@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.
- package/README.md +71 -0
- package/dist/KSevenWebLicenseSdk.d.ts +147 -0
- package/dist/KSevenWebLicenseSdk.js +1208 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +156 -0
- package/dist/crypto/KSevenCodec.d.ts +98 -0
- package/dist/crypto/KSevenCodec.js +502 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/storage/EncryptedStateStore.d.ts +8 -0
- package/dist/storage/EncryptedStateStore.js +40 -0
- package/dist/types.d.ts +318 -0
- package/dist/types.js +16 -0
- package/package.json +38 -0
- package/src/KSevenWebLicenseSdk.ts +1565 -0
- package/src/cli.ts +197 -0
- package/src/crypto/KSevenCodec.ts +808 -0
- package/src/index.ts +4 -0
- package/src/storage/EncryptedStateStore.ts +41 -0
- package/src/types.ts +353 -0
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import { KSevenWebSdkError } from '../types.js';
|
|
4
|
+
export class KSevenCodec {
|
|
5
|
+
/**
|
|
6
|
+
* Deriva chave local determinística para este host/processo caso `stateSecret` não seja fornecido explicitamente.
|
|
7
|
+
*/
|
|
8
|
+
static resolveDefaultStateSecret(customSecret) {
|
|
9
|
+
if (customSecret && customSecret.trim().length > 0) {
|
|
10
|
+
return customSecret.trim();
|
|
11
|
+
}
|
|
12
|
+
const envSecret = process.env.K7_WEB_STATE_SECRET?.trim();
|
|
13
|
+
if (envSecret)
|
|
14
|
+
return envSecret;
|
|
15
|
+
const uid = typeof process.getuid === 'function' ? String(process.getuid()) : 'win';
|
|
16
|
+
return `${os.hostname()}|${os.platform()}|${os.arch()}|${uid}|k7-web-sdk-local-seal-v1`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Serialização JSON determinística (chaves ordenadas recursivamente) idêntica à do backend.
|
|
20
|
+
*/
|
|
21
|
+
static canonicalizeJson(value) {
|
|
22
|
+
if (value === null || value === undefined)
|
|
23
|
+
return 'null';
|
|
24
|
+
if (typeof value === 'boolean' || typeof value === 'number')
|
|
25
|
+
return JSON.stringify(value);
|
|
26
|
+
if (typeof value === 'string')
|
|
27
|
+
return JSON.stringify(value);
|
|
28
|
+
if (value instanceof Date)
|
|
29
|
+
return JSON.stringify(value.toISOString());
|
|
30
|
+
if (Array.isArray(value)) {
|
|
31
|
+
return `[${value.map((item) => (item === undefined ? 'null' : this.canonicalizeJson(item))).join(',')}]`;
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === 'object') {
|
|
34
|
+
const keys = Object.keys(value)
|
|
35
|
+
.filter((k) => value[k] !== undefined)
|
|
36
|
+
.sort();
|
|
37
|
+
const parts = keys.map((k) => `${JSON.stringify(k)}:${this.canonicalizeJson(value[k])}`);
|
|
38
|
+
return `{${parts.join(',')}}`;
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify(String(value));
|
|
41
|
+
}
|
|
42
|
+
static sha256CanonicalJson(value) {
|
|
43
|
+
return crypto.createHash('sha256').update(this.canonicalizeJson(value), 'utf8').digest('hex');
|
|
44
|
+
}
|
|
45
|
+
static extractEd25519RawPublicKeyHex(publicKeyPem) {
|
|
46
|
+
const keyObj = crypto.createPublicKey({ key: publicKeyPem, format: 'pem', type: 'spki' });
|
|
47
|
+
if (keyObj.asymmetricKeyType !== 'ed25519') {
|
|
48
|
+
throw new KSevenWebSdkError(403, 'INVALID_PUBLIC_KEY', 'Chave pública fornecida não é Ed25519.');
|
|
49
|
+
}
|
|
50
|
+
const der = keyObj.export({ format: 'der', type: 'spki' });
|
|
51
|
+
if (der.length < 32) {
|
|
52
|
+
throw new KSevenWebSdkError(403, 'INVALID_PUBLIC_KEY', 'Estrutura SPKI Ed25519 inválida.');
|
|
53
|
+
}
|
|
54
|
+
return der.subarray(der.length - 32).toString('hex');
|
|
55
|
+
}
|
|
56
|
+
static generateClientEd25519KeyPair() {
|
|
57
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519', {
|
|
58
|
+
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|
59
|
+
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
|
|
60
|
+
});
|
|
61
|
+
return {
|
|
62
|
+
clientPublicKeyPem: publicKey,
|
|
63
|
+
clientPrivateKeyPem: privateKey
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Cifra e codifica estado local no formato `k7st.v1.<saltB64Url>.<ivB64Url>.<tagB64Url>.<cipherB64Url>`
|
|
68
|
+
* usando AES-256-GCM + HKDF-SHA256.
|
|
69
|
+
*/
|
|
70
|
+
static encodeEncryptedState(stateObj, secretInput) {
|
|
71
|
+
const masterSecret = this.resolveDefaultStateSecret(secretInput);
|
|
72
|
+
const salt = crypto.randomBytes(16);
|
|
73
|
+
const key = Buffer.from(crypto.hkdfSync('sha256', Buffer.from(masterSecret, 'utf8'), salt, Buffer.from('k7-web-state-v1', 'utf8'), 32));
|
|
74
|
+
const iv = crypto.randomBytes(12);
|
|
75
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
76
|
+
cipher.setAAD(Buffer.from('k7st.v1', 'utf8'));
|
|
77
|
+
const plaintext = Buffer.from(JSON.stringify(stateObj), 'utf8');
|
|
78
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
79
|
+
const tag = cipher.getAuthTag();
|
|
80
|
+
return `k7st.v1.${salt.toString('base64url')}.${iv.toString('base64url')}.${tag.toString('base64url')}.${ciphertext.toString('base64url')}`;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Decifra estado local `k7st.v1...` (ou lê JSON legado caso exista arquivo anterior à migração).
|
|
84
|
+
*/
|
|
85
|
+
static decodeEncryptedState(rawContent, secretInput) {
|
|
86
|
+
const trimmed = String(rawContent || '').trim();
|
|
87
|
+
if (!trimmed) {
|
|
88
|
+
throw new KSevenWebSdkError(400, 'EMPTY_STATE', 'Arquivo de estado da licença está vazio.');
|
|
89
|
+
}
|
|
90
|
+
if (trimmed.startsWith('{')) {
|
|
91
|
+
return JSON.parse(trimmed);
|
|
92
|
+
}
|
|
93
|
+
const parts = trimmed.split('.');
|
|
94
|
+
if (parts.length !== 6 || parts[0] !== 'k7st' || parts[1] !== 'v1') {
|
|
95
|
+
throw new KSevenWebSdkError(400, 'CORRUPTED_STATE_FORMAT', 'Formato de estado criptografado inválido ou adulterado.');
|
|
96
|
+
}
|
|
97
|
+
const salt = Buffer.from(parts[2], 'base64url');
|
|
98
|
+
const iv = Buffer.from(parts[3], 'base64url');
|
|
99
|
+
const tag = Buffer.from(parts[4], 'base64url');
|
|
100
|
+
const ciphertext = Buffer.from(parts[5], 'base64url');
|
|
101
|
+
const masterSecret = this.resolveDefaultStateSecret(secretInput);
|
|
102
|
+
const key = Buffer.from(crypto.hkdfSync('sha256', Buffer.from(masterSecret, 'utf8'), salt, Buffer.from('k7-web-state-v1', 'utf8'), 32));
|
|
103
|
+
try {
|
|
104
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
105
|
+
decipher.setAAD(Buffer.from('k7st.v1', 'utf8'));
|
|
106
|
+
decipher.setAuthTag(tag);
|
|
107
|
+
const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
|
108
|
+
return JSON.parse(plain);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
throw new KSevenWebSdkError(403, 'STATE_DECRYPT_FAILED', 'Não foi possível decifrar o arquivo de estado da licença. Verifique K7_WEB_STATE_SECRET ou reinstale.');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Inicia par de chaves efêmero ECDH P-256 para negociação de sessão cifrada de transporte.
|
|
116
|
+
*/
|
|
117
|
+
static createClientEphemeralKeyPair() {
|
|
118
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {
|
|
119
|
+
namedCurve: 'prime256v1'
|
|
120
|
+
});
|
|
121
|
+
const spkiDer = publicKey.export({ format: 'der', type: 'spki' });
|
|
122
|
+
return {
|
|
123
|
+
clientPublicKeySpkiBase64: spkiDer.toString('base64'),
|
|
124
|
+
privateKey
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
static deriveWireSessionFromServerResponse(privateKey, sessionId, serverPublicKeySpkiBase64, expiresInSeconds = 1800) {
|
|
128
|
+
const serverDer = Buffer.from(serverPublicKeySpkiBase64, 'base64');
|
|
129
|
+
const serverKey = crypto.createPublicKey({ key: serverDer, format: 'der', type: 'spki' });
|
|
130
|
+
const sharedSecret = crypto.diffieHellman({ privateKey, publicKey: serverKey });
|
|
131
|
+
const aesKey = Buffer.from(crypto.hkdfSync('sha256', sharedSecret, Buffer.from(sessionId, 'utf8'), Buffer.from('k7-web-wire-v1', 'utf8'), 32));
|
|
132
|
+
return {
|
|
133
|
+
sessionId,
|
|
134
|
+
aesKey,
|
|
135
|
+
expiresAtMs: Date.now() + Math.max(60, expiresInSeconds - 30) * 1000
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
static sealWirePayload(payload, aesKey, aad) {
|
|
139
|
+
const iv = crypto.randomBytes(12);
|
|
140
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
|
|
141
|
+
cipher.setAAD(Buffer.from(aad, 'utf8'));
|
|
142
|
+
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
|
|
143
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
144
|
+
const tag = cipher.getAuthTag();
|
|
145
|
+
return `k7seal.v1.${iv.toString('base64url')}.${tag.toString('base64url')}.${ciphertext.toString('base64url')}`;
|
|
146
|
+
}
|
|
147
|
+
static unsealWirePayload(sealedEnvelope, aesKey, aad) {
|
|
148
|
+
const parts = String(sealedEnvelope || '').split('.');
|
|
149
|
+
if (parts.length !== 5 || parts[0] !== 'k7seal' || parts[1] !== 'v1') {
|
|
150
|
+
throw new KSevenWebSdkError(400, 'INVALID_SEALED_RESPONSE', 'Envelope de resposta criptografado inválido.');
|
|
151
|
+
}
|
|
152
|
+
const iv = Buffer.from(parts[2], 'base64url');
|
|
153
|
+
const tag = Buffer.from(parts[3], 'base64url');
|
|
154
|
+
const ciphertext = Buffer.from(parts[4], 'base64url');
|
|
155
|
+
try {
|
|
156
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, iv);
|
|
157
|
+
decipher.setAAD(Buffer.from(aad, 'utf8'));
|
|
158
|
+
decipher.setAuthTag(tag);
|
|
159
|
+
const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
|
160
|
+
return JSON.parse(plain);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
throw new KSevenWebSdkError(403, 'SEALED_RESPONSE_AUTH_FAILED', 'Falha ao autenticar/decifrar envelope de resposta k7seal.v1 (tag GCM ou AAD divergente).');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
static verifyKeyTransitionProof(proof, signerPublicKeyPem, expectedToKeyId, expectedToPublicKeyRawHex, nowMs = Date.now()) {
|
|
167
|
+
if (!proof || proof.schema !== 'k7web-key-transition|v1' || !proof.signatureBase64) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (expectedToKeyId && proof.toKeyId !== expectedToKeyId)
|
|
171
|
+
return false;
|
|
172
|
+
if (expectedToPublicKeyRawHex &&
|
|
173
|
+
proof.toPublicKeyRawHex.toLowerCase() !== expectedToPublicKeyRawHex.toLowerCase()) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
const expiresMs = Date.parse(proof.expiresAt);
|
|
177
|
+
if (!Number.isFinite(expiresMs) || expiresMs <= nowMs)
|
|
178
|
+
return false;
|
|
179
|
+
const canonical = [
|
|
180
|
+
proof.schema,
|
|
181
|
+
proof.fromKeyId,
|
|
182
|
+
String(proof.fromKeyVersion),
|
|
183
|
+
proof.toKeyId,
|
|
184
|
+
String(proof.toKeyVersion),
|
|
185
|
+
proof.toPublicKeyRawHex.toLowerCase(),
|
|
186
|
+
proof.issuedAt,
|
|
187
|
+
proof.expiresAt,
|
|
188
|
+
proof.reason
|
|
189
|
+
].join('|');
|
|
190
|
+
try {
|
|
191
|
+
return crypto.verify(null, Buffer.from(canonical, 'utf8'), signerPublicKeyPem, Buffer.from(proof.signatureBase64, 'base64'));
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
static resolveTrustedKeysFromBundle(bundle, pinnedRootPublicKeyPem, explicitPinnedKeys, nowMs = Date.now()) {
|
|
198
|
+
const trusted = {};
|
|
199
|
+
const candidates = [
|
|
200
|
+
...(bundle.activeKey ? [bundle.activeKey] : []),
|
|
201
|
+
...(Array.isArray(bundle.secondaryKeys) ? bundle.secondaryKeys : []),
|
|
202
|
+
...(Array.isArray(bundle.keys) ? bundle.keys : [])
|
|
203
|
+
];
|
|
204
|
+
const dedup = new Map();
|
|
205
|
+
for (const c of candidates) {
|
|
206
|
+
if (c?.keyId && c?.publicKeyPem && !dedup.has(c.keyId)) {
|
|
207
|
+
dedup.set(c.keyId, c);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const entries = Array.from(dedup.values());
|
|
211
|
+
const effectiveRootPem = pinnedRootPublicKeyPem || bundle.rootKey?.publicKeyPem || '';
|
|
212
|
+
if (pinnedRootPublicKeyPem && bundle.rootKey?.publicKeyPem) {
|
|
213
|
+
const pinnedHex = this.extractEd25519RawPublicKeyHex(pinnedRootPublicKeyPem);
|
|
214
|
+
const bundleRootHex = this.extractEd25519RawPublicKeyHex(bundle.rootKey.publicKeyPem);
|
|
215
|
+
if (pinnedHex !== bundleRootHex) {
|
|
216
|
+
throw new KSevenWebSdkError(403, 'WEB_ROOT_KEY_MISMATCH', 'Chave raiz publicada pelo servidor diverge da chave raiz Ed25519 pinada no SDK.');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (effectiveRootPem) {
|
|
220
|
+
// 1) Chaves diretamente endossadas pela chave raiz via rootProof
|
|
221
|
+
for (const entry of entries) {
|
|
222
|
+
const rawHex = this.extractEd25519RawPublicKeyHex(entry.publicKeyPem);
|
|
223
|
+
if (entry.publicKeyRawHex && rawHex !== entry.publicKeyRawHex.toLowerCase())
|
|
224
|
+
continue;
|
|
225
|
+
if (entry.rootProof &&
|
|
226
|
+
this.verifyKeyTransitionProof(entry.rootProof, effectiveRootPem, entry.keyId, rawHex, nowMs)) {
|
|
227
|
+
trusted[entry.keyId] = entry.publicKeyPem;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
// 2) Chaves encadeadas via transitionProof assinada por chave operacional já confiável
|
|
231
|
+
let progress = true;
|
|
232
|
+
while (progress) {
|
|
233
|
+
progress = false;
|
|
234
|
+
for (const entry of entries) {
|
|
235
|
+
if (trusted[entry.keyId] || !entry.transitionProof)
|
|
236
|
+
continue;
|
|
237
|
+
const signerPem = trusted[entry.transitionProof.fromKeyId];
|
|
238
|
+
if (!signerPem)
|
|
239
|
+
continue;
|
|
240
|
+
const rawHex = this.extractEd25519RawPublicKeyHex(entry.publicKeyPem);
|
|
241
|
+
if ((!entry.publicKeyRawHex || rawHex === entry.publicKeyRawHex.toLowerCase()) &&
|
|
242
|
+
this.verifyKeyTransitionProof(entry.transitionProof, signerPem, entry.keyId, rawHex, nowMs)) {
|
|
243
|
+
trusted[entry.keyId] = entry.publicKeyPem;
|
|
244
|
+
progress = true;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// Se nenhuma chave raiz foi pinada e o servidor está em modo legado sem provas, aceita bundle publicado
|
|
250
|
+
if (!pinnedRootPublicKeyPem && Object.keys(trusted).length === 0) {
|
|
251
|
+
for (const entry of entries) {
|
|
252
|
+
trusted[entry.keyId] = entry.publicKeyPem;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// Chaves explícitas pinadas por keyId sempre prevalecem
|
|
256
|
+
if (explicitPinnedKeys) {
|
|
257
|
+
for (const [keyId, pem] of Object.entries(explicitPinnedKeys)) {
|
|
258
|
+
if (keyId && pem)
|
|
259
|
+
trusted[keyId] = pem;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return trusted;
|
|
263
|
+
}
|
|
264
|
+
static verifyEcdhHandshakeSignature(params) {
|
|
265
|
+
const hs = params.handshakeSignature;
|
|
266
|
+
if (!hs || hs.schema !== 'k7-web-ecdh-sig-v1' || !hs.signatureBase64 || !hs.keyId) {
|
|
267
|
+
throw new KSevenWebSdkError(403, 'MISSING_HANDSHAKE_SIGNATURE', 'Resposta de /session-key sem assinatura Ed25519 de handshake.');
|
|
268
|
+
}
|
|
269
|
+
const publicKeyPem = params.trustedKeys[hs.keyId];
|
|
270
|
+
if (!publicKeyPem) {
|
|
271
|
+
throw new KSevenWebSdkError(403, 'UNTRUSTED_HANDSHAKE_KEY', `Chave Ed25519 do handshake ECDH não é confiável (keyId=${hs.keyId}).`);
|
|
272
|
+
}
|
|
273
|
+
if (hs.nonce !== params.expectedNonce) {
|
|
274
|
+
throw new KSevenWebSdkError(403, 'HANDSHAKE_NONCE_MISMATCH', 'Nonce retornado no handshake ECDH diverge do nonce enviado pelo cliente.');
|
|
275
|
+
}
|
|
276
|
+
const tsMs = Date.parse(hs.timestamp);
|
|
277
|
+
const maxAge = (params.maxAgeSeconds ?? 300) * 1000;
|
|
278
|
+
if (!Number.isFinite(tsMs) || Math.abs(Date.now() - tsMs) > maxAge) {
|
|
279
|
+
throw new KSevenWebSdkError(403, 'HANDSHAKE_TIMESTAMP_INVALID', 'Timestamp do handshake ECDH fora da janela permitida.');
|
|
280
|
+
}
|
|
281
|
+
const clientPublicKeySha256 = crypto
|
|
282
|
+
.createHash('sha256')
|
|
283
|
+
.update(Buffer.from(params.clientPublicKeySpkiBase64, 'base64'))
|
|
284
|
+
.digest('hex');
|
|
285
|
+
const canonical = [
|
|
286
|
+
hs.schema,
|
|
287
|
+
params.sessionId,
|
|
288
|
+
params.serverPublicKeySpkiBase64,
|
|
289
|
+
params.fingerprintSha256,
|
|
290
|
+
clientPublicKeySha256,
|
|
291
|
+
hs.timestamp,
|
|
292
|
+
String(params.expiresInSeconds),
|
|
293
|
+
hs.nonce
|
|
294
|
+
].join('|');
|
|
295
|
+
let ok = false;
|
|
296
|
+
try {
|
|
297
|
+
ok = crypto.verify(null, Buffer.from(canonical, 'utf8'), publicKeyPem, Buffer.from(hs.signatureBase64, 'base64'));
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
ok = false;
|
|
301
|
+
}
|
|
302
|
+
if (!ok) {
|
|
303
|
+
throw new KSevenWebSdkError(403, 'INVALID_HANDSHAKE_SIGNATURE', `Assinatura Ed25519 do handshake ECDH inválida para keyId=${hs.keyId}.`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
static verifyRuntimeResponseSignature(params) {
|
|
307
|
+
const env = params.responseBody?.signatureEnvelope;
|
|
308
|
+
if (!env || env.schema !== 'k7-web-response-sig-v1' || !env.signatureBase64 || !env.keyId) {
|
|
309
|
+
throw new KSevenWebSdkError(403, 'MISSING_RESPONSE_SIGNATURE', 'Resposta de runtime sem signatureEnvelope Ed25519.');
|
|
310
|
+
}
|
|
311
|
+
const publicKeyPem = params.trustedKeys[env.keyId];
|
|
312
|
+
if (!publicKeyPem) {
|
|
313
|
+
throw new KSevenWebSdkError(403, 'UNTRUSTED_RESPONSE_SIGNING_KEY', `Chave Ed25519 da resposta de runtime não é confiável (keyId=${env.keyId}).`);
|
|
314
|
+
}
|
|
315
|
+
if (params.expectedNonce !== undefined && env.nonce !== params.expectedNonce) {
|
|
316
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_NONCE_MISMATCH', 'Nonce do envelope assinado diverge do nonce enviado na requisição.');
|
|
317
|
+
}
|
|
318
|
+
if (env.method.toUpperCase() !== params.expectedMethod.toUpperCase()) {
|
|
319
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_METHOD_MISMATCH', 'Método HTTP do envelope assinado diverge da requisição.');
|
|
320
|
+
}
|
|
321
|
+
if (env.path !== params.expectedPath) {
|
|
322
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_PATH_MISMATCH', 'Rota do envelope assinado diverge da requisição.');
|
|
323
|
+
}
|
|
324
|
+
if (env.httpStatus !== params.expectedHttpStatus) {
|
|
325
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_STATUS_MISMATCH', 'Status HTTP do envelope assinado diverge da resposta recebida.');
|
|
326
|
+
}
|
|
327
|
+
const tsMs = Date.parse(env.timestamp);
|
|
328
|
+
const maxAge = (params.maxAgeSeconds ?? 300) * 1000;
|
|
329
|
+
if (!Number.isFinite(tsMs) || Math.abs(Date.now() - tsMs) > maxAge) {
|
|
330
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_TIMESTAMP_OUT_OF_WINDOW', 'Timestamp da assinatura da resposta fora da janela permitida.');
|
|
331
|
+
}
|
|
332
|
+
const unsignedCopy = { ...params.responseBody };
|
|
333
|
+
delete unsignedCopy.signatureEnvelope;
|
|
334
|
+
const computedHash = this.sha256CanonicalJson(unsignedCopy);
|
|
335
|
+
if (computedHash !== env.payloadSha256) {
|
|
336
|
+
throw new KSevenWebSdkError(403, 'RESPONSE_PAYLOAD_TAMPERED', 'Hash SHA-256 do payload diverge do signatureEnvelope assinado.');
|
|
337
|
+
}
|
|
338
|
+
const canonical = [
|
|
339
|
+
env.schema,
|
|
340
|
+
env.protocolVersion,
|
|
341
|
+
env.keyId,
|
|
342
|
+
String(env.keyVersion),
|
|
343
|
+
env.rootKeyId,
|
|
344
|
+
env.requestId,
|
|
345
|
+
env.nonce,
|
|
346
|
+
env.method.toUpperCase(),
|
|
347
|
+
env.path,
|
|
348
|
+
env.timestamp,
|
|
349
|
+
String(env.httpStatus),
|
|
350
|
+
env.decision,
|
|
351
|
+
env.code,
|
|
352
|
+
env.productSlug || '',
|
|
353
|
+
env.licenseId !== null && env.licenseId !== undefined ? String(env.licenseId) : '',
|
|
354
|
+
env.installationId || '',
|
|
355
|
+
env.domain || '',
|
|
356
|
+
env.licenseStatus || '',
|
|
357
|
+
env.expiresAt || '',
|
|
358
|
+
env.entitlementHash || '',
|
|
359
|
+
env.payloadSha256
|
|
360
|
+
].join('|');
|
|
361
|
+
let ok = false;
|
|
362
|
+
try {
|
|
363
|
+
ok = crypto.verify(null, Buffer.from(canonical, 'utf8'), publicKeyPem, Buffer.from(env.signatureBase64, 'base64'));
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
ok = false;
|
|
367
|
+
}
|
|
368
|
+
if (!ok) {
|
|
369
|
+
throw new KSevenWebSdkError(403, 'INVALID_RESPONSE_SIGNATURE', `Assinatura Ed25519 da resposta de runtime inválida para keyId=${env.keyId}.`);
|
|
370
|
+
}
|
|
371
|
+
return { keyId: env.keyId };
|
|
372
|
+
}
|
|
373
|
+
static signClientRequest(params) {
|
|
374
|
+
const bodySha256 = this.sha256CanonicalJson(params.body || {});
|
|
375
|
+
const canonical = [
|
|
376
|
+
'k7web-client-req|v1',
|
|
377
|
+
params.method.toUpperCase(),
|
|
378
|
+
params.path,
|
|
379
|
+
params.timestamp,
|
|
380
|
+
params.nonce,
|
|
381
|
+
params.installationId,
|
|
382
|
+
bodySha256
|
|
383
|
+
].join('|');
|
|
384
|
+
return crypto
|
|
385
|
+
.sign(null, Buffer.from(canonical, 'utf8'), params.clientPrivateKeyPem)
|
|
386
|
+
.toString('base64');
|
|
387
|
+
}
|
|
388
|
+
static verifyEd25519Manifest(params) {
|
|
389
|
+
let valid = false;
|
|
390
|
+
try {
|
|
391
|
+
valid = crypto.verify(null, Buffer.from(params.manifestJson, 'utf8'), params.publicKeyPem, Buffer.from(params.manifestSignature, 'base64'));
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
valid = false;
|
|
395
|
+
}
|
|
396
|
+
if (!valid) {
|
|
397
|
+
throw new KSevenWebSdkError(403, 'INVALID_RELEASE_SIGNATURE', `Assinatura Ed25519 do manifesto rejeitada para keyId=${params.signingKeyId}.`);
|
|
398
|
+
}
|
|
399
|
+
const parsed = JSON.parse(params.manifestJson);
|
|
400
|
+
if (parsed?.schema !== 'k7-web-release-v1') {
|
|
401
|
+
throw new KSevenWebSdkError(403, 'INVALID_MANIFEST_SCHEMA', 'Esquema de manifesto desconhecido.');
|
|
402
|
+
}
|
|
403
|
+
return parsed;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Valida offline o último `signatureEnvelope` Ed25519 salvo em cache criptografado,
|
|
407
|
+
* garantindo integridade do payload, status ativo (não REVOKED/SUSPENDED),
|
|
408
|
+
* correspondência de instalação/domínio e janela de carência `graceUntil`.
|
|
409
|
+
*/
|
|
410
|
+
static verifyCachedOfflineEntitlement(params) {
|
|
411
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
412
|
+
const cached = params.cachedResponse;
|
|
413
|
+
if (!cached || typeof cached !== 'object' || !cached.signatureEnvelope) {
|
|
414
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_CACHE_MISSING', 'Nenhum comprovante assinado Ed25519 disponível em cache para validação offline.');
|
|
415
|
+
}
|
|
416
|
+
const env = cached.signatureEnvelope;
|
|
417
|
+
if (env.schema !== 'k7-web-response-sig-v1' || !env.signatureBase64 || !env.keyId) {
|
|
418
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_CACHE_INVALID', 'Envelope de assinatura em cache offline é inválido.');
|
|
419
|
+
}
|
|
420
|
+
const publicKeyPem = params.trustedKeys[env.keyId];
|
|
421
|
+
if (!publicKeyPem) {
|
|
422
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_UNTRUSTED_KEY', `Chave Ed25519 do cache offline não é confiável (keyId=${env.keyId}).`);
|
|
423
|
+
}
|
|
424
|
+
if (env.decision !== 'ALLOW' || (env.httpStatus !== 200 && env.httpStatus !== 201)) {
|
|
425
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_CACHE_NOT_ALLOWED', 'Última resposta assinada em cache não autoriza operação offline.');
|
|
426
|
+
}
|
|
427
|
+
if (env.installationId && env.installationId !== params.expectedInstallationId) {
|
|
428
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_INSTALLATION_MISMATCH', 'Cache offline não pertence à instalação atual.');
|
|
429
|
+
}
|
|
430
|
+
if (env.domain && env.domain.toLowerCase() !== params.expectedDomain.toLowerCase()) {
|
|
431
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_DOMAIN_MISMATCH', 'Cache offline não pertence ao domínio atual.');
|
|
432
|
+
}
|
|
433
|
+
const unsignedCopy = { ...cached };
|
|
434
|
+
delete unsignedCopy.signatureEnvelope;
|
|
435
|
+
const computedHash = this.sha256CanonicalJson(unsignedCopy);
|
|
436
|
+
if (computedHash !== env.payloadSha256) {
|
|
437
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_CACHE_TAMPERED', 'Integridade SHA-256 do cache offline violada.');
|
|
438
|
+
}
|
|
439
|
+
const canonical = [
|
|
440
|
+
env.schema,
|
|
441
|
+
env.protocolVersion,
|
|
442
|
+
env.keyId,
|
|
443
|
+
String(env.keyVersion),
|
|
444
|
+
env.rootKeyId,
|
|
445
|
+
env.requestId,
|
|
446
|
+
env.nonce,
|
|
447
|
+
env.method.toUpperCase(),
|
|
448
|
+
env.path,
|
|
449
|
+
env.timestamp,
|
|
450
|
+
String(env.httpStatus),
|
|
451
|
+
env.decision,
|
|
452
|
+
env.code,
|
|
453
|
+
env.productSlug || '',
|
|
454
|
+
env.licenseId !== null && env.licenseId !== undefined ? String(env.licenseId) : '',
|
|
455
|
+
env.installationId || '',
|
|
456
|
+
env.domain || '',
|
|
457
|
+
env.licenseStatus || '',
|
|
458
|
+
env.expiresAt || '',
|
|
459
|
+
env.entitlementHash || '',
|
|
460
|
+
env.payloadSha256
|
|
461
|
+
].join('|');
|
|
462
|
+
let sigOk = false;
|
|
463
|
+
try {
|
|
464
|
+
sigOk = crypto.verify(null, Buffer.from(canonical, 'utf8'), publicKeyPem, Buffer.from(env.signatureBase64, 'base64'));
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
sigOk = false;
|
|
468
|
+
}
|
|
469
|
+
if (!sigOk) {
|
|
470
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_SIGNATURE_INVALID', 'Assinatura Ed25519 do comprovante offline inválida.');
|
|
471
|
+
}
|
|
472
|
+
const entitlement = cached.entitlement;
|
|
473
|
+
if (!entitlement || typeof entitlement !== 'object') {
|
|
474
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_ENTITLEMENT_MISSING', 'Payload de entitlement ausente no cache offline.');
|
|
475
|
+
}
|
|
476
|
+
const status = String(entitlement.licenseStatus || env.licenseStatus || '').toUpperCase();
|
|
477
|
+
const hardRevoke = Array.isArray(entitlement.offlineValidation?.hardRevokeStatuses)
|
|
478
|
+
? entitlement.offlineValidation.hardRevokeStatuses.map((s) => String(s).toUpperCase())
|
|
479
|
+
: ['REVOKED', 'SUSPENDED'];
|
|
480
|
+
if (hardRevoke.includes(status) || (status !== 'ACTIVE' && !entitlement.inGracePeriod)) {
|
|
481
|
+
throw new KSevenWebSdkError(403, 'LICENSE_HARD_REVOKED', `Operação offline bloqueada para licença em status ${status || 'DESCONHECIDO'}.`);
|
|
482
|
+
}
|
|
483
|
+
if (entitlement.offlineValidation && entitlement.offlineValidation.allowed === false) {
|
|
484
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_GRACE_DISABLED', 'A política desta licença não permite operação offline em carência.');
|
|
485
|
+
}
|
|
486
|
+
const graceUntil = String(entitlement.offlineValidation?.graceUntil || entitlement.graceUntil || '').trim();
|
|
487
|
+
const graceMs = Date.parse(graceUntil);
|
|
488
|
+
if (!graceUntil || !Number.isFinite(graceMs) || nowMs > graceMs) {
|
|
489
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_GRACE_EXPIRED', 'Período de carência offline expirado. Reconecte à API K’Seven para revalidar.');
|
|
490
|
+
}
|
|
491
|
+
const issuedMs = Date.parse(env.timestamp);
|
|
492
|
+
if (!Number.isFinite(issuedMs) || issuedMs > nowMs + 5 * 60 * 1000) {
|
|
493
|
+
throw new KSevenWebSdkError(403, 'OFFLINE_CLOCK_TAMPERED', 'Relógio local inconsistente com a data de emissão do comprovante assinado.');
|
|
494
|
+
}
|
|
495
|
+
return {
|
|
496
|
+
keyId: env.keyId,
|
|
497
|
+
graceUntil,
|
|
498
|
+
entitlement,
|
|
499
|
+
issuedAt: env.timestamp
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { WebSdkPersistedState, WebSdkStateStore } from '../types.js';
|
|
2
|
+
export declare class EncryptedStateStore implements WebSdkStateStore {
|
|
3
|
+
private readonly filePath;
|
|
4
|
+
private readonly secret?;
|
|
5
|
+
constructor(filePath: string, secret?: string);
|
|
6
|
+
read(): Promise<WebSdkPersistedState | null>;
|
|
7
|
+
write(state: WebSdkPersistedState | null): Promise<void>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { KSevenCodec } from '../crypto/KSevenCodec.js';
|
|
5
|
+
export class EncryptedStateStore {
|
|
6
|
+
filePath;
|
|
7
|
+
secret;
|
|
8
|
+
constructor(filePath, secret) {
|
|
9
|
+
this.filePath = path.resolve(filePath);
|
|
10
|
+
this.secret = secret;
|
|
11
|
+
}
|
|
12
|
+
async read() {
|
|
13
|
+
try {
|
|
14
|
+
const content = await fs.readFile(this.filePath, 'utf8');
|
|
15
|
+
if (!content.trim())
|
|
16
|
+
return null;
|
|
17
|
+
return KSevenCodec.decodeEncryptedState(content, this.secret);
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
if (err?.code === 'ENOENT')
|
|
21
|
+
return null;
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async write(state) {
|
|
26
|
+
if (!state) {
|
|
27
|
+
await fs.unlink(this.filePath).catch((err) => {
|
|
28
|
+
if (err?.code !== 'ENOENT')
|
|
29
|
+
throw err;
|
|
30
|
+
});
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
|
|
34
|
+
const sealed = KSevenCodec.encodeEncryptedState(state, this.secret);
|
|
35
|
+
const tmpPath = `${this.filePath}.tmp-${crypto.randomBytes(4).toString('hex')}`;
|
|
36
|
+
await fs.writeFile(tmpPath, sealed, { encoding: 'utf8', mode: 0o600 });
|
|
37
|
+
await fs.rename(tmpPath, this.filePath);
|
|
38
|
+
await fs.chmod(this.filePath, 0o600).catch(() => { });
|
|
39
|
+
}
|
|
40
|
+
}
|