@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 ADDED
@@ -0,0 +1,71 @@
1
+ # @kseven/web-license-sdk
2
+
3
+ SDK oficial servidor-side (Node.js / TypeScript) para o domínio de **Licenciamento Web K'Seven** (`/api/web/license/v1/*`).
4
+
5
+ ## Instalação (npm / pnpm / yarn)
6
+
7
+ ```bash
8
+ # Via registro privado ou tarball gerado com `npm pack`
9
+ npm install @kseven/web-license-sdk
10
+ # Ou localmente a partir do repositório
11
+ npm install ./sdk-web/nodejs
12
+ ```
13
+
14
+ ## Recursos de Segurança
15
+
16
+ - **Transporte Cifrado (ECDH P-256 + HKDF-SHA256 + AES-256-GCM)**: negociação automática de chave de sessão em `/api/web/license/v1/session-key` e envelope `k7seal.v1` autenticado com AAD (`METHOD:/path`).
17
+ - **Estado Local Criptografado (`k7st.v1`)**: credenciais de instalação (`k7i_*`) gravadas em `.kseven-web-license.dat` (permissão `0600`) cifradas com AES-256-GCM + HKDF-SHA256 (suporte a `K7_WEB_STATE_SECRET`).
18
+ - **Verificação Criptográfica de Releases**: assinatura **Ed25519** do manifesto + conferência **SHA-256** antes da gravação em disco com proteção anti *path traversal*.
19
+
20
+ ## Uso Rápido
21
+
22
+ ```ts
23
+ import { KSevenWebLicenseSdk } from '@kseven/web-license-sdk';
24
+
25
+ const sdk = new KSevenWebLicenseSdk({
26
+ apiBaseUrl: 'https://api.kseven.com.br',
27
+ stateSecret: process.env.K7_WEB_STATE_SECRET,
28
+ useEncryptedTransport: true
29
+ });
30
+
31
+ await sdk.install({
32
+ licenseKey: process.env.K7_WEB_LICENSE_KEY!,
33
+ domain: 'meusite.com.br',
34
+ appVersion: '1.0.0'
35
+ });
36
+
37
+ const check = await sdk.checkVersion({ channel: 'stable', includeRollbacks: true });
38
+ if (check.updateAvailable) {
39
+ await sdk.update({ channel: 'stable', destDir: './updates' });
40
+ }
41
+
42
+ // Operação offline durante queda momentânea de rede (fail-closed após graceUntil)
43
+ const offline = await sdk.validateOffline();
44
+ console.log('Offline válido até:', offline.graceUntil);
45
+
46
+ // Listar releases compatíveis (PRODUCT, UPDATE, PLUGIN) e versões de rollback
47
+ const releases = await sdk.listCompatibleReleases({ channel: 'stable' });
48
+
49
+ // Transferir instalação para novo servidor sem nova compra
50
+ await sdk.transferInstallation({
51
+ toDomain: 'novoservidor.meusite.com.br',
52
+ toInstanceFingerprint: 'srv-nvme-02',
53
+ reason: 'Migração de infraestrutura'
54
+ });
55
+
56
+ await sdk.uninstall();
57
+ ```
58
+
59
+ ## CLI (`k7web`)
60
+
61
+ ```bash
62
+ npx k7web install --api https://api.kseven.com.br --key k7w_live_... --domain meusite.com.br --app-version 1.0.0
63
+ npx k7web validate --api https://api.kseven.com.br
64
+ npx k7web validate-offline
65
+ npx k7web check-version --api https://api.kseven.com.br --include-rollbacks
66
+ npx k7web list-releases --api https://api.kseven.com.br --release-kind PLUGIN
67
+ npx k7web update --api https://api.kseven.com.br --dest-dir ./updates
68
+ npx k7web transfer --api https://api.kseven.com.br --to-domain novo.meusite.com.br --reason "Troca de VPS"
69
+ npx k7web uninstall --api https://api.kseven.com.br
70
+ ```
71
+
@@ -0,0 +1,147 @@
1
+ import { KSevenCodec } from './crypto/KSevenCodec.js';
2
+ import { EncryptedStateStore } from './storage/EncryptedStateStore.js';
3
+ import { AutoUpdateOptions, AutoUpdateResult, CheckVersionOptions, CheckVersionResult, InstallOptions, KSevenWebSdkConfig, OfflineValidationResult, RollbackOptions, TransferInstallationOptions, UpdateOptions, UpdateResult, ValidateOptions, WebSdkChannel, WebSdkDomainEnvironment, WebSdkPlatform, WebSdkPersistedState } from './types.js';
4
+ export * from './types.js';
5
+ export { KSevenCodec, EncryptedStateStore };
6
+ export declare class KSevenWebLicenseSdk {
7
+ private readonly apiBaseUrl;
8
+ private readonly stateFilePath;
9
+ private readonly defaultPlatform;
10
+ private readonly timeoutMs;
11
+ private readonly allowInsecureLocalHttp;
12
+ private readonly useEncryptedTransport;
13
+ private readonly requireSealedTransport;
14
+ private readonly pinnedRootPublicKeyPem?;
15
+ private readonly verifyResponseSignatures;
16
+ private readonly pinnedPublicKeys;
17
+ private readonly configuredClientPublicKeyPem?;
18
+ private readonly configuredClientPrivateKeyPem?;
19
+ private readonly stateStore;
20
+ private wireSession;
21
+ private discoveredTrustedKeys;
22
+ constructor(config: KSevenWebSdkConfig);
23
+ private assertAllowedEndpointUrl;
24
+ private resolveSafeChildPath;
25
+ readState(): Promise<WebSdkPersistedState | null>;
26
+ private writeState;
27
+ private requireState;
28
+ /**
29
+ * Obtém bundle de chaves públicas Ed25519 (ativa + secundárias + raiz) em `/keys` (fallback `/releases/public-key`)
30
+ * e valida cadeia `rootProof` / `transitionProof` contra `pinnedRootPublicKeyPem` quando configurada.
31
+ */
32
+ fetchPublicKeysMap(forceRefresh?: boolean): Promise<Record<string, string>>;
33
+ private verifySignedEnvelopeWithRefresh;
34
+ private ensureWireSession;
35
+ private resolveClientSigningContext;
36
+ private apiRequest;
37
+ createDomainChallenge(params: {
38
+ licenseKey: string;
39
+ domain: string;
40
+ method: 'DNS_TXT' | 'WELL_KNOWN_HTTP';
41
+ environment?: WebSdkDomainEnvironment;
42
+ allowSubdomains?: boolean;
43
+ }): Promise<any>;
44
+ verifyDomainChallenge(challengeId: string, licenseKey?: string): Promise<any>;
45
+ install(options: InstallOptions): Promise<{
46
+ installed: boolean;
47
+ installationId: string;
48
+ domain: string;
49
+ platform: WebSdkPlatform;
50
+ appVersion: string;
51
+ idempotentReplay: boolean;
52
+ encryptedTransport: boolean;
53
+ clientKeyRegistered: boolean;
54
+ entitlement: any;
55
+ signatureEnvelope: any;
56
+ }>;
57
+ validate(appVersion?: string, options?: ValidateOptions): Promise<any>;
58
+ /**
59
+ * Valida offline o último comprovante Ed25519 assinado em cache local criptografado,
60
+ * respeitando rigorosamente `graceUntil` e bloqueando status `REVOKED`/`SUSPENDED` ou adulterações.
61
+ */
62
+ validateOffline(nowMs?: number): Promise<OfflineValidationResult>;
63
+ /**
64
+ * Solicita transferência/troca de servidor da instalação atual para outro domínio verificado
65
+ * da mesma licença sem exigir nova compra. Atualiza ou limpa o estado cifrado local conforme resultado.
66
+ */
67
+ transferInstallation(options: TransferInstallationOptions): Promise<any>;
68
+ entitlements(): Promise<any>;
69
+ acquireLease(ttlSeconds?: number, idempotencyKey?: string): Promise<any>;
70
+ heartbeatLease(leaseId: string, leaseToken?: string): Promise<any>;
71
+ releaseLease(leaseId: string): Promise<any>;
72
+ listCompatibleReleases(options?: CheckVersionOptions): Promise<any>;
73
+ checkVersion(options?: CheckVersionOptions): Promise<CheckVersionResult>;
74
+ private downloadAndApplyRelease;
75
+ update(options?: UpdateOptions): Promise<UpdateResult>;
76
+ /**
77
+ * Reporta progresso e resultado de uma execução de auto-update para visibilidade no painel.
78
+ */
79
+ reportAutoUpdateProgress(payload: {
80
+ runUid: string;
81
+ releaseId?: number | null;
82
+ channel?: WebSdkChannel;
83
+ fromVersion: string;
84
+ toVersion: string;
85
+ status: string;
86
+ progressPercent?: number;
87
+ currentStep?: string;
88
+ signatureVerified?: boolean;
89
+ sha256Verified?: boolean;
90
+ backupCreated?: boolean;
91
+ rollbackPerformed?: boolean;
92
+ migrationsExecuted?: string[];
93
+ error?: string | null;
94
+ }): Promise<any>;
95
+ private copyDirectorySafe;
96
+ private restoreDirectoryFromBackup;
97
+ /**
98
+ * Executa atualização Web automática e transacional:
99
+ * 1. Consulta exclusivamente releases compatíveis e autorizadas na sequência contínua.
100
+ * 2. Baixa para área temporária, valida assinatura Ed25519, canal, versão, dependências e SHA-256.
101
+ * 3. Cria backup completo do diretório alvo antes de qualquer modificação.
102
+ * 4. Aplica pacote e executa migrações declaradas em ordem.
103
+ * 5. Em qualquer falha, aborta e restaura o estado anterior integralmente (rollback limpo).
104
+ */
105
+ autoUpdate(options: AutoUpdateOptions): Promise<AutoUpdateResult>;
106
+ /**
107
+ * Faz rollback seguro para uma release anterior compatível e habilitada com `allowRollback`,
108
+ * verificando Ed25519 e SHA-256 antes de gravar ou invocar o callback.
109
+ */
110
+ rollback(releaseId: number, options?: RollbackOptions): Promise<UpdateResult>;
111
+ /**
112
+ * Helpers autenticados por Bearer JWT do painel para integração da Loja in-app em backends intermediários.
113
+ */
114
+ private panelRequest;
115
+ fetchStoreCatalog(jwtToken: string, opts?: {
116
+ licenseId?: number;
117
+ productSlug?: string;
118
+ }): Promise<any>;
119
+ checkStoreCompatibility(jwtToken: string, payload: {
120
+ webLicenseId?: number;
121
+ webProductId?: number;
122
+ webPlanId?: number;
123
+ webAddonId?: number;
124
+ targetVersion?: string;
125
+ invoiceType?: string;
126
+ }): Promise<any>;
127
+ createStoreOrder(jwtToken: string, payload: {
128
+ invoiceType: 'NEW_LICENSE' | 'RENEWAL' | 'ADDON' | 'PLUGIN' | 'UPGRADE' | 'UPDATE_EXTENSION';
129
+ webProductId?: number;
130
+ webPlanId?: number;
131
+ webAddonId?: number;
132
+ webLicenseId?: number;
133
+ quantity?: number;
134
+ orderOrigin?: 'PANEL' | 'IN_APP_STORE' | 'ADMIN';
135
+ }): Promise<any>;
136
+ uninstall(reason?: string): Promise<{
137
+ uninstalled: boolean;
138
+ alreadyUninstalled: boolean;
139
+ installationId: null;
140
+ serverDeactivated?: undefined;
141
+ } | {
142
+ uninstalled: boolean;
143
+ alreadyUninstalled: boolean;
144
+ serverDeactivated: boolean;
145
+ installationId: string;
146
+ }>;
147
+ }