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