@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,808 @@
1
+ import crypto from 'node:crypto';
2
+ import os from 'node:os';
3
+ import {
4
+ KSevenWebSdkError,
5
+ VerifiedManifestPayload,
6
+ WebEcdhHandshakeSignature,
7
+ WebKeyTransitionProof,
8
+ WebPublicKeyBundle,
9
+ WebRuntimeSignatureEnvelope
10
+ } from '../types.js';
11
+
12
+ export interface ActiveWireSession {
13
+ sessionId: string;
14
+ aesKey: Buffer;
15
+ expiresAtMs: number;
16
+ }
17
+
18
+ export class KSevenCodec {
19
+ /**
20
+ * Deriva chave local determinística para este host/processo caso `stateSecret` não seja fornecido explicitamente.
21
+ */
22
+ public static resolveDefaultStateSecret(customSecret?: string): string {
23
+ if (customSecret && customSecret.trim().length > 0) {
24
+ return customSecret.trim();
25
+ }
26
+ const envSecret = process.env.K7_WEB_STATE_SECRET?.trim();
27
+ if (envSecret) return envSecret;
28
+
29
+ const uid = typeof process.getuid === 'function' ? String(process.getuid()) : 'win';
30
+ return `${os.hostname()}|${os.platform()}|${os.arch()}|${uid}|k7-web-sdk-local-seal-v1`;
31
+ }
32
+
33
+ /**
34
+ * Serialização JSON determinística (chaves ordenadas recursivamente) idêntica à do backend.
35
+ */
36
+ public static canonicalizeJson(value: any): string {
37
+ if (value === null || value === undefined) return 'null';
38
+ if (typeof value === 'boolean' || typeof value === 'number') return JSON.stringify(value);
39
+ if (typeof value === 'string') return JSON.stringify(value);
40
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
41
+ if (Array.isArray(value)) {
42
+ return `[${value.map((item) => (item === undefined ? 'null' : this.canonicalizeJson(item))).join(',')}]`;
43
+ }
44
+ if (typeof value === 'object') {
45
+ const keys = Object.keys(value)
46
+ .filter((k) => value[k] !== undefined)
47
+ .sort();
48
+ const parts = keys.map((k) => `${JSON.stringify(k)}:${this.canonicalizeJson(value[k])}`);
49
+ return `{${parts.join(',')}}`;
50
+ }
51
+ return JSON.stringify(String(value));
52
+ }
53
+
54
+ public static sha256CanonicalJson(value: any): string {
55
+ return crypto.createHash('sha256').update(this.canonicalizeJson(value), 'utf8').digest('hex');
56
+ }
57
+
58
+ public static extractEd25519RawPublicKeyHex(publicKeyPem: string): string {
59
+ const keyObj = crypto.createPublicKey({ key: publicKeyPem, format: 'pem', type: 'spki' });
60
+ if (keyObj.asymmetricKeyType !== 'ed25519') {
61
+ throw new KSevenWebSdkError(403, 'INVALID_PUBLIC_KEY', 'Chave pública fornecida não é Ed25519.');
62
+ }
63
+ const der = keyObj.export({ format: 'der', type: 'spki' }) as Buffer;
64
+ if (der.length < 32) {
65
+ throw new KSevenWebSdkError(403, 'INVALID_PUBLIC_KEY', 'Estrutura SPKI Ed25519 inválida.');
66
+ }
67
+ return der.subarray(der.length - 32).toString('hex');
68
+ }
69
+
70
+ public static generateClientEd25519KeyPair(): {
71
+ clientPublicKeyPem: string;
72
+ clientPrivateKeyPem: string;
73
+ } {
74
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519', {
75
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
76
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
77
+ });
78
+ return {
79
+ clientPublicKeyPem: publicKey,
80
+ clientPrivateKeyPem: privateKey
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Cifra e codifica estado local no formato `k7st.v1.<saltB64Url>.<ivB64Url>.<tagB64Url>.<cipherB64Url>`
86
+ * usando AES-256-GCM + HKDF-SHA256.
87
+ */
88
+ public static encodeEncryptedState(stateObj: unknown, secretInput?: string): string {
89
+ const masterSecret = this.resolveDefaultStateSecret(secretInput);
90
+ const salt = crypto.randomBytes(16);
91
+ const key = Buffer.from(
92
+ crypto.hkdfSync(
93
+ 'sha256',
94
+ Buffer.from(masterSecret, 'utf8'),
95
+ salt,
96
+ Buffer.from('k7-web-state-v1', 'utf8'),
97
+ 32
98
+ )
99
+ );
100
+ const iv = crypto.randomBytes(12);
101
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
102
+ cipher.setAAD(Buffer.from('k7st.v1', 'utf8'));
103
+ const plaintext = Buffer.from(JSON.stringify(stateObj), 'utf8');
104
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
105
+ const tag = cipher.getAuthTag();
106
+ return `k7st.v1.${salt.toString('base64url')}.${iv.toString('base64url')}.${tag.toString('base64url')}.${ciphertext.toString('base64url')}`;
107
+ }
108
+
109
+ /**
110
+ * Decifra estado local `k7st.v1...` (ou lê JSON legado caso exista arquivo anterior à migração).
111
+ */
112
+ public static decodeEncryptedState<T = any>(rawContent: string, secretInput?: string): T {
113
+ const trimmed = String(rawContent || '').trim();
114
+ if (!trimmed) {
115
+ throw new KSevenWebSdkError(400, 'EMPTY_STATE', 'Arquivo de estado da licença está vazio.');
116
+ }
117
+
118
+ if (trimmed.startsWith('{')) {
119
+ return JSON.parse(trimmed) as T;
120
+ }
121
+
122
+ const parts = trimmed.split('.');
123
+ if (parts.length !== 6 || parts[0] !== 'k7st' || parts[1] !== 'v1') {
124
+ throw new KSevenWebSdkError(
125
+ 400,
126
+ 'CORRUPTED_STATE_FORMAT',
127
+ 'Formato de estado criptografado inválido ou adulterado.'
128
+ );
129
+ }
130
+
131
+ const salt = Buffer.from(parts[2], 'base64url');
132
+ const iv = Buffer.from(parts[3], 'base64url');
133
+ const tag = Buffer.from(parts[4], 'base64url');
134
+ const ciphertext = Buffer.from(parts[5], 'base64url');
135
+
136
+ const masterSecret = this.resolveDefaultStateSecret(secretInput);
137
+ const key = Buffer.from(
138
+ crypto.hkdfSync(
139
+ 'sha256',
140
+ Buffer.from(masterSecret, 'utf8'),
141
+ salt,
142
+ Buffer.from('k7-web-state-v1', 'utf8'),
143
+ 32
144
+ )
145
+ );
146
+
147
+ try {
148
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
149
+ decipher.setAAD(Buffer.from('k7st.v1', 'utf8'));
150
+ decipher.setAuthTag(tag);
151
+ const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
152
+ return JSON.parse(plain) as T;
153
+ } catch {
154
+ throw new KSevenWebSdkError(
155
+ 403,
156
+ 'STATE_DECRYPT_FAILED',
157
+ 'Não foi possível decifrar o arquivo de estado da licença. Verifique K7_WEB_STATE_SECRET ou reinstale.'
158
+ );
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Inicia par de chaves efêmero ECDH P-256 para negociação de sessão cifrada de transporte.
164
+ */
165
+ public static createClientEphemeralKeyPair(): {
166
+ clientPublicKeySpkiBase64: string;
167
+ privateKey: crypto.KeyObject;
168
+ } {
169
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {
170
+ namedCurve: 'prime256v1'
171
+ });
172
+ const spkiDer = publicKey.export({ format: 'der', type: 'spki' }) as Buffer;
173
+ return {
174
+ clientPublicKeySpkiBase64: spkiDer.toString('base64'),
175
+ privateKey
176
+ };
177
+ }
178
+
179
+ public static deriveWireSessionFromServerResponse(
180
+ privateKey: crypto.KeyObject,
181
+ sessionId: string,
182
+ serverPublicKeySpkiBase64: string,
183
+ expiresInSeconds = 1800
184
+ ): ActiveWireSession {
185
+ const serverDer = Buffer.from(serverPublicKeySpkiBase64, 'base64');
186
+ const serverKey = crypto.createPublicKey({ key: serverDer, format: 'der', type: 'spki' });
187
+ const sharedSecret = crypto.diffieHellman({ privateKey, publicKey: serverKey });
188
+ const aesKey = Buffer.from(
189
+ crypto.hkdfSync(
190
+ 'sha256',
191
+ sharedSecret,
192
+ Buffer.from(sessionId, 'utf8'),
193
+ Buffer.from('k7-web-wire-v1', 'utf8'),
194
+ 32
195
+ )
196
+ );
197
+
198
+ return {
199
+ sessionId,
200
+ aesKey,
201
+ expiresAtMs: Date.now() + Math.max(60, expiresInSeconds - 30) * 1000
202
+ };
203
+ }
204
+
205
+ public static sealWirePayload(payload: unknown, aesKey: Buffer, aad: string): string {
206
+ const iv = crypto.randomBytes(12);
207
+ const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
208
+ cipher.setAAD(Buffer.from(aad, 'utf8'));
209
+ const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
210
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
211
+ const tag = cipher.getAuthTag();
212
+ return `k7seal.v1.${iv.toString('base64url')}.${tag.toString('base64url')}.${ciphertext.toString('base64url')}`;
213
+ }
214
+
215
+ public static unsealWirePayload(sealedEnvelope: string, aesKey: Buffer, aad: string): any {
216
+ const parts = String(sealedEnvelope || '').split('.');
217
+ if (parts.length !== 5 || parts[0] !== 'k7seal' || parts[1] !== 'v1') {
218
+ throw new KSevenWebSdkError(400, 'INVALID_SEALED_RESPONSE', 'Envelope de resposta criptografado inválido.');
219
+ }
220
+ const iv = Buffer.from(parts[2], 'base64url');
221
+ const tag = Buffer.from(parts[3], 'base64url');
222
+ const ciphertext = Buffer.from(parts[4], 'base64url');
223
+ try {
224
+ const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, iv);
225
+ decipher.setAAD(Buffer.from(aad, 'utf8'));
226
+ decipher.setAuthTag(tag);
227
+ const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
228
+ return JSON.parse(plain);
229
+ } catch {
230
+ throw new KSevenWebSdkError(
231
+ 403,
232
+ 'SEALED_RESPONSE_AUTH_FAILED',
233
+ 'Falha ao autenticar/decifrar envelope de resposta k7seal.v1 (tag GCM ou AAD divergente).'
234
+ );
235
+ }
236
+ }
237
+
238
+ public static verifyKeyTransitionProof(
239
+ proof: WebKeyTransitionProof | null | undefined,
240
+ signerPublicKeyPem: string,
241
+ expectedToKeyId?: string,
242
+ expectedToPublicKeyRawHex?: string,
243
+ nowMs = Date.now()
244
+ ): boolean {
245
+ if (!proof || proof.schema !== 'k7web-key-transition|v1' || !proof.signatureBase64) {
246
+ return false;
247
+ }
248
+ if (expectedToKeyId && proof.toKeyId !== expectedToKeyId) return false;
249
+ if (
250
+ expectedToPublicKeyRawHex &&
251
+ proof.toPublicKeyRawHex.toLowerCase() !== expectedToPublicKeyRawHex.toLowerCase()
252
+ ) {
253
+ return false;
254
+ }
255
+ const expiresMs = Date.parse(proof.expiresAt);
256
+ if (!Number.isFinite(expiresMs) || expiresMs <= nowMs) return false;
257
+
258
+ const canonical = [
259
+ proof.schema,
260
+ proof.fromKeyId,
261
+ String(proof.fromKeyVersion),
262
+ proof.toKeyId,
263
+ String(proof.toKeyVersion),
264
+ proof.toPublicKeyRawHex.toLowerCase(),
265
+ proof.issuedAt,
266
+ proof.expiresAt,
267
+ proof.reason
268
+ ].join('|');
269
+
270
+ try {
271
+ return crypto.verify(
272
+ null,
273
+ Buffer.from(canonical, 'utf8'),
274
+ signerPublicKeyPem,
275
+ Buffer.from(proof.signatureBase64, 'base64')
276
+ );
277
+ } catch {
278
+ return false;
279
+ }
280
+ }
281
+
282
+ public static resolveTrustedKeysFromBundle(
283
+ bundle: Partial<WebPublicKeyBundle>,
284
+ pinnedRootPublicKeyPem?: string,
285
+ explicitPinnedKeys?: Record<string, string>,
286
+ nowMs = Date.now()
287
+ ): Record<string, string> {
288
+ const trusted: Record<string, string> = {};
289
+ const candidates = [
290
+ ...(bundle.activeKey ? [bundle.activeKey] : []),
291
+ ...(Array.isArray(bundle.secondaryKeys) ? bundle.secondaryKeys : []),
292
+ ...(Array.isArray(bundle.keys) ? bundle.keys : [])
293
+ ];
294
+ const dedup = new Map<string, (typeof candidates)[number]>();
295
+ for (const c of candidates) {
296
+ if (c?.keyId && c?.publicKeyPem && !dedup.has(c.keyId)) {
297
+ dedup.set(c.keyId, c);
298
+ }
299
+ }
300
+ const entries = Array.from(dedup.values());
301
+
302
+ const effectiveRootPem = pinnedRootPublicKeyPem || bundle.rootKey?.publicKeyPem || '';
303
+ if (pinnedRootPublicKeyPem && bundle.rootKey?.publicKeyPem) {
304
+ const pinnedHex = this.extractEd25519RawPublicKeyHex(pinnedRootPublicKeyPem);
305
+ const bundleRootHex = this.extractEd25519RawPublicKeyHex(bundle.rootKey.publicKeyPem);
306
+ if (pinnedHex !== bundleRootHex) {
307
+ throw new KSevenWebSdkError(
308
+ 403,
309
+ 'WEB_ROOT_KEY_MISMATCH',
310
+ 'Chave raiz publicada pelo servidor diverge da chave raiz Ed25519 pinada no SDK.'
311
+ );
312
+ }
313
+ }
314
+
315
+ if (effectiveRootPem) {
316
+ // 1) Chaves diretamente endossadas pela chave raiz via rootProof
317
+ for (const entry of entries) {
318
+ const rawHex = this.extractEd25519RawPublicKeyHex(entry.publicKeyPem);
319
+ if (entry.publicKeyRawHex && rawHex !== entry.publicKeyRawHex.toLowerCase()) continue;
320
+ if (
321
+ entry.rootProof &&
322
+ this.verifyKeyTransitionProof(entry.rootProof, effectiveRootPem, entry.keyId, rawHex, nowMs)
323
+ ) {
324
+ trusted[entry.keyId] = entry.publicKeyPem;
325
+ }
326
+ }
327
+
328
+ // 2) Chaves encadeadas via transitionProof assinada por chave operacional já confiável
329
+ let progress = true;
330
+ while (progress) {
331
+ progress = false;
332
+ for (const entry of entries) {
333
+ if (trusted[entry.keyId] || !entry.transitionProof) continue;
334
+ const signerPem = trusted[entry.transitionProof.fromKeyId];
335
+ if (!signerPem) continue;
336
+ const rawHex = this.extractEd25519RawPublicKeyHex(entry.publicKeyPem);
337
+ if (
338
+ (!entry.publicKeyRawHex || rawHex === entry.publicKeyRawHex.toLowerCase()) &&
339
+ this.verifyKeyTransitionProof(entry.transitionProof, signerPem, entry.keyId, rawHex, nowMs)
340
+ ) {
341
+ trusted[entry.keyId] = entry.publicKeyPem;
342
+ progress = true;
343
+ }
344
+ }
345
+ }
346
+ }
347
+
348
+ // Se nenhuma chave raiz foi pinada e o servidor está em modo legado sem provas, aceita bundle publicado
349
+ if (!pinnedRootPublicKeyPem && Object.keys(trusted).length === 0) {
350
+ for (const entry of entries) {
351
+ trusted[entry.keyId] = entry.publicKeyPem;
352
+ }
353
+ }
354
+
355
+ // Chaves explícitas pinadas por keyId sempre prevalecem
356
+ if (explicitPinnedKeys) {
357
+ for (const [keyId, pem] of Object.entries(explicitPinnedKeys)) {
358
+ if (keyId && pem) trusted[keyId] = pem;
359
+ }
360
+ }
361
+
362
+ return trusted;
363
+ }
364
+
365
+ public static verifyEcdhHandshakeSignature(params: {
366
+ sessionId: string;
367
+ serverPublicKeySpkiBase64: string;
368
+ fingerprintSha256: string;
369
+ clientPublicKeySpkiBase64: string;
370
+ expiresInSeconds: number;
371
+ expectedNonce: string;
372
+ handshakeSignature: WebEcdhHandshakeSignature | undefined;
373
+ trustedKeys: Record<string, string>;
374
+ maxAgeSeconds?: number;
375
+ }): void {
376
+ const hs = params.handshakeSignature;
377
+ if (!hs || hs.schema !== 'k7-web-ecdh-sig-v1' || !hs.signatureBase64 || !hs.keyId) {
378
+ throw new KSevenWebSdkError(
379
+ 403,
380
+ 'MISSING_HANDSHAKE_SIGNATURE',
381
+ 'Resposta de /session-key sem assinatura Ed25519 de handshake.'
382
+ );
383
+ }
384
+
385
+ const publicKeyPem = params.trustedKeys[hs.keyId];
386
+ if (!publicKeyPem) {
387
+ throw new KSevenWebSdkError(
388
+ 403,
389
+ 'UNTRUSTED_HANDSHAKE_KEY',
390
+ `Chave Ed25519 do handshake ECDH não é confiável (keyId=${hs.keyId}).`
391
+ );
392
+ }
393
+
394
+ if (hs.nonce !== params.expectedNonce) {
395
+ throw new KSevenWebSdkError(
396
+ 403,
397
+ 'HANDSHAKE_NONCE_MISMATCH',
398
+ 'Nonce retornado no handshake ECDH diverge do nonce enviado pelo cliente.'
399
+ );
400
+ }
401
+
402
+ const tsMs = Date.parse(hs.timestamp);
403
+ const maxAge = (params.maxAgeSeconds ?? 300) * 1000;
404
+ if (!Number.isFinite(tsMs) || Math.abs(Date.now() - tsMs) > maxAge) {
405
+ throw new KSevenWebSdkError(
406
+ 403,
407
+ 'HANDSHAKE_TIMESTAMP_INVALID',
408
+ 'Timestamp do handshake ECDH fora da janela permitida.'
409
+ );
410
+ }
411
+
412
+ const clientPublicKeySha256 = crypto
413
+ .createHash('sha256')
414
+ .update(Buffer.from(params.clientPublicKeySpkiBase64, 'base64'))
415
+ .digest('hex');
416
+
417
+ const canonical = [
418
+ hs.schema,
419
+ params.sessionId,
420
+ params.serverPublicKeySpkiBase64,
421
+ params.fingerprintSha256,
422
+ clientPublicKeySha256,
423
+ hs.timestamp,
424
+ String(params.expiresInSeconds),
425
+ hs.nonce
426
+ ].join('|');
427
+
428
+ let ok = false;
429
+ try {
430
+ ok = crypto.verify(
431
+ null,
432
+ Buffer.from(canonical, 'utf8'),
433
+ publicKeyPem,
434
+ Buffer.from(hs.signatureBase64, 'base64')
435
+ );
436
+ } catch {
437
+ ok = false;
438
+ }
439
+
440
+ if (!ok) {
441
+ throw new KSevenWebSdkError(
442
+ 403,
443
+ 'INVALID_HANDSHAKE_SIGNATURE',
444
+ `Assinatura Ed25519 do handshake ECDH inválida para keyId=${hs.keyId}.`
445
+ );
446
+ }
447
+ }
448
+
449
+ public static verifyRuntimeResponseSignature(params: {
450
+ responseBody: Record<string, any>;
451
+ trustedKeys: Record<string, string>;
452
+ expectedMethod: string;
453
+ expectedPath: string;
454
+ expectedHttpStatus: number;
455
+ expectedNonce?: string;
456
+ maxAgeSeconds?: number;
457
+ }): { keyId: string } {
458
+ const env = params.responseBody?.signatureEnvelope as WebRuntimeSignatureEnvelope | undefined;
459
+ if (!env || env.schema !== 'k7-web-response-sig-v1' || !env.signatureBase64 || !env.keyId) {
460
+ throw new KSevenWebSdkError(
461
+ 403,
462
+ 'MISSING_RESPONSE_SIGNATURE',
463
+ 'Resposta de runtime sem signatureEnvelope Ed25519.'
464
+ );
465
+ }
466
+
467
+ const publicKeyPem = params.trustedKeys[env.keyId];
468
+ if (!publicKeyPem) {
469
+ throw new KSevenWebSdkError(
470
+ 403,
471
+ 'UNTRUSTED_RESPONSE_SIGNING_KEY',
472
+ `Chave Ed25519 da resposta de runtime não é confiável (keyId=${env.keyId}).`
473
+ );
474
+ }
475
+
476
+ if (params.expectedNonce !== undefined && env.nonce !== params.expectedNonce) {
477
+ throw new KSevenWebSdkError(
478
+ 403,
479
+ 'RESPONSE_NONCE_MISMATCH',
480
+ 'Nonce do envelope assinado diverge do nonce enviado na requisição.'
481
+ );
482
+ }
483
+ if (env.method.toUpperCase() !== params.expectedMethod.toUpperCase()) {
484
+ throw new KSevenWebSdkError(
485
+ 403,
486
+ 'RESPONSE_METHOD_MISMATCH',
487
+ 'Método HTTP do envelope assinado diverge da requisição.'
488
+ );
489
+ }
490
+ if (env.path !== params.expectedPath) {
491
+ throw new KSevenWebSdkError(
492
+ 403,
493
+ 'RESPONSE_PATH_MISMATCH',
494
+ 'Rota do envelope assinado diverge da requisição.'
495
+ );
496
+ }
497
+ if (env.httpStatus !== params.expectedHttpStatus) {
498
+ throw new KSevenWebSdkError(
499
+ 403,
500
+ 'RESPONSE_STATUS_MISMATCH',
501
+ 'Status HTTP do envelope assinado diverge da resposta recebida.'
502
+ );
503
+ }
504
+
505
+ const tsMs = Date.parse(env.timestamp);
506
+ const maxAge = (params.maxAgeSeconds ?? 300) * 1000;
507
+ if (!Number.isFinite(tsMs) || Math.abs(Date.now() - tsMs) > maxAge) {
508
+ throw new KSevenWebSdkError(
509
+ 403,
510
+ 'RESPONSE_TIMESTAMP_OUT_OF_WINDOW',
511
+ 'Timestamp da assinatura da resposta fora da janela permitida.'
512
+ );
513
+ }
514
+
515
+ const unsignedCopy: Record<string, any> = { ...params.responseBody };
516
+ delete unsignedCopy.signatureEnvelope;
517
+ const computedHash = this.sha256CanonicalJson(unsignedCopy);
518
+ if (computedHash !== env.payloadSha256) {
519
+ throw new KSevenWebSdkError(
520
+ 403,
521
+ 'RESPONSE_PAYLOAD_TAMPERED',
522
+ 'Hash SHA-256 do payload diverge do signatureEnvelope assinado.'
523
+ );
524
+ }
525
+
526
+ const canonical = [
527
+ env.schema,
528
+ env.protocolVersion,
529
+ env.keyId,
530
+ String(env.keyVersion),
531
+ env.rootKeyId,
532
+ env.requestId,
533
+ env.nonce,
534
+ env.method.toUpperCase(),
535
+ env.path,
536
+ env.timestamp,
537
+ String(env.httpStatus),
538
+ env.decision,
539
+ env.code,
540
+ env.productSlug || '',
541
+ env.licenseId !== null && env.licenseId !== undefined ? String(env.licenseId) : '',
542
+ env.installationId || '',
543
+ env.domain || '',
544
+ env.licenseStatus || '',
545
+ env.expiresAt || '',
546
+ env.entitlementHash || '',
547
+ env.payloadSha256
548
+ ].join('|');
549
+
550
+ let ok = false;
551
+ try {
552
+ ok = crypto.verify(
553
+ null,
554
+ Buffer.from(canonical, 'utf8'),
555
+ publicKeyPem,
556
+ Buffer.from(env.signatureBase64, 'base64')
557
+ );
558
+ } catch {
559
+ ok = false;
560
+ }
561
+
562
+ if (!ok) {
563
+ throw new KSevenWebSdkError(
564
+ 403,
565
+ 'INVALID_RESPONSE_SIGNATURE',
566
+ `Assinatura Ed25519 da resposta de runtime inválida para keyId=${env.keyId}.`
567
+ );
568
+ }
569
+
570
+ return { keyId: env.keyId };
571
+ }
572
+
573
+ public static signClientRequest(params: {
574
+ clientPrivateKeyPem: string;
575
+ method: string;
576
+ path: string;
577
+ timestamp: string;
578
+ nonce: string;
579
+ installationId: string;
580
+ body?: Record<string, any>;
581
+ }): string {
582
+ const bodySha256 = this.sha256CanonicalJson(params.body || {});
583
+ const canonical = [
584
+ 'k7web-client-req|v1',
585
+ params.method.toUpperCase(),
586
+ params.path,
587
+ params.timestamp,
588
+ params.nonce,
589
+ params.installationId,
590
+ bodySha256
591
+ ].join('|');
592
+
593
+ return crypto
594
+ .sign(null, Buffer.from(canonical, 'utf8'), params.clientPrivateKeyPem)
595
+ .toString('base64');
596
+ }
597
+
598
+ public static verifyEd25519Manifest(params: {
599
+ manifestJson: string;
600
+ manifestSignature: string;
601
+ signingKeyId: string;
602
+ publicKeyPem: string;
603
+ }): VerifiedManifestPayload {
604
+ let valid = false;
605
+ try {
606
+ valid = crypto.verify(
607
+ null,
608
+ Buffer.from(params.manifestJson, 'utf8'),
609
+ params.publicKeyPem,
610
+ Buffer.from(params.manifestSignature, 'base64')
611
+ );
612
+ } catch {
613
+ valid = false;
614
+ }
615
+ if (!valid) {
616
+ throw new KSevenWebSdkError(
617
+ 403,
618
+ 'INVALID_RELEASE_SIGNATURE',
619
+ `Assinatura Ed25519 do manifesto rejeitada para keyId=${params.signingKeyId}.`
620
+ );
621
+ }
622
+ const parsed = JSON.parse(params.manifestJson);
623
+ if (parsed?.schema !== 'k7-web-release-v1') {
624
+ throw new KSevenWebSdkError(403, 'INVALID_MANIFEST_SCHEMA', 'Esquema de manifesto desconhecido.');
625
+ }
626
+ return parsed as VerifiedManifestPayload;
627
+ }
628
+
629
+ /**
630
+ * Valida offline o último `signatureEnvelope` Ed25519 salvo em cache criptografado,
631
+ * garantindo integridade do payload, status ativo (não REVOKED/SUSPENDED),
632
+ * correspondência de instalação/domínio e janela de carência `graceUntil`.
633
+ */
634
+ public static verifyCachedOfflineEntitlement(params: {
635
+ cachedResponse: Record<string, any> | null | undefined;
636
+ trustedKeys: Record<string, string>;
637
+ expectedInstallationId: string;
638
+ expectedDomain: string;
639
+ nowMs?: number;
640
+ }): {
641
+ keyId: string;
642
+ graceUntil: string;
643
+ entitlement: Record<string, any>;
644
+ issuedAt: string;
645
+ } {
646
+ const nowMs = params.nowMs ?? Date.now();
647
+ const cached = params.cachedResponse;
648
+ if (!cached || typeof cached !== 'object' || !cached.signatureEnvelope) {
649
+ throw new KSevenWebSdkError(
650
+ 403,
651
+ 'OFFLINE_CACHE_MISSING',
652
+ 'Nenhum comprovante assinado Ed25519 disponível em cache para validação offline.'
653
+ );
654
+ }
655
+
656
+ const env = cached.signatureEnvelope as WebRuntimeSignatureEnvelope;
657
+ if (env.schema !== 'k7-web-response-sig-v1' || !env.signatureBase64 || !env.keyId) {
658
+ throw new KSevenWebSdkError(
659
+ 403,
660
+ 'OFFLINE_CACHE_INVALID',
661
+ 'Envelope de assinatura em cache offline é inválido.'
662
+ );
663
+ }
664
+
665
+ const publicKeyPem = params.trustedKeys[env.keyId];
666
+ if (!publicKeyPem) {
667
+ throw new KSevenWebSdkError(
668
+ 403,
669
+ 'OFFLINE_UNTRUSTED_KEY',
670
+ `Chave Ed25519 do cache offline não é confiável (keyId=${env.keyId}).`
671
+ );
672
+ }
673
+
674
+ if (env.decision !== 'ALLOW' || (env.httpStatus !== 200 && env.httpStatus !== 201)) {
675
+ throw new KSevenWebSdkError(
676
+ 403,
677
+ 'OFFLINE_CACHE_NOT_ALLOWED',
678
+ 'Última resposta assinada em cache não autoriza operação offline.'
679
+ );
680
+ }
681
+
682
+ if (env.installationId && env.installationId !== params.expectedInstallationId) {
683
+ throw new KSevenWebSdkError(
684
+ 403,
685
+ 'OFFLINE_INSTALLATION_MISMATCH',
686
+ 'Cache offline não pertence à instalação atual.'
687
+ );
688
+ }
689
+ if (env.domain && env.domain.toLowerCase() !== params.expectedDomain.toLowerCase()) {
690
+ throw new KSevenWebSdkError(
691
+ 403,
692
+ 'OFFLINE_DOMAIN_MISMATCH',
693
+ 'Cache offline não pertence ao domínio atual.'
694
+ );
695
+ }
696
+
697
+ const unsignedCopy: Record<string, any> = { ...cached };
698
+ delete unsignedCopy.signatureEnvelope;
699
+ const computedHash = this.sha256CanonicalJson(unsignedCopy);
700
+ if (computedHash !== env.payloadSha256) {
701
+ throw new KSevenWebSdkError(
702
+ 403,
703
+ 'OFFLINE_CACHE_TAMPERED',
704
+ 'Integridade SHA-256 do cache offline violada.'
705
+ );
706
+ }
707
+
708
+ const canonical = [
709
+ env.schema,
710
+ env.protocolVersion,
711
+ env.keyId,
712
+ String(env.keyVersion),
713
+ env.rootKeyId,
714
+ env.requestId,
715
+ env.nonce,
716
+ env.method.toUpperCase(),
717
+ env.path,
718
+ env.timestamp,
719
+ String(env.httpStatus),
720
+ env.decision,
721
+ env.code,
722
+ env.productSlug || '',
723
+ env.licenseId !== null && env.licenseId !== undefined ? String(env.licenseId) : '',
724
+ env.installationId || '',
725
+ env.domain || '',
726
+ env.licenseStatus || '',
727
+ env.expiresAt || '',
728
+ env.entitlementHash || '',
729
+ env.payloadSha256
730
+ ].join('|');
731
+
732
+ let sigOk = false;
733
+ try {
734
+ sigOk = crypto.verify(
735
+ null,
736
+ Buffer.from(canonical, 'utf8'),
737
+ publicKeyPem,
738
+ Buffer.from(env.signatureBase64, 'base64')
739
+ );
740
+ } catch {
741
+ sigOk = false;
742
+ }
743
+ if (!sigOk) {
744
+ throw new KSevenWebSdkError(
745
+ 403,
746
+ 'OFFLINE_SIGNATURE_INVALID',
747
+ 'Assinatura Ed25519 do comprovante offline inválida.'
748
+ );
749
+ }
750
+
751
+ const entitlement = cached.entitlement;
752
+ if (!entitlement || typeof entitlement !== 'object') {
753
+ throw new KSevenWebSdkError(
754
+ 403,
755
+ 'OFFLINE_ENTITLEMENT_MISSING',
756
+ 'Payload de entitlement ausente no cache offline.'
757
+ );
758
+ }
759
+
760
+ const status = String(entitlement.licenseStatus || env.licenseStatus || '').toUpperCase();
761
+ const hardRevoke = Array.isArray(entitlement.offlineValidation?.hardRevokeStatuses)
762
+ ? entitlement.offlineValidation.hardRevokeStatuses.map((s: any) => String(s).toUpperCase())
763
+ : ['REVOKED', 'SUSPENDED'];
764
+ if (hardRevoke.includes(status) || (status !== 'ACTIVE' && !entitlement.inGracePeriod)) {
765
+ throw new KSevenWebSdkError(
766
+ 403,
767
+ 'LICENSE_HARD_REVOKED',
768
+ `Operação offline bloqueada para licença em status ${status || 'DESCONHECIDO'}.`
769
+ );
770
+ }
771
+
772
+ if (entitlement.offlineValidation && entitlement.offlineValidation.allowed === false) {
773
+ throw new KSevenWebSdkError(
774
+ 403,
775
+ 'OFFLINE_GRACE_DISABLED',
776
+ 'A política desta licença não permite operação offline em carência.'
777
+ );
778
+ }
779
+
780
+ const graceUntil = String(
781
+ entitlement.offlineValidation?.graceUntil || entitlement.graceUntil || ''
782
+ ).trim();
783
+ const graceMs = Date.parse(graceUntil);
784
+ if (!graceUntil || !Number.isFinite(graceMs) || nowMs > graceMs) {
785
+ throw new KSevenWebSdkError(
786
+ 403,
787
+ 'OFFLINE_GRACE_EXPIRED',
788
+ 'Período de carência offline expirado. Reconecte à API K’Seven para revalidar.'
789
+ );
790
+ }
791
+
792
+ const issuedMs = Date.parse(env.timestamp);
793
+ if (!Number.isFinite(issuedMs) || issuedMs > nowMs + 5 * 60 * 1000) {
794
+ throw new KSevenWebSdkError(
795
+ 403,
796
+ 'OFFLINE_CLOCK_TAMPERED',
797
+ 'Relógio local inconsistente com a data de emissão do comprovante assinado.'
798
+ );
799
+ }
800
+
801
+ return {
802
+ keyId: env.keyId,
803
+ graceUntil,
804
+ entitlement,
805
+ issuedAt: env.timestamp
806
+ };
807
+ }
808
+ }