@ksevendev/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1208 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { KSevenCodec } from './crypto/KSevenCodec.js';
6
+ import { EncryptedStateStore } from './storage/EncryptedStateStore.js';
7
+ import { KSevenWebSdkError } from './types.js';
8
+ export * from './types.js';
9
+ export { KSevenCodec, EncryptedStateStore };
10
+ export class KSevenWebLicenseSdk {
11
+ apiBaseUrl;
12
+ stateFilePath;
13
+ defaultPlatform;
14
+ timeoutMs;
15
+ allowInsecureLocalHttp;
16
+ useEncryptedTransport;
17
+ requireSealedTransport;
18
+ pinnedRootPublicKeyPem;
19
+ verifyResponseSignatures;
20
+ pinnedPublicKeys;
21
+ configuredClientPublicKeyPem;
22
+ configuredClientPrivateKeyPem;
23
+ stateStore;
24
+ wireSession = null;
25
+ discoveredTrustedKeys = {};
26
+ constructor(config) {
27
+ if (!config?.apiBaseUrl) {
28
+ throw new KSevenWebSdkError(400, 'INVALID_CONFIG', 'apiBaseUrl é obrigatório.');
29
+ }
30
+ this.apiBaseUrl = config.apiBaseUrl.replace(/\/+$/, '');
31
+ this.allowInsecureLocalHttp = Boolean(config.allowInsecureLocalHttp);
32
+ this.assertAllowedEndpointUrl(this.apiBaseUrl);
33
+ this.stateFilePath = path.resolve(config.stateFilePath || path.join(process.cwd(), '.kseven-web-license.dat'));
34
+ this.defaultPlatform = config.platform || 'nodejs';
35
+ this.timeoutMs = Math.max(1000, Number(config.timeoutMs || 15000));
36
+ this.useEncryptedTransport = config.useEncryptedTransport !== false;
37
+ this.requireSealedTransport = Boolean(config.requireSealedTransport);
38
+ this.pinnedRootPublicKeyPem = config.pinnedRootPublicKeyPem?.trim() || undefined;
39
+ this.verifyResponseSignatures = config.verifyResponseSignatures !== false;
40
+ this.pinnedPublicKeys = { ...(config.pinnedPublicKeys || {}) };
41
+ this.configuredClientPublicKeyPem = config.clientPublicKeyPem?.trim() || undefined;
42
+ this.configuredClientPrivateKeyPem = config.clientPrivateKeyPem?.trim() || undefined;
43
+ this.stateStore =
44
+ config.stateStore || new EncryptedStateStore(this.stateFilePath, config.stateSecret);
45
+ }
46
+ assertAllowedEndpointUrl(rawUrl) {
47
+ let parsed;
48
+ try {
49
+ parsed = new URL(rawUrl);
50
+ }
51
+ catch {
52
+ throw new KSevenWebSdkError(400, 'INVALID_URL', 'URL de API/pacote inválida.');
53
+ }
54
+ if (parsed.protocol === 'https:') {
55
+ return parsed;
56
+ }
57
+ if (parsed.protocol === 'http:' &&
58
+ this.allowInsecureLocalHttp &&
59
+ (parsed.hostname === '127.0.0.1' || parsed.hostname === 'localhost' || parsed.hostname === '::1')) {
60
+ return parsed;
61
+ }
62
+ throw new KSevenWebSdkError(400, 'INSECURE_URL', `Somente URLs HTTPS são permitidas em produção (recebido: ${parsed.protocol}//${parsed.hostname}).`);
63
+ }
64
+ resolveSafeChildPath(baseDir, relativeTarget) {
65
+ const resolvedBase = path.resolve(baseDir);
66
+ const cleanedName = path.basename(relativeTarget);
67
+ if (!cleanedName ||
68
+ cleanedName === '.' ||
69
+ cleanedName === '..' ||
70
+ cleanedName !== relativeTarget.replace(/^[/\\]+/, '')) {
71
+ throw new KSevenWebSdkError(400, 'INVALID_FILE_NAME', 'Nome de arquivo inválido ou fora do diretório permitido.');
72
+ }
73
+ const resolvedTarget = path.resolve(resolvedBase, cleanedName);
74
+ if (!resolvedTarget.startsWith(resolvedBase + path.sep)) {
75
+ throw new KSevenWebSdkError(400, 'PATH_TRAVERSAL_BLOCKED', 'Destino fora do diretório base autorizado.');
76
+ }
77
+ return resolvedTarget;
78
+ }
79
+ async readState() {
80
+ return this.stateStore.read();
81
+ }
82
+ async writeState(state) {
83
+ await this.stateStore.write(state);
84
+ }
85
+ async requireState() {
86
+ const state = await this.readState();
87
+ if (!state?.installationCredential) {
88
+ throw new KSevenWebSdkError(401, 'NOT_INSTALLED', 'Instalação web não configurada localmente. Execute install() primeiro.');
89
+ }
90
+ return state;
91
+ }
92
+ /**
93
+ * Obtém bundle de chaves públicas Ed25519 (ativa + secundárias + raiz) em `/keys` (fallback `/releases/public-key`)
94
+ * e valida cadeia `rootProof` / `transitionProof` contra `pinnedRootPublicKeyPem` quando configurada.
95
+ */
96
+ async fetchPublicKeysMap(forceRefresh = false) {
97
+ if (!forceRefresh && Object.keys(this.discoveredTrustedKeys).length > 0) {
98
+ return {
99
+ ...this.discoveredTrustedKeys,
100
+ ...this.pinnedPublicKeys
101
+ };
102
+ }
103
+ const persisted = await this.readState().catch(() => null);
104
+ const rootPin = this.pinnedRootPublicKeyPem || persisted?.pinnedRootPublicKeyPem;
105
+ const endpoints = ['/keys', '/releases/public-key'];
106
+ let lastError = null;
107
+ for (const ep of endpoints) {
108
+ const url = `${this.apiBaseUrl}/api/web/license/v1${ep}`;
109
+ this.assertAllowedEndpointUrl(url);
110
+ const controller = new AbortController();
111
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
112
+ try {
113
+ const res = await fetch(url, {
114
+ method: 'GET',
115
+ headers: { Accept: 'application/json' },
116
+ signal: controller.signal
117
+ });
118
+ if (!res.ok)
119
+ continue;
120
+ const bundle = (await res.json().catch(() => null));
121
+ if (!bundle)
122
+ continue;
123
+ const resolved = KSevenCodec.resolveTrustedKeysFromBundle(bundle, rootPin, this.pinnedPublicKeys);
124
+ if (Object.keys(resolved).length === 0 && rootPin) {
125
+ throw new KSevenWebSdkError(403, 'NO_TRUSTED_WEB_KEYS', 'Nenhuma chave operacional publicada pelo servidor foi validada pela chave raiz pinada.');
126
+ }
127
+ this.discoveredTrustedKeys = resolved;
128
+ return {
129
+ ...resolved,
130
+ ...this.pinnedPublicKeys
131
+ };
132
+ }
133
+ catch (err) {
134
+ if (err instanceof KSevenWebSdkError) {
135
+ throw err;
136
+ }
137
+ lastError = err;
138
+ }
139
+ finally {
140
+ clearTimeout(timer);
141
+ }
142
+ }
143
+ if (rootPin && Object.keys(this.pinnedPublicKeys).length === 0) {
144
+ throw new KSevenWebSdkError(503, 'KEY_DISCOVERY_FAILED', `Não foi possível obter e verificar o bundle de chaves Web Ed25519: ${lastError?.message || 'erro de rede'}`);
145
+ }
146
+ return {
147
+ ...(persisted?.pinnedPublicKeys || {}),
148
+ ...this.discoveredTrustedKeys,
149
+ ...this.pinnedPublicKeys
150
+ };
151
+ }
152
+ async verifySignedEnvelopeWithRefresh(params) {
153
+ if (!this.verifyResponseSignatures)
154
+ return;
155
+ if (!params.data || typeof params.data !== 'object')
156
+ return;
157
+ const hasEnvelope = Boolean(params.data.signatureEnvelope);
158
+ if (!hasEnvelope) {
159
+ const isUnsignedInfraError = params.httpStatus >= 400 &&
160
+ (params.httpStatus === 503 ||
161
+ params.httpStatus === 429 ||
162
+ params.httpStatus >= 500 ||
163
+ Boolean(params.data.code) ||
164
+ params.data.success === false);
165
+ if (this.pinnedRootPublicKeyPem && !isUnsignedInfraError) {
166
+ throw new KSevenWebSdkError(403, 'MISSING_RESPONSE_SIGNATURE', 'Servidor respondeu sem signatureEnvelope Ed25519 exigido pela política de chave raiz pinada.');
167
+ }
168
+ return;
169
+ }
170
+ let trustedKeys = await this.fetchPublicKeysMap(false);
171
+ const keyId = String(params.data.signatureEnvelope?.keyId || '');
172
+ if (keyId && !trustedKeys[keyId]) {
173
+ // Atualiza bundle de chaves para suportar rotação ativa -> secundária sem downtime
174
+ trustedKeys = await this.fetchPublicKeysMap(true);
175
+ }
176
+ KSevenCodec.verifyRuntimeResponseSignature({
177
+ responseBody: params.data,
178
+ trustedKeys,
179
+ expectedMethod: params.method,
180
+ expectedPath: params.fullPath,
181
+ expectedHttpStatus: params.httpStatus,
182
+ expectedNonce: params.expectedNonce
183
+ });
184
+ }
185
+ async ensureWireSession() {
186
+ if (!this.useEncryptedTransport && !this.requireSealedTransport)
187
+ return null;
188
+ if (this.wireSession && Date.now() < this.wireSession.expiresAtMs) {
189
+ return this.wireSession;
190
+ }
191
+ const { clientPublicKeySpkiBase64, privateKey } = KSevenCodec.createClientEphemeralKeyPair();
192
+ const url = `${this.apiBaseUrl}/api/web/license/v1/session-key`;
193
+ this.assertAllowedEndpointUrl(url);
194
+ const timestamp = new Date().toISOString();
195
+ const nonce = crypto.randomBytes(16).toString('hex');
196
+ const controller = new AbortController();
197
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
198
+ try {
199
+ const res = await fetch(url, {
200
+ method: 'POST',
201
+ headers: {
202
+ Accept: 'application/json',
203
+ 'Content-Type': 'application/json',
204
+ 'x-k7-web-timestamp': timestamp,
205
+ 'x-k7-web-nonce': nonce
206
+ },
207
+ body: JSON.stringify({ clientPublicKeySpkiBase64 }),
208
+ signal: controller.signal
209
+ });
210
+ const data = await res.json().catch(() => null);
211
+ if (!res.ok) {
212
+ const errCode = String(data?.code || (res.status === 503 ? 'REDIS_UNAVAILABLE' : 'SEALED_TRANSPORT_UNAVAILABLE'));
213
+ const errMsg = String(data?.message || `Falha ao negociar sessão criptográfica ECDH (HTTP ${res.status}).`);
214
+ const requestId = typeof data?.requestId === 'string' ? data.requestId : undefined;
215
+ if (this.requireSealedTransport || res.status === 503 || res.status === 429 || res.status >= 500) {
216
+ throw new KSevenWebSdkError(res.status, errCode, errMsg, requestId, data || undefined);
217
+ }
218
+ return null;
219
+ }
220
+ if (!data?.sessionId || !data?.serverPublicKeySpkiBase64) {
221
+ if (this.requireSealedTransport) {
222
+ throw new KSevenWebSdkError(502, 'INVALID_SESSION_KEY_RESPONSE', 'Resposta incompleta do servidor em /session-key.');
223
+ }
224
+ return null;
225
+ }
226
+ if (this.verifyResponseSignatures) {
227
+ let trustedKeys = await this.fetchPublicKeysMap(false);
228
+ const hsKeyId = String(data.handshakeSignature?.keyId || '');
229
+ if (hsKeyId && !trustedKeys[hsKeyId]) {
230
+ trustedKeys = await this.fetchPublicKeysMap(true);
231
+ }
232
+ if (data.handshakeSignature || this.pinnedRootPublicKeyPem) {
233
+ KSevenCodec.verifyEcdhHandshakeSignature({
234
+ sessionId: String(data.sessionId),
235
+ serverPublicKeySpkiBase64: String(data.serverPublicKeySpkiBase64),
236
+ fingerprintSha256: String(data.fingerprintSha256 || ''),
237
+ clientPublicKeySpkiBase64,
238
+ expiresInSeconds: Number(data.expiresInSeconds || 1800),
239
+ expectedNonce: nonce,
240
+ handshakeSignature: data.handshakeSignature,
241
+ trustedKeys
242
+ });
243
+ }
244
+ await this.verifySignedEnvelopeWithRefresh({
245
+ data,
246
+ method: 'POST',
247
+ fullPath: '/api/web/license/v1/session-key',
248
+ httpStatus: res.status,
249
+ expectedNonce: nonce
250
+ });
251
+ }
252
+ this.wireSession = KSevenCodec.deriveWireSessionFromServerResponse(privateKey, String(data.sessionId), String(data.serverPublicKeySpkiBase64), Number(data.expiresInSeconds || 1800));
253
+ return this.wireSession;
254
+ }
255
+ catch (err) {
256
+ if (err instanceof KSevenWebSdkError) {
257
+ throw err;
258
+ }
259
+ if (this.requireSealedTransport) {
260
+ throw new KSevenWebSdkError(503, 'SEALED_TRANSPORT_UNAVAILABLE', 'Não foi possível estabelecer sessão selada k7seal.v1 obrigatória.');
261
+ }
262
+ return null;
263
+ }
264
+ finally {
265
+ clearTimeout(timer);
266
+ }
267
+ }
268
+ resolveClientSigningContext(state) {
269
+ const clientPrivateKeyPem = state?.clientPrivateKeyPem || this.configuredClientPrivateKeyPem;
270
+ const installationId = state?.installationId;
271
+ if (clientPrivateKeyPem && installationId) {
272
+ return { installationId, clientPrivateKeyPem };
273
+ }
274
+ return {};
275
+ }
276
+ async apiRequest(method, endpointPath, opts) {
277
+ const url = `${this.apiBaseUrl}/api/web/license/v1${endpointPath}`;
278
+ this.assertAllowedEndpointUrl(url);
279
+ const fullPath = `/api/web/license/v1${endpointPath.split('?')[0]}`;
280
+ const timestamp = new Date().toISOString();
281
+ const nonce = crypto.randomBytes(16).toString('hex');
282
+ const session = await this.ensureWireSession();
283
+ const aad = session
284
+ ? `${method}:${fullPath}:${session.sessionId}:${nonce}`
285
+ : `${method}:${fullPath}`;
286
+ const headers = {
287
+ Accept: 'application/json',
288
+ 'x-k7-web-timestamp': timestamp,
289
+ 'x-k7-web-nonce': nonce,
290
+ ...(opts?.headers || {})
291
+ };
292
+ if (opts?.credential) {
293
+ headers['x-web-installation-credential'] = opts.credential;
294
+ }
295
+ if (opts?.clientPrivateKeyPem && opts?.installationId) {
296
+ headers['x-k7-web-client-signature'] = KSevenCodec.signClientRequest({
297
+ clientPrivateKeyPem: opts.clientPrivateKeyPem,
298
+ method,
299
+ path: fullPath,
300
+ timestamp,
301
+ nonce,
302
+ installationId: opts.installationId,
303
+ body: opts.body
304
+ });
305
+ }
306
+ let requestBodyStr;
307
+ if (session) {
308
+ headers['x-k7-web-session'] = session.sessionId;
309
+ headers['x-k7-web-cipher'] = 'aes-256-gcm';
310
+ if (opts?.body !== undefined) {
311
+ headers['Content-Type'] = 'application/json';
312
+ requestBodyStr = JSON.stringify({
313
+ sealed: true,
314
+ sealedEnvelope: KSevenCodec.sealWirePayload(opts.body, session.aesKey, aad)
315
+ });
316
+ }
317
+ }
318
+ else if (opts?.body !== undefined) {
319
+ headers['Content-Type'] = 'application/json';
320
+ requestBodyStr = JSON.stringify(opts.body);
321
+ }
322
+ const controller = new AbortController();
323
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
324
+ try {
325
+ const response = await fetch(url, {
326
+ method,
327
+ headers,
328
+ body: requestBodyStr,
329
+ signal: controller.signal
330
+ });
331
+ if (response.status === 428 && session && opts?.retryOnSessionExpired !== false) {
332
+ this.wireSession = null;
333
+ return this.apiRequest(method, endpointPath, {
334
+ ...opts,
335
+ retryOnSessionExpired: false
336
+ });
337
+ }
338
+ const rawData = await response.json().catch(() => ({}));
339
+ const data = session && rawData?.sealed && typeof rawData?.sealedEnvelope === 'string'
340
+ ? KSevenCodec.unsealWirePayload(rawData.sealedEnvelope, session.aesKey, aad)
341
+ : rawData;
342
+ if (!opts?.skipSignatureVerify && this.verifyResponseSignatures) {
343
+ await this.verifySignedEnvelopeWithRefresh({
344
+ data,
345
+ method,
346
+ fullPath,
347
+ httpStatus: response.status,
348
+ expectedNonce: nonce
349
+ });
350
+ }
351
+ if (!response.ok) {
352
+ const requestId = typeof data?.requestId === 'string' ? data.requestId : undefined;
353
+ const details = data && typeof data === 'object' ? { ...data } : undefined;
354
+ if (details)
355
+ delete details.signatureEnvelope;
356
+ throw new KSevenWebSdkError(response.status, String(data?.code || `HTTP_${response.status}`), String(data?.message || `Erro HTTP ${response.status} em ${endpointPath}`), requestId, details);
357
+ }
358
+ return data;
359
+ }
360
+ catch (err) {
361
+ if (err instanceof KSevenWebSdkError)
362
+ throw err;
363
+ throw new KSevenWebSdkError(503, 'NETWORK_ERROR', err?.name === 'AbortError'
364
+ ? `Tempo limite excedido ao contatar API de licenças (${this.timeoutMs}ms).`
365
+ : `Falha de comunicação com API de licenças: ${err?.message || 'erro desconhecido'}`);
366
+ }
367
+ finally {
368
+ clearTimeout(timer);
369
+ }
370
+ }
371
+ async createDomainChallenge(params) {
372
+ return this.apiRequest('POST', '/domain-challenges', { body: params });
373
+ }
374
+ async verifyDomainChallenge(challengeId, licenseKey) {
375
+ return this.apiRequest('POST', `/domain-challenges/${encodeURIComponent(challengeId)}/verify`, {
376
+ body: licenseKey ? { licenseKey } : {}
377
+ });
378
+ }
379
+ async install(options) {
380
+ const platform = options.platform || this.defaultPlatform;
381
+ const environment = options.environment || 'production';
382
+ const fingerprint = options.instanceFingerprint ||
383
+ crypto
384
+ .createHash('sha256')
385
+ .update(`${os.hostname()}:${platform}:${options.domain}`)
386
+ .digest('hex')
387
+ .slice(0, 32);
388
+ const idempotencyKey = options.idempotencyKey || `install-${platform}-${fingerprint}`;
389
+ let clientPublicKeyPem = options.clientPublicKeyPem || this.configuredClientPublicKeyPem;
390
+ let clientPrivateKeyPem = options.clientPrivateKeyPem || this.configuredClientPrivateKeyPem;
391
+ if (options.generateClientKeyPair && !clientPublicKeyPem && !clientPrivateKeyPem) {
392
+ const pair = KSevenCodec.generateClientEd25519KeyPair();
393
+ clientPublicKeyPem = pair.clientPublicKeyPem;
394
+ clientPrivateKeyPem = pair.clientPrivateKeyPem;
395
+ }
396
+ const requireSealed = options.requireSealedTransport !== undefined
397
+ ? options.requireSealedTransport
398
+ : this.requireSealedTransport;
399
+ const res = await this.apiRequest('POST', '/activate', {
400
+ body: {
401
+ licenseKey: options.licenseKey,
402
+ domain: options.domain,
403
+ platform,
404
+ appVersion: options.appVersion,
405
+ environment,
406
+ instanceFingerprint: fingerprint,
407
+ idempotencyKey,
408
+ ...(clientPublicKeyPem ? { clientPublicKeyPem } : {}),
409
+ ...(requireSealed ? { requireSealedTransport: true } : {}),
410
+ protocolVersion: '1.1'
411
+ }
412
+ });
413
+ const nowIso = new Date().toISOString();
414
+ const publicKeys = await this.fetchPublicKeysMap(true).catch(() => ({ ...this.pinnedPublicKeys }));
415
+ const graceUntil = res?.entitlement?.offlineValidation?.graceUntil || res?.entitlement?.graceUntil || null;
416
+ const nextState = {
417
+ apiBaseUrl: this.apiBaseUrl,
418
+ installationId: res.installationId,
419
+ installationCredential: res.installationCredential,
420
+ credentialPrefix: res.credentialPrefix,
421
+ credentialVersion: res.credentialVersion,
422
+ domain: res.domain,
423
+ platform: res.platform,
424
+ appVersion: res.appVersion,
425
+ environment,
426
+ instanceFingerprint: fingerprint,
427
+ installedAt: nowIso,
428
+ updatedAt: nowIso,
429
+ lastValidatedAt: nowIso,
430
+ graceUntil,
431
+ lastSignedEntitlement: res.entitlement || null,
432
+ lastSignedValidationResponse: res.signatureEnvelope ? res : null,
433
+ pinnedPublicKeys: publicKeys,
434
+ ...(this.pinnedRootPublicKeyPem ? { pinnedRootPublicKeyPem: this.pinnedRootPublicKeyPem } : {}),
435
+ ...(clientPublicKeyPem ? { clientPublicKeyPem } : {}),
436
+ ...(clientPrivateKeyPem ? { clientPrivateKeyPem } : {}),
437
+ ...(requireSealed ? { requireSealedTransport: true } : {}),
438
+ protocolVersion: '1.1'
439
+ };
440
+ await this.writeState(nextState);
441
+ return {
442
+ installed: true,
443
+ installationId: nextState.installationId,
444
+ domain: nextState.domain,
445
+ platform: nextState.platform,
446
+ appVersion: nextState.appVersion,
447
+ idempotentReplay: Boolean(res.idempotentReplay),
448
+ encryptedTransport: Boolean(this.wireSession),
449
+ clientKeyRegistered: Boolean(clientPublicKeyPem),
450
+ entitlement: res.entitlement,
451
+ signatureEnvelope: res.signatureEnvelope
452
+ };
453
+ }
454
+ async validate(appVersion, options = {}) {
455
+ const state = await this.requireState();
456
+ const signing = this.resolveClientSigningContext(state);
457
+ try {
458
+ const res = await this.apiRequest('POST', '/validate', {
459
+ credential: state.installationCredential,
460
+ ...signing,
461
+ body: {
462
+ domain: state.domain,
463
+ ...(appVersion ? { appVersion } : {})
464
+ }
465
+ });
466
+ const nowIso = new Date().toISOString();
467
+ const graceUntil = res?.entitlement?.offlineValidation?.graceUntil || res?.entitlement?.graceUntil || null;
468
+ const mergedKeys = {
469
+ ...(state.pinnedPublicKeys || {}),
470
+ ...this.discoveredTrustedKeys,
471
+ ...this.pinnedPublicKeys
472
+ };
473
+ await this.writeState({
474
+ ...state,
475
+ appVersion: appVersion || state.appVersion,
476
+ updatedAt: nowIso,
477
+ lastValidatedAt: nowIso,
478
+ graceUntil,
479
+ lastSignedEntitlement: res?.entitlement || state.lastSignedEntitlement || null,
480
+ lastSignedValidationResponse: res?.signatureEnvelope
481
+ ? res
482
+ : state.lastSignedValidationResponse || null,
483
+ pinnedPublicKeys: mergedKeys
484
+ });
485
+ return res;
486
+ }
487
+ catch (err) {
488
+ const isTransientOffline = err instanceof KSevenWebSdkError &&
489
+ (err.code === 'NETWORK_ERROR' || err.statusCode === 503 || err.statusCode === 502 || err.statusCode === 504);
490
+ if (options.allowOfflineGrace && isTransientOffline) {
491
+ return this.validateOffline(options.nowMs);
492
+ }
493
+ throw err;
494
+ }
495
+ }
496
+ /**
497
+ * Valida offline o último comprovante Ed25519 assinado em cache local criptografado,
498
+ * respeitando rigorosamente `graceUntil` e bloqueando status `REVOKED`/`SUSPENDED` ou adulterações.
499
+ */
500
+ async validateOffline(nowMs = Date.now()) {
501
+ const state = await this.requireState();
502
+ const trustedKeys = {
503
+ ...(state.pinnedPublicKeys || {}),
504
+ ...this.discoveredTrustedKeys,
505
+ ...this.pinnedPublicKeys
506
+ };
507
+ const verified = KSevenCodec.verifyCachedOfflineEntitlement({
508
+ cachedResponse: state.lastSignedValidationResponse,
509
+ trustedKeys,
510
+ expectedInstallationId: state.installationId,
511
+ expectedDomain: state.domain,
512
+ nowMs
513
+ });
514
+ return {
515
+ valid: true,
516
+ offline: true,
517
+ inGracePeriod: true,
518
+ graceUntil: verified.graceUntil,
519
+ lastValidatedAt: state.lastValidatedAt || verified.issuedAt || null,
520
+ installationId: state.installationId,
521
+ domain: state.domain,
522
+ entitlement: verified.entitlement,
523
+ signatureKeyId: verified.keyId
524
+ };
525
+ }
526
+ /**
527
+ * Solicita transferência/troca de servidor da instalação atual para outro domínio verificado
528
+ * da mesma licença sem exigir nova compra. Atualiza ou limpa o estado cifrado local conforme resultado.
529
+ */
530
+ async transferInstallation(options) {
531
+ const state = await this.requireState();
532
+ const signing = this.resolveClientSigningContext(state);
533
+ const body = {
534
+ toDomain: options.toDomain,
535
+ ...(options.reason ? { reason: options.reason } : {}),
536
+ ...(options.immediateActivate !== undefined ? { immediateActivate: options.immediateActivate } : {}),
537
+ ...(options.platform ? { platform: options.platform } : {}),
538
+ ...(options.appVersion ? { appVersion: options.appVersion } : {}),
539
+ ...(options.instanceFingerprint ? { instanceFingerprint: options.instanceFingerprint } : {}),
540
+ ...(options.clientPublicKeyPem ? { clientPublicKeyPem: options.clientPublicKeyPem } : {}),
541
+ ...(options.requireSealedTransport !== undefined
542
+ ? { requireSealedTransport: options.requireSealedTransport }
543
+ : {})
544
+ };
545
+ const res = await this.apiRequest('POST', '/installations/transfer', {
546
+ credential: state.installationCredential,
547
+ ...signing,
548
+ body
549
+ });
550
+ const nowIso = new Date().toISOString();
551
+ if (!res.pendingReview && res.newInstallation?.installationCredential) {
552
+ const graceUntil = res?.entitlement?.offlineValidation?.graceUntil || res?.entitlement?.graceUntil || null;
553
+ await this.writeState({
554
+ ...state,
555
+ installationId: res.newInstallation.installationId,
556
+ installationCredential: res.newInstallation.installationCredential,
557
+ credentialPrefix: res.newInstallation.credentialPrefix,
558
+ credentialVersion: res.newInstallation.credentialVersion,
559
+ domain: res.newInstallation.domain || options.toDomain,
560
+ platform: (res.newInstallation.platform || state.platform),
561
+ appVersion: res.newInstallation.appVersion || state.appVersion,
562
+ updatedAt: nowIso,
563
+ lastValidatedAt: nowIso,
564
+ graceUntil,
565
+ lastSignedEntitlement: res.entitlement || null,
566
+ lastSignedValidationResponse: res.signatureEnvelope ? res : null
567
+ });
568
+ }
569
+ else if (!res.pendingReview && res.sourceRevoked) {
570
+ await this.writeState(null);
571
+ }
572
+ return res;
573
+ }
574
+ async entitlements() {
575
+ const state = await this.requireState();
576
+ const signing = this.resolveClientSigningContext(state);
577
+ return this.apiRequest('GET', '/entitlements', {
578
+ credential: state.installationCredential,
579
+ ...signing
580
+ });
581
+ }
582
+ async acquireLease(ttlSeconds = 180, idempotencyKey) {
583
+ const state = await this.requireState();
584
+ const signing = this.resolveClientSigningContext(state);
585
+ return this.apiRequest('POST', '/leases/acquire', {
586
+ credential: state.installationCredential,
587
+ ...signing,
588
+ body: {
589
+ ttlSeconds,
590
+ ...(idempotencyKey ? { idempotencyKey } : {})
591
+ }
592
+ });
593
+ }
594
+ async heartbeatLease(leaseId, leaseToken) {
595
+ const state = await this.requireState();
596
+ const signing = this.resolveClientSigningContext(state);
597
+ return this.apiRequest('POST', `/leases/${encodeURIComponent(leaseId)}/heartbeat`, {
598
+ credential: state.installationCredential,
599
+ ...signing,
600
+ body: leaseToken ? { leaseToken } : {}
601
+ });
602
+ }
603
+ async releaseLease(leaseId) {
604
+ const state = await this.requireState();
605
+ const signing = this.resolveClientSigningContext(state);
606
+ return this.apiRequest('POST', `/leases/${encodeURIComponent(leaseId)}/release`, {
607
+ credential: state.installationCredential,
608
+ ...signing,
609
+ body: {}
610
+ });
611
+ }
612
+ async listCompatibleReleases(options = {}) {
613
+ const state = await this.requireState();
614
+ const signing = this.resolveClientSigningContext(state);
615
+ const params = new URLSearchParams();
616
+ if (options.channel)
617
+ params.set('channel', options.channel === 'beta' ? 'beta' : 'stable');
618
+ if (options.currentVersion || state.appVersion) {
619
+ params.set('currentVersion', options.currentVersion || state.appVersion);
620
+ }
621
+ if (options.releaseKind)
622
+ params.set('releaseKind', options.releaseKind);
623
+ const qs = params.toString();
624
+ return this.apiRequest('GET', `/updates/releases${qs ? `?${qs}` : ''}`, {
625
+ credential: state.installationCredential,
626
+ ...signing
627
+ });
628
+ }
629
+ async checkVersion(options = {}) {
630
+ const state = await this.requireState();
631
+ const signing = this.resolveClientSigningContext(state);
632
+ const channel = options.channel === 'beta' ? 'beta' : 'stable';
633
+ const currentVersion = options.currentVersion || state.appVersion;
634
+ const qsParams = new URLSearchParams({
635
+ channel,
636
+ currentVersion
637
+ });
638
+ if (options.releaseKind) {
639
+ qsParams.set('releaseKind', options.releaseKind);
640
+ }
641
+ const res = await this.apiRequest('GET', `/updates/check?${qsParams.toString()}`, {
642
+ credential: state.installationCredential,
643
+ ...signing
644
+ });
645
+ if (!res.latestRelease) {
646
+ return {
647
+ updateAvailable: false,
648
+ channel,
649
+ currentVersion,
650
+ latestRelease: null,
651
+ availableRollbacks: Array.isArray(res.availableRollbacks) ? res.availableRollbacks : [],
652
+ updatesActive: res.updatesActive,
653
+ updatesExpiresAt: res.updatesExpiresAt ?? null,
654
+ signatureVerified: true
655
+ };
656
+ }
657
+ const rel = res.latestRelease;
658
+ const keysMap = await this.fetchPublicKeysMap(false).catch(() => ({
659
+ ...(state.pinnedPublicKeys || {}),
660
+ ...this.pinnedPublicKeys
661
+ }));
662
+ let trustedPem = this.pinnedPublicKeys[rel.signingKeyId] || keysMap[rel.signingKeyId];
663
+ if (!trustedPem) {
664
+ const refreshed = await this.fetchPublicKeysMap(true).catch(() => ({}));
665
+ trustedPem = this.pinnedPublicKeys[rel.signingKeyId] || refreshed[rel.signingKeyId];
666
+ }
667
+ if (!trustedPem && !this.pinnedRootPublicKeyPem) {
668
+ trustedPem = rel.publicKeyPem;
669
+ }
670
+ if (!trustedPem) {
671
+ throw new KSevenWebSdkError(403, 'UNKNOWN_SIGNING_KEY', `Chave pública Ed25519 confiável não encontrada para signingKeyId=${rel.signingKeyId}.`);
672
+ }
673
+ const manifest = KSevenCodec.verifyEd25519Manifest({
674
+ manifestJson: rel.manifestJson,
675
+ manifestSignature: rel.manifestSignature,
676
+ signingKeyId: rel.signingKeyId,
677
+ publicKeyPem: trustedPem
678
+ });
679
+ if (manifest.version !== rel.version ||
680
+ manifest.packageSha256 !== rel.packageSha256 ||
681
+ manifest.channel !== rel.channel) {
682
+ throw new KSevenWebSdkError(403, 'MANIFEST_METADATA_MISMATCH', 'Metadados do manifesto assinado divergem da resposta de versão.');
683
+ }
684
+ return {
685
+ updateAvailable: Boolean(res.updateAvailable),
686
+ channel,
687
+ currentVersion: res.currentVersion || currentVersion,
688
+ latestRelease: rel,
689
+ availableRollbacks: Array.isArray(res.availableRollbacks) ? res.availableRollbacks : [],
690
+ updatesActive: res.updatesActive,
691
+ updatesExpiresAt: res.updatesExpiresAt ?? null,
692
+ signatureVerified: true
693
+ };
694
+ }
695
+ async downloadAndApplyRelease(state, rel, options) {
696
+ const signing = this.resolveClientSigningContext(state);
697
+ const grant = await this.apiRequest('POST', `/updates/${rel.releaseId}/download-grants`, {
698
+ credential: state.installationCredential,
699
+ ...signing,
700
+ body: { maxDownloads: 1 }
701
+ });
702
+ const consumed = await this.apiRequest('GET', `/updates/download/${encodeURIComponent(grant.grantId)}`, {
703
+ headers: {
704
+ 'x-download-grant-token': grant.grantToken
705
+ }
706
+ });
707
+ const keysMap = await this.fetchPublicKeysMap(false).catch(() => state.pinnedPublicKeys || {});
708
+ let trustedPem = this.pinnedPublicKeys[consumed.signingKeyId] || keysMap[consumed.signingKeyId];
709
+ if (!trustedPem) {
710
+ const refreshed = await this.fetchPublicKeysMap(true).catch(() => ({}));
711
+ trustedPem = this.pinnedPublicKeys[consumed.signingKeyId] || refreshed[consumed.signingKeyId];
712
+ }
713
+ if (!trustedPem && !this.pinnedRootPublicKeyPem) {
714
+ trustedPem = rel.publicKeyPem;
715
+ }
716
+ if (!trustedPem) {
717
+ throw new KSevenWebSdkError(403, 'UNKNOWN_SIGNING_KEY', 'Chave pública Ed25519 confiável ausente ao consumir grant.');
718
+ }
719
+ const verifiedManifest = KSevenCodec.verifyEd25519Manifest({
720
+ manifestJson: consumed.manifestJson,
721
+ manifestSignature: consumed.manifestSignature,
722
+ signingKeyId: consumed.signingKeyId,
723
+ publicKeyPem: trustedPem
724
+ });
725
+ const downloadUrl = String(consumed.packageUrl || '').startsWith('/api/')
726
+ ? `${this.apiBaseUrl}${consumed.packageUrl}`
727
+ : String(consumed.packageUrl || '');
728
+ this.assertAllowedEndpointUrl(downloadUrl);
729
+ const controller = new AbortController();
730
+ const timer = setTimeout(() => controller.abort(), Math.max(this.timeoutMs, 30000));
731
+ let packageBuffer;
732
+ try {
733
+ const pkgRes = await fetch(downloadUrl, { signal: controller.signal });
734
+ if (!pkgRes.ok) {
735
+ throw new KSevenWebSdkError(pkgRes.status, 'PACKAGE_DOWNLOAD_FAILED', `Falha ao baixar pacote da release v${rel.version} (HTTP ${pkgRes.status}).`);
736
+ }
737
+ packageBuffer = Buffer.from(await pkgRes.arrayBuffer());
738
+ }
739
+ finally {
740
+ clearTimeout(timer);
741
+ }
742
+ const actualSha256 = crypto.createHash('sha256').update(packageBuffer).digest('hex');
743
+ if (actualSha256 !== verifiedManifest.packageSha256.toLowerCase()) {
744
+ throw new KSevenWebSdkError(422, 'PACKAGE_SHA256_MISMATCH', `Integridade do pacote comprometida: SHA-256 esperado ${verifiedManifest.packageSha256}, obtido ${actualSha256}.`);
745
+ }
746
+ if (verifiedManifest.packageSizeBytes > 0 &&
747
+ packageBuffer.length !== verifiedManifest.packageSizeBytes) {
748
+ throw new KSevenWebSdkError(422, 'PACKAGE_SIZE_MISMATCH', `Tamanho do pacote diverge do manifesto assinado (${packageBuffer.length} != ${verifiedManifest.packageSizeBytes}).`);
749
+ }
750
+ let savedFilePath;
751
+ if (options.destDir) {
752
+ const fileName = options.downloadFileName || `${rel.productSlug}-${rel.version}-${rel.platform}.pkg`;
753
+ savedFilePath = this.resolveSafeChildPath(options.destDir, fileName);
754
+ await fs.mkdir(path.resolve(options.destDir), { recursive: true });
755
+ const tmpPkgPath = `${savedFilePath}.tmp-${crypto.randomBytes(4).toString('hex')}`;
756
+ await fs.writeFile(tmpPkgPath, packageBuffer, { mode: 0o640 });
757
+ await fs.rename(tmpPkgPath, savedFilePath);
758
+ }
759
+ if (options.onVerifiedPackage) {
760
+ await options.onVerifiedPackage({
761
+ packageBuffer,
762
+ release: rel,
763
+ verifiedSha256: actualSha256
764
+ });
765
+ }
766
+ const previousVersion = state.appVersion;
767
+ await this.validate(rel.version);
768
+ return {
769
+ updated: true,
770
+ previousVersion,
771
+ currentVersion: rel.version,
772
+ release: rel,
773
+ savedFilePath,
774
+ verifiedSha256: actualSha256,
775
+ signatureVerified: true,
776
+ ...(options.rollback ? { rollback: true } : {})
777
+ };
778
+ }
779
+ async update(options = {}) {
780
+ const state = await this.requireState();
781
+ const check = await this.checkVersion({
782
+ channel: options.channel,
783
+ currentVersion: options.currentVersion,
784
+ releaseKind: options.releaseKind
785
+ });
786
+ if (!check.updateAvailable || !check.latestRelease) {
787
+ return {
788
+ updated: false,
789
+ previousVersion: state.appVersion,
790
+ currentVersion: state.appVersion,
791
+ release: check.latestRelease,
792
+ signatureVerified: check.signatureVerified
793
+ };
794
+ }
795
+ return this.downloadAndApplyRelease(state, check.latestRelease, options);
796
+ }
797
+ /**
798
+ * Reporta progresso e resultado de uma execução de auto-update para visibilidade no painel.
799
+ */
800
+ async reportAutoUpdateProgress(payload) {
801
+ const state = await this.requireState();
802
+ const signing = this.resolveClientSigningContext(state);
803
+ return this.apiRequest('POST', '/updates/auto-update/report', {
804
+ credential: state.installationCredential,
805
+ ...signing,
806
+ body: payload
807
+ });
808
+ }
809
+ async copyDirectorySafe(sourceDir, destDir, excludeNames) {
810
+ await fs.mkdir(destDir, { recursive: true });
811
+ const entries = await fs.readdir(sourceDir, { withFileTypes: true });
812
+ for (const entry of entries) {
813
+ if (excludeNames.has(entry.name))
814
+ continue;
815
+ if (entry.isSymbolicLink())
816
+ continue; // evita symlink traversal durante backup/restore
817
+ const srcPath = path.join(sourceDir, entry.name);
818
+ const dstPath = path.join(destDir, entry.name);
819
+ if (entry.isDirectory()) {
820
+ await this.copyDirectorySafe(srcPath, dstPath, excludeNames);
821
+ }
822
+ else if (entry.isFile()) {
823
+ await fs.copyFile(srcPath, dstPath);
824
+ }
825
+ }
826
+ }
827
+ async restoreDirectoryFromBackup(backupDir, targetDir, preserveNames) {
828
+ // Limpa arquivos potencialmente parciais no targetDir (exceto preservados)
829
+ const currentEntries = await fs.readdir(targetDir, { withFileTypes: true }).catch(() => []);
830
+ for (const entry of currentEntries) {
831
+ if (preserveNames.has(entry.name))
832
+ continue;
833
+ const fullPath = path.join(targetDir, entry.name);
834
+ await fs.rm(fullPath, { recursive: true, force: true });
835
+ }
836
+ // Restaura estado exato do backup
837
+ await this.copyDirectorySafe(backupDir, targetDir, preserveNames);
838
+ }
839
+ /**
840
+ * Executa atualização Web automática e transacional:
841
+ * 1. Consulta exclusivamente releases compatíveis e autorizadas na sequência contínua.
842
+ * 2. Baixa para área temporária, valida assinatura Ed25519, canal, versão, dependências e SHA-256.
843
+ * 3. Cria backup completo do diretório alvo antes de qualquer modificação.
844
+ * 4. Aplica pacote e executa migrações declaradas em ordem.
845
+ * 5. Em qualquer falha, aborta e restaura o estado anterior integralmente (rollback limpo).
846
+ */
847
+ async autoUpdate(options) {
848
+ const state = await this.requireState();
849
+ const runUid = `aur_${crypto.randomBytes(10).toString('hex')}`;
850
+ const channel = options.channel === 'beta' ? 'beta' : 'stable';
851
+ const previousVersion = options.currentVersion || state.appVersion;
852
+ const shouldReport = options.reportProgress !== false;
853
+ const safeReport = async (patch) => {
854
+ if (!shouldReport)
855
+ return;
856
+ await this.reportAutoUpdateProgress({
857
+ runUid,
858
+ channel,
859
+ fromVersion: previousVersion,
860
+ ...patch
861
+ }).catch(() => { });
862
+ };
863
+ const check = await this.checkVersion({
864
+ channel,
865
+ currentVersion: previousVersion,
866
+ releaseKind: options.releaseKind
867
+ });
868
+ if (!check.updateAvailable || !check.latestRelease) {
869
+ return {
870
+ runUid,
871
+ updated: false,
872
+ status: 'UP_TO_DATE',
873
+ previousVersion,
874
+ currentVersion: previousVersion,
875
+ targetVersion: null,
876
+ release: check.latestRelease,
877
+ signatureVerified: check.signatureVerified,
878
+ sha256Verified: false,
879
+ backupCreated: false,
880
+ rollbackPerformed: false,
881
+ migrationsExecuted: [],
882
+ sanitizedError: null
883
+ };
884
+ }
885
+ const rel = check.latestRelease;
886
+ const targetDir = path.resolve(options.targetDir);
887
+ const preserveNames = new Set([
888
+ '.env',
889
+ '.kseven-web-license.dat',
890
+ ...(options.preserveRelativePaths || []).map((p) => path.basename(p))
891
+ ]);
892
+ const stagingRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'k7-autoupdate-stage-'));
893
+ const backupDir = options.backupDir
894
+ ? path.resolve(options.backupDir)
895
+ : path.join(stagingRoot, 'backup');
896
+ let signatureVerified = false;
897
+ let sha256Verified = false;
898
+ let backupCreated = false;
899
+ let rollbackPerformed = false;
900
+ const migrationsExecuted = [];
901
+ try {
902
+ await safeReport({
903
+ releaseId: rel.releaseId,
904
+ toVersion: rel.version,
905
+ status: 'DOWNLOADING',
906
+ progressPercent: 15,
907
+ currentStep: `Solicitando grant assinado e baixando v${rel.version} em área temporária`
908
+ });
909
+ const signing = this.resolveClientSigningContext(state);
910
+ const grant = await this.apiRequest('POST', `/updates/${rel.releaseId}/download-grants`, {
911
+ credential: state.installationCredential,
912
+ ...signing,
913
+ body: { maxDownloads: 1 }
914
+ });
915
+ const consumed = await this.apiRequest('GET', `/updates/download/${encodeURIComponent(grant.grantId)}`, {
916
+ headers: { 'x-download-grant-token': grant.grantToken }
917
+ });
918
+ await safeReport({
919
+ releaseId: rel.releaseId,
920
+ toVersion: rel.version,
921
+ status: 'VERIFYING',
922
+ progressPercent: 35,
923
+ currentStep: 'Verificando assinatura Ed25519, canal, versão e SHA-256 do pacote'
924
+ });
925
+ const keysMap = await this.fetchPublicKeysMap(false).catch(() => state.pinnedPublicKeys || {});
926
+ let trustedPem = this.pinnedPublicKeys[consumed.signingKeyId] || keysMap[consumed.signingKeyId];
927
+ if (!trustedPem) {
928
+ const refreshed = await this.fetchPublicKeysMap(true).catch(() => ({}));
929
+ trustedPem = this.pinnedPublicKeys[consumed.signingKeyId] || refreshed[consumed.signingKeyId];
930
+ }
931
+ if (!trustedPem && !this.pinnedRootPublicKeyPem) {
932
+ trustedPem = rel.publicKeyPem;
933
+ }
934
+ if (!trustedPem) {
935
+ throw new KSevenWebSdkError(403, 'UNKNOWN_SIGNING_KEY', 'Chave pública Ed25519 confiável ausente na verificação do auto-update.');
936
+ }
937
+ const verifiedManifest = KSevenCodec.verifyEd25519Manifest({
938
+ manifestJson: consumed.manifestJson,
939
+ manifestSignature: consumed.manifestSignature,
940
+ signingKeyId: consumed.signingKeyId,
941
+ publicKeyPem: trustedPem
942
+ });
943
+ if (verifiedManifest.version !== rel.version || verifiedManifest.channel !== channel) {
944
+ throw new KSevenWebSdkError(403, 'MANIFEST_METADATA_MISMATCH', 'Versão ou canal do manifesto assinado diverge da release autorizada.');
945
+ }
946
+ signatureVerified = true;
947
+ const downloadUrl = String(consumed.packageUrl || '').startsWith('/api/')
948
+ ? `${this.apiBaseUrl}${consumed.packageUrl}`
949
+ : String(consumed.packageUrl || '');
950
+ this.assertAllowedEndpointUrl(downloadUrl);
951
+ const controller = new AbortController();
952
+ const timer = setTimeout(() => controller.abort(), Math.max(this.timeoutMs, 30000));
953
+ let packageBuffer;
954
+ try {
955
+ const pkgRes = await fetch(downloadUrl, { signal: controller.signal });
956
+ if (!pkgRes.ok) {
957
+ throw new KSevenWebSdkError(pkgRes.status, 'PACKAGE_DOWNLOAD_FAILED', `Falha ao baixar pacote da release v${rel.version} (HTTP ${pkgRes.status}).`);
958
+ }
959
+ packageBuffer = Buffer.from(await pkgRes.arrayBuffer());
960
+ }
961
+ finally {
962
+ clearTimeout(timer);
963
+ }
964
+ const actualSha256 = crypto.createHash('sha256').update(packageBuffer).digest('hex');
965
+ if (actualSha256 !== verifiedManifest.packageSha256.toLowerCase()) {
966
+ throw new KSevenWebSdkError(422, 'PACKAGE_SHA256_MISMATCH', `Hash SHA-256 inválido para v${rel.version}: integridade comprometida.`);
967
+ }
968
+ if (verifiedManifest.packageSizeBytes > 0 &&
969
+ packageBuffer.length !== verifiedManifest.packageSizeBytes) {
970
+ throw new KSevenWebSdkError(422, 'PACKAGE_SIZE_MISMATCH', 'Tamanho do pacote diverge do manifesto assinado.');
971
+ }
972
+ sha256Verified = true;
973
+ const stagingPackagePath = path.join(stagingRoot, `verified-${rel.version}.pkg`);
974
+ await fs.writeFile(stagingPackagePath, packageBuffer, { mode: 0o640 });
975
+ await safeReport({
976
+ releaseId: rel.releaseId,
977
+ toVersion: rel.version,
978
+ status: 'BACKING_UP',
979
+ progressPercent: 55,
980
+ currentStep: 'Criando backup completo do estado atual antes de aplicar arquivos',
981
+ signatureVerified,
982
+ sha256Verified
983
+ });
984
+ await fs.mkdir(targetDir, { recursive: true });
985
+ await this.copyDirectorySafe(targetDir, backupDir, preserveNames);
986
+ backupCreated = true;
987
+ await safeReport({
988
+ releaseId: rel.releaseId,
989
+ toVersion: rel.version,
990
+ status: 'APPLYING',
991
+ progressPercent: 75,
992
+ currentStep: `Aplicando arquivos verificados da v${rel.version}`,
993
+ signatureVerified,
994
+ sha256Verified,
995
+ backupCreated
996
+ });
997
+ await options.applyPackage({
998
+ stagingPackagePath,
999
+ packageBuffer,
1000
+ targetDir,
1001
+ release: rel,
1002
+ verifiedSha256: actualSha256
1003
+ });
1004
+ const migrations = Array.isArray(options.migrations) ? options.migrations : [];
1005
+ if (migrations.length > 0) {
1006
+ await safeReport({
1007
+ releaseId: rel.releaseId,
1008
+ toVersion: rel.version,
1009
+ status: 'MIGRATING',
1010
+ progressPercent: 88,
1011
+ currentStep: `Executando ${migrations.length} migração(ões) declarada(s) em ordem`,
1012
+ signatureVerified,
1013
+ sha256Verified,
1014
+ backupCreated
1015
+ });
1016
+ for (const migration of migrations) {
1017
+ await migration.run({
1018
+ targetDir,
1019
+ fromVersion: previousVersion,
1020
+ toVersion: rel.version
1021
+ });
1022
+ migrationsExecuted.push(migration.id);
1023
+ }
1024
+ }
1025
+ await this.validate(rel.version);
1026
+ await safeReport({
1027
+ releaseId: rel.releaseId,
1028
+ toVersion: rel.version,
1029
+ status: 'COMPLETED',
1030
+ progressPercent: 100,
1031
+ currentStep: `Atualização para v${rel.version} concluída com integridade verificada`,
1032
+ signatureVerified,
1033
+ sha256Verified,
1034
+ backupCreated,
1035
+ rollbackPerformed: false,
1036
+ migrationsExecuted
1037
+ });
1038
+ return {
1039
+ runUid,
1040
+ updated: true,
1041
+ status: 'COMPLETED',
1042
+ previousVersion,
1043
+ currentVersion: rel.version,
1044
+ targetVersion: rel.version,
1045
+ release: rel,
1046
+ signatureVerified,
1047
+ sha256Verified,
1048
+ backupCreated,
1049
+ rollbackPerformed: false,
1050
+ migrationsExecuted,
1051
+ sanitizedError: null
1052
+ };
1053
+ }
1054
+ catch (err) {
1055
+ const sanitizedMsg = String(err?.message || 'Falha durante atualização automática').slice(0, 400);
1056
+ if (backupCreated) {
1057
+ try {
1058
+ await this.restoreDirectoryFromBackup(backupDir, targetDir, preserveNames);
1059
+ rollbackPerformed = true;
1060
+ }
1061
+ catch {
1062
+ rollbackPerformed = false;
1063
+ }
1064
+ }
1065
+ const terminalStatus = rollbackPerformed ? 'ROLLED_BACK' : 'FAILED';
1066
+ await safeReport({
1067
+ releaseId: rel.releaseId,
1068
+ toVersion: rel.version,
1069
+ status: terminalStatus,
1070
+ progressPercent: 100,
1071
+ currentStep: rollbackPerformed
1072
+ ? `Falha detectada; estado anterior v${previousVersion} restaurado via backup`
1073
+ : 'Falha antes da aplicação; instalação mantida intacta',
1074
+ signatureVerified,
1075
+ sha256Verified,
1076
+ backupCreated,
1077
+ rollbackPerformed,
1078
+ migrationsExecuted,
1079
+ error: sanitizedMsg
1080
+ });
1081
+ return {
1082
+ runUid,
1083
+ updated: false,
1084
+ status: terminalStatus,
1085
+ previousVersion,
1086
+ currentVersion: previousVersion,
1087
+ targetVersion: rel.version,
1088
+ release: rel,
1089
+ signatureVerified,
1090
+ sha256Verified,
1091
+ backupCreated,
1092
+ rollbackPerformed,
1093
+ migrationsExecuted,
1094
+ sanitizedError: sanitizedMsg
1095
+ };
1096
+ }
1097
+ finally {
1098
+ await fs.rm(stagingRoot, { recursive: true, force: true }).catch(() => { });
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Faz rollback seguro para uma release anterior compatível e habilitada com `allowRollback`,
1103
+ * verificando Ed25519 e SHA-256 antes de gravar ou invocar o callback.
1104
+ */
1105
+ async rollback(releaseId, options = {}) {
1106
+ const state = await this.requireState();
1107
+ const listed = await this.listCompatibleReleases({ channel: options.channel });
1108
+ const allReleases = [
1109
+ ...(Array.isArray(listed?.releases) ? listed.releases : []),
1110
+ ...(Array.isArray(listed?.availableRollbacks) ? listed.availableRollbacks : [])
1111
+ ];
1112
+ const target = allReleases.find((r) => Number(r.releaseId) === Number(releaseId));
1113
+ if (!target) {
1114
+ throw new KSevenWebSdkError(404, 'ROLLBACK_RELEASE_NOT_FOUND', `Release #${releaseId} não encontrada ou não autorizada para rollback nesta licença.`);
1115
+ }
1116
+ if (target.allowRollback === false) {
1117
+ throw new KSevenWebSdkError(403, 'ROLLBACK_DISABLED', `A release #${releaseId} (${target.version}) não permite rollback.`);
1118
+ }
1119
+ return this.downloadAndApplyRelease(state, target, { ...options, rollback: true });
1120
+ }
1121
+ /**
1122
+ * Helpers autenticados por Bearer JWT do painel para integração da Loja in-app em backends intermediários.
1123
+ */
1124
+ async panelRequest(method, panelPath, jwtToken, body) {
1125
+ const url = `${this.apiBaseUrl}/api/web${panelPath}`;
1126
+ this.assertAllowedEndpointUrl(url);
1127
+ const controller = new AbortController();
1128
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1129
+ try {
1130
+ const res = await fetch(url, {
1131
+ method,
1132
+ headers: {
1133
+ Accept: 'application/json',
1134
+ Authorization: `Bearer ${jwtToken}`,
1135
+ ...(body ? { 'Content-Type': 'application/json' } : {})
1136
+ },
1137
+ body: body ? JSON.stringify(body) : undefined,
1138
+ signal: controller.signal
1139
+ });
1140
+ const data = await res.json().catch(() => ({}));
1141
+ if (!res.ok) {
1142
+ throw new KSevenWebSdkError(res.status, String(data?.code || `HTTP_${res.status}`), String(data?.message || `Erro HTTP ${res.status} em ${panelPath}`), typeof data?.requestId === 'string' ? data.requestId : undefined, data);
1143
+ }
1144
+ return data;
1145
+ }
1146
+ catch (err) {
1147
+ if (err instanceof KSevenWebSdkError)
1148
+ throw err;
1149
+ throw new KSevenWebSdkError(503, 'NETWORK_ERROR', err?.message || 'Erro de rede na consulta da loja.');
1150
+ }
1151
+ finally {
1152
+ clearTimeout(timer);
1153
+ }
1154
+ }
1155
+ async fetchStoreCatalog(jwtToken, opts) {
1156
+ const qs = new URLSearchParams();
1157
+ if (opts?.licenseId)
1158
+ qs.set('licenseId', String(opts.licenseId));
1159
+ if (opts?.productSlug)
1160
+ qs.set('productSlug', opts.productSlug);
1161
+ const suffix = qs.toString() ? `?${qs.toString()}` : '';
1162
+ return this.panelRequest('GET', `/store/catalog${suffix}`, jwtToken);
1163
+ }
1164
+ async checkStoreCompatibility(jwtToken, payload) {
1165
+ return this.panelRequest('POST', '/store/compatibility-check', jwtToken, payload);
1166
+ }
1167
+ async createStoreOrder(jwtToken, payload) {
1168
+ return this.panelRequest('POST', '/invoices/checkout', jwtToken, {
1169
+ ...payload,
1170
+ orderOrigin: payload.orderOrigin || 'IN_APP_STORE'
1171
+ });
1172
+ }
1173
+ async uninstall(reason = 'SDK_UNINSTALL') {
1174
+ const state = await this.readState();
1175
+ if (!state?.installationCredential) {
1176
+ return {
1177
+ uninstalled: true,
1178
+ alreadyUninstalled: true,
1179
+ installationId: null
1180
+ };
1181
+ }
1182
+ const signing = this.resolveClientSigningContext(state);
1183
+ let serverDeactivated = false;
1184
+ try {
1185
+ await this.apiRequest('POST', '/deactivate', {
1186
+ credential: state.installationCredential,
1187
+ ...signing,
1188
+ body: { reason }
1189
+ });
1190
+ serverDeactivated = true;
1191
+ }
1192
+ catch (err) {
1193
+ if (err instanceof KSevenWebSdkError && (err.statusCode === 403 || err.statusCode === 401)) {
1194
+ serverDeactivated = true;
1195
+ }
1196
+ else {
1197
+ throw err;
1198
+ }
1199
+ }
1200
+ await this.writeState(null);
1201
+ return {
1202
+ uninstalled: true,
1203
+ alreadyUninstalled: false,
1204
+ serverDeactivated,
1205
+ installationId: state.installationId
1206
+ };
1207
+ }
1208
+ }