mumpix 1.0.20 → 1.0.29
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/CHANGELOG.md +42 -14
- package/README.md +185 -8
- package/bin/mumpix.js +1 -405
- package/examples/agent-memory.js +1 -1
- package/examples/basic.js +1 -1
- package/examples/behavioral-primitives.js +50 -0
- package/examples/verified-mode.js +1 -1
- package/package.json +17 -13
- package/scripts/test-license-modes.cjs +87 -0
- package/src/brp/index.js +1 -0
- package/src/collapse/index.js +1 -0
- package/src/core/MumpixDB.js +210 -322
- package/src/core/audit.js +1 -173
- package/src/core/auth.js +1 -232
- package/src/core/inverted-index.js +144 -0
- package/src/core/license.js +1 -267
- package/src/core/ml-dsa.mjs +1 -25
- package/src/core/ml-kem.mjs +1 -32
- package/src/core/recall.js +1 -176
- package/src/core/store.js +335 -286
- package/src/core/wal-writer.js +83 -0
- package/src/index.js +20 -34
- package/src/integrations/developer-sdk.js +1 -165
- package/src/integrations/langchain-official.js +1 -0
- package/src/integrations/langchain.js +1 -131
- package/src/integrations/llamaindex-official.js +1 -0
- package/src/integrations/llamaindex.js +1 -86
- package/src/integrations/vector-sidecar.js +325 -0
- package/src/rlp/index.js +1 -0
- package/src/temporal/engine.js +1 -1894
- package/src/temporal/indexes.js +1 -178
- package/src/temporal/operators.js +1 -186
- package/scripts/postinstall-auth.js +0 -101
package/src/core/license.js
CHANGED
|
@@ -1,267 +1 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const crypto = require('crypto');
|
|
4
|
-
const fs = require('fs');
|
|
5
|
-
const os = require('os');
|
|
6
|
-
const https = require('https');
|
|
7
|
-
const path = require('path');
|
|
8
|
-
|
|
9
|
-
// Default embedded public key (official issuer).
|
|
10
|
-
const DEFAULT_MASTER_PUBLIC_KEY_B64 = `NW0JjKYCRfWHp8SPjrQi5A3n3tK694t3u+Gxes6esbA46LXNONbaxn/6GlnaAEasydB+3CrRkpls5mYIl8mx/xXA3e+WgmF4/djS1M1DAex91cfubcCNH7ZP9zpgEE7d9lzBJrB4gRs6niTMPIbP0dB/DVjbUXvO70jigY1A5xLAid1HlrKvIp89qg+pE+PaiZiNp+lHmPszn+Y3Er0zK3E4SWunV5yn1iDYzaw2iCj34t3TK8eqMxknnkaFtOV8qkBG9SBJnsM+kwofNAejYnxLpOx2PzmccsdNSnhg7FEPnP4TQn9JZQnnTQ7SxO8pJpVTcECq8UoxJlfallAnmVcIA7LqiB6HZLGhNmxsGHP9dBk7oC2nZomfKW9gnAKMnlOnyD/OPlXhHUEzm5fIzPGLim2ENMQVtu4dpU9JufLnFgBrulhEVLvIK/p9ro3Mos70yi0aOvpAQaIcSpKCyYctcxopUMoHQqR4V/svcBW8aoJydWFZfqqZ2iTs51r0YDXClb7HF5UaJD0xSogVjhllcUk/zpK6cEDce121TZRdZDRwiiz430hrQTOuj/15mAb7e4uFhZWnHhjI5lDV/i3PMPxGfHboht0sxz7wczSQJFtIGPh4RdELnTPeD/Xbtjrv0bK3KFubsjPzk6WveVIZZOFETTfv4MgCqgSe9NArFTX4HpUjVQ4ATx/zA9DAEpjyL3LmSEksn/ft7sll/ZIB6F0BVVp9dgNxkjUMeNo5IlCWj98z6yWnSVizockxGkrMQbAAuPRRD+3Qrgbz+KDaGTKZZXkfBXZUz6nO8AlMVfUAHeYEA9srlDY2n6CIVm6vDU+XCGx1wtDA6vI3Pb1PTOEn0GbXioLtXzCMbTeW1SwWsOJDLLN8ScN0uOTAY6WqaI6uGY4S8fEaCu4w0FADtf7xptrH2tIcukorySDx0+yBr2QZBsjC1X2sg4o6DcNvZq/ZOB+sRHkQzfhihbw0rXzm4qLnwYLXhIOCodkmch4fd3OPsrF8kEEDKmm4qqOF7cobJFQZsmx3UXFRhfIURw2KlZDUYINPjJgx46Wx5yyINEqbRYRxlmR2Rp1Pw97zyoAPrs+++CNVi1b8cmjA8KVGc9irI47tA7lShGMVSt5/71jiQ+XR6mDgp3BzJxDGAa5KBDsYXGPYwouWb1Rg6Dnao7AHv5/KEhM1P0kQPP+oXkGcoZyQiRpdOeefiZPQ2fUKoy4rfHlx89QGeD/9lM4Cm4hC6Ejo47XgvnM799TTQIFzQXYNFCNppJw8pUyUM/5iFhGgDzXJZ1Rz5qInTouhofQZbF9Yfls/CGUt6mhCZTj/2EWtNSefOXYoDmfReWpdINiTkxjoFhcSLXuG43xxS51S9VkimudforUaqSgolhAsnYNF+peI/dEztwq5/WbrR7lHDSxaAmYPvrM84lNcM2ys7tBkJo+L+UcsCLsAncRorA6/243oOJMapdbFy835tmxwHbHhFm/isXySaNZ2tAvpU9kSgNoGhd5ByDRTzJ1KD/YdfDgql5WCA/jFb0xXr6UjkRLIBw4hNg7Q8W0N9G/XeNdflzmdG/hCrqtQzP4Wio0UZZl083gMDfj31Rfc4T5E782tiCeyqK7MIO92ll147y9qDIFhw57nzSLC367J1L6aQKZauThLdp5gZ/LoFc72zqOdJWhhookAyBc8xUyMXQ5ebiShy3NpLuZogzOUVa5V/N88sMsS0ERdm+wpMoYx4xeoX/cZsoztjkTSX1QL/keP8v+hR6trG8UVgTQAB61usksnJ3rLU8XxtwOP5J4DuiQ9n9FLerMZ81/2t60GrlxqLXSf+f18qxsP+94aaMyYmocEYR81DUzjieFP+2mphWJ995hFpqOadpTb4Rri2kIv6FzZjboWPCLZjreS9u9oggnNJncP2OfB2Uq87PecPhQ0eEuZmL3P1eleWe5WSZmAuuXoIpBbK1BJaJGC0G7eTVZ6BBUVMp34a1waAc66Xjam8VHL+9Lx0c2XFStmPN7+9SvdkStv12O0FOApgpXnsPQiKriIswm0FvZ6DQ5jzAoapyuX0+X0BNyDBbUy+phG/GsNOFQ9ERXFSg8Q+tg0EwgTgvAQn4rVllb1w+SURXaRZ6YBod9BguGW2Oi/qXg9icVmZTz3SFFFBXc33aVc93enOdyj9z9ryvdowoFSpFN8bE0bi0Dgth7BpL82Lzh2y10aV2TH5pTp2H1GqCB1LWDsTVXq4lnUIJ1b+Tg8kHOCs4zAn1oWXKzqgY9CPireCmp78vMJxReTWPaK5/NvC/iMrEKNMUSfHnfjJ2TjURCvrLJsOHfGLQ8ROJBTO+knqh+2IjL/bFP/gYm1ojGxJlB2xbbfP+a9OdvKCR5PbvlU36CcIDIk3DwA9aVxLpWuW4YvjCuLXxpYavenJrPHnapUirfydVtL3qndWaM9WwlgFkM5VUGHomIqH7KYk/ZwhFWvc3lesaC/nTw5JAhcX8tBi1x0en1f6/1na47SQrytJlc/TFX+S+4RkL3fZ90zTggf9CTHhkjxhhdLbsN3jz6HDyWl27OADo/rxd9a6c2fmfdL11ZEnq2W9K9qffAMb5ibOcs=`;
|
|
11
|
-
|
|
12
|
-
function activeMasterPublicKeyB64() {
|
|
13
|
-
return String(process.env.MUMPIX_LICENSE_PUBLIC_KEY_B64 || DEFAULT_MASTER_PUBLIC_KEY_B64).trim();
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function envInt(name, fallback) {
|
|
17
|
-
const raw = process.env[name];
|
|
18
|
-
if (raw == null || raw === '') return fallback;
|
|
19
|
-
const n = Number(raw);
|
|
20
|
-
return Number.isFinite(n) ? n : fallback;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
class LicenseManager {
|
|
24
|
-
constructor(key = null) {
|
|
25
|
-
this.key = key;
|
|
26
|
-
this.tier = 'free';
|
|
27
|
-
this.expiry = null;
|
|
28
|
-
this.verified = false;
|
|
29
|
-
this.userId = 'guest';
|
|
30
|
-
this._ml_dsa = null;
|
|
31
|
-
this.fileId = null;
|
|
32
|
-
this.issuedAt = null;
|
|
33
|
-
this.validationError = '';
|
|
34
|
-
this._licenseFingerprint = key
|
|
35
|
-
? crypto.createHash('sha256').update(String(key), 'utf8').digest('hex')
|
|
36
|
-
: 'free';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
_capsForTier(tier) {
|
|
40
|
-
const t = this._normalizeTier(tier);
|
|
41
|
-
if (t === 'monthly') return { modes: ['eventual', 'strict'] };
|
|
42
|
-
if (t === 'developer') return { modes: ['eventual', 'strict'] };
|
|
43
|
-
if (t === 'standard') return { modes: ['eventual', 'strict'] };
|
|
44
|
-
if (t === 'teams' || t === 'team') return { modes: ['eventual', 'strict'] };
|
|
45
|
-
if (t === 'compliance' || t === 'enterprise' || t === 'government' || t === 'verified' || t === 'pro') {
|
|
46
|
-
return { modes: ['eventual', 'strict', 'verified'] };
|
|
47
|
-
}
|
|
48
|
-
return { modes: ['eventual'] };
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
_normalizeTier(tier) {
|
|
52
|
-
const t = String(tier || 'free').toLowerCase().trim();
|
|
53
|
-
if (t === 'gov' || t === 'public-sector') return 'government';
|
|
54
|
-
if (t === 'team') return 'teams';
|
|
55
|
-
if (t === 'month' || t === 'monthly' || t === 'starter') return 'monthly';
|
|
56
|
-
return t || 'free';
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
_maxDaysForTier(tier) {
|
|
60
|
-
const t = this._normalizeTier(tier);
|
|
61
|
-
if (t === 'monthly') return envInt('MUMPIX_LICENSE_MAX_DAYS_MONTHLY', 45);
|
|
62
|
-
if (t === 'standard') return envInt('MUMPIX_LICENSE_MAX_DAYS_STANDARD', 45);
|
|
63
|
-
if (t === 'developer') return envInt('MUMPIX_LICENSE_MAX_DAYS_DEVELOPER', 365);
|
|
64
|
-
if (t === 'teams') return envInt('MUMPIX_LICENSE_MAX_DAYS_TEAMS', 365);
|
|
65
|
-
if (t === 'enterprise') return envInt('MUMPIX_LICENSE_MAX_DAYS_ENTERPRISE', 36500);
|
|
66
|
-
if (t === 'government') return envInt('MUMPIX_LICENSE_MAX_DAYS_GOVERNMENT', 36500);
|
|
67
|
-
if (t === 'compliance' || t === 'verified' || t === 'pro') {
|
|
68
|
-
return envInt('MUMPIX_LICENSE_MAX_DAYS_COMPLIANCE', 36500);
|
|
69
|
-
}
|
|
70
|
-
return envInt('MUMPIX_LICENSE_MAX_DAYS_FREE', 30);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
_watermarkPath() {
|
|
74
|
-
const custom = String(process.env.MUMPIX_LICENSE_WATERMARK_PATH || '').trim();
|
|
75
|
-
if (custom) return custom;
|
|
76
|
-
return path.join(process.cwd(), '.mumpix-license-watermark.json');
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
_clockSkewMs() {
|
|
80
|
-
return envInt('MUMPIX_LICENSE_CLOCK_SKEW_MS', 6 * 60 * 60 * 1000);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
_loadWatermarkState() {
|
|
84
|
-
const p = this._watermarkPath();
|
|
85
|
-
try {
|
|
86
|
-
const raw = fs.readFileSync(p, 'utf8');
|
|
87
|
-
const parsed = JSON.parse(raw);
|
|
88
|
-
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
89
|
-
} catch {
|
|
90
|
-
return {};
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
_saveWatermarkState(state) {
|
|
95
|
-
const p = this._watermarkPath();
|
|
96
|
-
const dir = path.dirname(p);
|
|
97
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
98
|
-
const tmp = `${p}.tmp`;
|
|
99
|
-
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8');
|
|
100
|
-
fs.renameSync(tmp, p);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
_enforceClockMonotonic(nowTs = Date.now()) {
|
|
104
|
-
if (String(process.env.MUMPIX_DISABLE_CLOCK_ROLLBACK_CHECK || '0') === '1') return;
|
|
105
|
-
try {
|
|
106
|
-
const skew = this._clockSkewMs();
|
|
107
|
-
const state = this._loadWatermarkState();
|
|
108
|
-
const rec = state[this._licenseFingerprint] || {};
|
|
109
|
-
const lastSeen = Number(rec.lastSeen || 0);
|
|
110
|
-
if (lastSeen && nowTs + skew < lastSeen) {
|
|
111
|
-
throw new Error('System clock rollback detected for license context');
|
|
112
|
-
}
|
|
113
|
-
if (!lastSeen || nowTs > lastSeen) {
|
|
114
|
-
state[this._licenseFingerprint] = {
|
|
115
|
-
lastSeen: nowTs,
|
|
116
|
-
updatedAt: nowTs,
|
|
117
|
-
tier: this.tier,
|
|
118
|
-
userId: this.userId,
|
|
119
|
-
};
|
|
120
|
-
this._saveWatermarkState(state);
|
|
121
|
-
}
|
|
122
|
-
} catch (err) {
|
|
123
|
-
const strict = String(process.env.MUMPIX_LICENSE_WATERMARK_STRICT || '0') === '1';
|
|
124
|
-
if (strict) throw err;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
_validateLeaseWindow(payload) {
|
|
129
|
-
const iat = Number(payload.iat || 0);
|
|
130
|
-
const exp = Number(payload.exp || 0);
|
|
131
|
-
if (!iat || !exp) return;
|
|
132
|
-
if (exp <= iat) throw new Error('Invalid license lease window');
|
|
133
|
-
|
|
134
|
-
const now = Date.now();
|
|
135
|
-
const maxFutureIatMs = envInt('MUMPIX_LICENSE_MAX_FUTURE_IAT_MS', 24 * 60 * 60 * 1000);
|
|
136
|
-
if (iat > now + maxFutureIatMs) throw new Error('License iat is too far in the future');
|
|
137
|
-
|
|
138
|
-
const durationDays = Math.ceil((exp - iat) / (24 * 60 * 60 * 1000));
|
|
139
|
-
const maxDays = this._maxDaysForTier(payload.tier);
|
|
140
|
-
if (maxDays > 0 && durationDays > maxDays) {
|
|
141
|
-
throw new Error(`License lease exceeds max policy for tier (${durationDays}d > ${maxDays}d)`);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
setFileContext(fileId) {
|
|
146
|
-
this.fileId = fileId ? String(fileId) : null;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
async init() {
|
|
150
|
-
if (!this.key) return false;
|
|
151
|
-
try {
|
|
152
|
-
if (typeof globalThis.crypto === 'undefined') {
|
|
153
|
-
globalThis.crypto = require('node:crypto').webcrypto;
|
|
154
|
-
}
|
|
155
|
-
const mlDsaPath = 'file://' + path.resolve(__dirname, 'ml-dsa.mjs');
|
|
156
|
-
const { ml_dsa65 } = await import(mlDsaPath);
|
|
157
|
-
this._ml_dsa = ml_dsa65;
|
|
158
|
-
return await this.validate(this.key);
|
|
159
|
-
} catch (e) {
|
|
160
|
-
console.error('Mumpix Licensing Initialization Failed:', e.message);
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async validate(key) {
|
|
166
|
-
try {
|
|
167
|
-
const [payloadB64, signatureB64] = key.split('.');
|
|
168
|
-
if (!payloadB64 || !signatureB64) throw new Error('Invalid key format');
|
|
169
|
-
|
|
170
|
-
const payloadRaw = Buffer.from(payloadB64, 'base64').toString();
|
|
171
|
-
const payload = JSON.parse(payloadRaw);
|
|
172
|
-
|
|
173
|
-
const msg = Buffer.from(payloadB64, 'utf-8');
|
|
174
|
-
const sig = Buffer.from(signatureB64, 'base64');
|
|
175
|
-
const pubB64 = activeMasterPublicKeyB64();
|
|
176
|
-
const pub = Buffer.from(pubB64, 'base64');
|
|
177
|
-
|
|
178
|
-
console.log('[CRYPTO DEBUG] Payload Length:', msg.length);
|
|
179
|
-
console.log('[CRYPTO DEBUG] Sig Length:', sig.length);
|
|
180
|
-
console.log('[CRYPTO DEBUG] Pub Length:', pub.length);
|
|
181
|
-
console.log('[CRYPTO DEBUG] Pub Start (B64):', pubB64.substring(0, 20));
|
|
182
|
-
|
|
183
|
-
const isValid = this._ml_dsa.verify(sig, msg, pub);
|
|
184
|
-
console.log('[CRYPTO DEBUG] isValid:', isValid);
|
|
185
|
-
if (!isValid) throw new Error('Quantum signature verification failed');
|
|
186
|
-
|
|
187
|
-
this._validateLeaseWindow(payload);
|
|
188
|
-
|
|
189
|
-
if (payload.exp && Date.now() > payload.exp) {
|
|
190
|
-
throw new Error('License key has expired');
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
if (payload.fid && this.fileId && String(payload.fid) !== String(this.fileId)) {
|
|
194
|
-
throw new Error('License key is bound to a different file');
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
this.userId = payload.id;
|
|
198
|
-
this.tier = this._normalizeTier(payload.tier || 'free');
|
|
199
|
-
this.issuedAt = payload.iat || null;
|
|
200
|
-
this.expiry = payload.exp;
|
|
201
|
-
this.verified = true;
|
|
202
|
-
this.validationError = '';
|
|
203
|
-
this._enforceClockMonotonic(Date.now());
|
|
204
|
-
return true;
|
|
205
|
-
} catch (e) {
|
|
206
|
-
this.verified = false;
|
|
207
|
-
this.tier = 'free';
|
|
208
|
-
this.validationError = e && e.message ? String(e.message) : 'license_validation_failed';
|
|
209
|
-
return false;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
checkLimit(type, currentCount) {
|
|
214
|
-
if (type === 'records') return true;
|
|
215
|
-
|
|
216
|
-
if (type === 'mode') {
|
|
217
|
-
const requested = String(currentCount || '').toLowerCase();
|
|
218
|
-
const caps = this._capsForTier(this.tier);
|
|
219
|
-
if (!caps.modes.includes(requested)) {
|
|
220
|
-
if (this.key && !this.verified && this.validationError) {
|
|
221
|
-
throw new Error(`Mumpix license is invalid for mode ${requested}: ${this.validationError}`);
|
|
222
|
-
}
|
|
223
|
-
if (requested === 'strict') {
|
|
224
|
-
throw new Error('MumpixDB strict mode requires Developer tier or higher. Upgrade at mumpixdb.com.');
|
|
225
|
-
}
|
|
226
|
-
if (requested === 'verified') {
|
|
227
|
-
throw new Error('MumpixDB verified mode requires Compliance tier. Upgrade at mumpixdb.com.');
|
|
228
|
-
}
|
|
229
|
-
throw new Error(`MumpixDB mode ${requested} is not available on your current tier.`);
|
|
230
|
-
}
|
|
231
|
-
return true;
|
|
232
|
-
}
|
|
233
|
-
return true;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
assertActive(requestedMode = 'eventual') {
|
|
237
|
-
const mode = String(requestedMode || 'eventual').toLowerCase();
|
|
238
|
-
this.checkLimit('mode', mode);
|
|
239
|
-
const now = Date.now();
|
|
240
|
-
this._enforceClockMonotonic(now);
|
|
241
|
-
if (this.expiry && now > Number(this.expiry) && mode !== 'eventual') {
|
|
242
|
-
throw new Error('Mumpix license expired. Renew license to continue using this mode.');
|
|
243
|
-
}
|
|
244
|
-
return true;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
async syncUsage(stats) {
|
|
248
|
-
if (process.env.MUMPIX_DISABLE_TELEMETRY === 'true') return;
|
|
249
|
-
const body = JSON.stringify({
|
|
250
|
-
userId: this.userId, tier: this.tier, machine: os.hostname(),
|
|
251
|
-
platform: os.platform(), stats: stats, ts: Date.now()
|
|
252
|
-
});
|
|
253
|
-
const options = {
|
|
254
|
-
hostname: 'api.vdsx.cloud', port: 443, path: '/api/mumpix/usage',
|
|
255
|
-
method: 'POST', headers: {
|
|
256
|
-
'Content-Type': 'application/json', 'Content-Length': body.length,
|
|
257
|
-
'X-Mumpix-Key': this.key || 'free'
|
|
258
|
-
}, timeout: 2000
|
|
259
|
-
};
|
|
260
|
-
const req = https.request(options);
|
|
261
|
-
req.on('error', () => { });
|
|
262
|
-
req.write(body);
|
|
263
|
-
req.end();
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
module.exports = { LicenseManager };
|
|
1
|
+
"use strict";const e=require("crypto"),t=require("fs"),r=require("os"),i=require("https"),n=require("path");function s(e,t){const r=process.env[e];if(null==r||""===r)return t;const i=Number(r);return Number.isFinite(i)?i:t}function a(){const e=String(process.env.MUMPIX_CONFIG_DIR||"").trim();return e||("win32"===process.platform?n.join(process.env.APPDATA||n.join(r.homedir(),"AppData","Roaming"),"mumpix"):n.join(r.homedir(),".config","mumpix"))}function o(e){try{return JSON.parse(e)}catch{return null}}function c(e){return Buffer.from(e).toString("base64")}function u(t){return e.createHash("sha256").update(t).digest("hex")}function l(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>l(e)).join(",")}]`;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${l(e[t])}`).join(",")}}`}module.exports={LicenseManager:class{constructor(t=null){this.key=t,this.tier="free",this.expiry=null,this.verified=!1,this.userId="guest",this._ml_dsa=null,this.fileId=null,this.issuedAt=null,this.validationError="",this._licenseFingerprint=t?e.createHash("sha256").update(String(t),"utf8").digest("hex"):"free"}_capsForTier(e){const t=this._normalizeTier(e);return"monthly"===t||"developer"===t||"standard"===t||"teams"===t||"team"===t?{modes:["eventual","strict"]}:"compliance"===t||"enterprise"===t||"government"===t||"verified"===t||"pro"===t?{modes:["eventual","strict","verified"]}:{modes:["eventual"]}}_normalizeTier(e){const t=String(e||"free").toLowerCase().trim();return"gov"===t||"public-sector"===t?"government":"team"===t?"teams":"month"===t||"monthly"===t||"starter"===t?"monthly":t||"free"}_maxDaysForTier(e){const t=this._normalizeTier(e);return"monthly"===t?s("MUMPIX_LICENSE_MAX_DAYS_MONTHLY",45):"standard"===t?s("MUMPIX_LICENSE_MAX_DAYS_STANDARD",45):"developer"===t?s("MUMPIX_LICENSE_MAX_DAYS_DEVELOPER",365):"teams"===t?s("MUMPIX_LICENSE_MAX_DAYS_TEAMS",365):"enterprise"===t?s("MUMPIX_LICENSE_MAX_DAYS_ENTERPRISE",36500):"government"===t?s("MUMPIX_LICENSE_MAX_DAYS_GOVERNMENT",36500):"compliance"===t||"verified"===t||"pro"===t?s("MUMPIX_LICENSE_MAX_DAYS_COMPLIANCE",36500):s("MUMPIX_LICENSE_MAX_DAYS_FREE",30)}_watermarkPath(){const e=String(process.env.MUMPIX_LICENSE_WATERMARK_PATH||"").trim();return e||n.join(process.cwd(),".mumpix-license-watermark.json")}_clockSkewMs(){return s("MUMPIX_LICENSE_CLOCK_SKEW_MS",216e5)}_loadWatermarkState(){const e=this._watermarkPath();try{const r=t.readFileSync(e,"utf8"),i=JSON.parse(r);return i&&"object"==typeof i?i:{}}catch{return{}}}_saveWatermarkState(e){const r=this._watermarkPath(),i=n.dirname(r);t.mkdirSync(i,{recursive:!0});const s=`${r}.tmp`;t.writeFileSync(s,JSON.stringify(e,null,2),"utf8"),t.renameSync(s,r)}_enforceClockMonotonic(e=Date.now()){if("1"!==String(process.env.MUMPIX_DISABLE_CLOCK_ROLLBACK_CHECK||"0"))try{const t=this._clockSkewMs(),r=this._loadWatermarkState(),i=r[this._licenseFingerprint]||{},n=Number(i.lastSeen||0);if(n&&e+t<n)throw new Error("System clock rollback detected for license context");(!n||e>n)&&(r[this._licenseFingerprint]={lastSeen:e,updatedAt:e,tier:this.tier,userId:this.userId},this._saveWatermarkState(r))}catch(e){if("1"===String(process.env.MUMPIX_LICENSE_WATERMARK_STRICT||"0"))throw e}}_validateLeaseWindow(e){const t=Number(e.iat||0),r=Number(e.exp||0);if(!t||!r)return;if(r<=t)throw new Error("Invalid license lease window");if(t>Date.now()+s("MUMPIX_LICENSE_MAX_FUTURE_IAT_MS",864e5))throw new Error("License iat is too far in the future");const i=Math.ceil((r-t)/864e5),n=this._maxDaysForTier(e.tier);if(n>0&&i>n)throw new Error(`License lease exceeds max policy for tier (${i}d > ${n}d)`)}setFileContext(e){this.fileId=e?String(e):null}async init(){if(!this.key)return!1;try{void 0===globalThis.crypto&&(globalThis.crypto=require("node:crypto").webcrypto);const e="file://"+n.resolve(__dirname,"ml-dsa.mjs"),{ml_dsa44:t}=await import(e);return this._ml_dsa=t,await this.validate(this.key)}catch(e){return console.error("Mumpix Licensing Initialization Failed:",e.message),!1}}async validate(e){try{const[t,r]=e.split(".");if(!t||!r)throw new Error("Invalid key format");const i=Buffer.from(t,"base64").toString(),n=JSON.parse(i),s=Buffer.from(t,"utf-8"),a=Buffer.from(r,"base64"),o=Buffer.from(String(process.env.MUMPIX_LICENSE_PUBLIC_KEY_B64||"szA4EoME83k0zoSQnzMWSC5BOEnr1VazfZlyP4JKqufZHIjlc0TalnK4gi4Jsn0PMHAJlzEOp/0PvUiW8L0RN3rj0pKEkuwDY5c1Q5C2u1Dh7VfcyiCzj+JusviaANuJQxoEdi6yeBUXJO7tZpwpTrekF5hrc5V9ccY0U3gAofg+4prZz0bA7aaLxK+/WIYXtO+PR7VOAavMzR536FAdJtfcgz08L1hu7RUiE38hQnAH2yRuBkmcGesw4k0XSx3HZXjVwaVxZsOZpL3DihS2EwbluDIzrb3Tz5nf7a2ak/FRFcTS+LLjM4ywxuq6toKT/laAOt/0AEVp67nFGVm8OU4blpmgO3gA0APpglrVMGFcxrBQyYLqMsgwxmb6dQMydILriHQ9vN+jR8jD3qs5f14FwsZkkMtBgBMNRFybQvrXOxvPF36rknnkeDuE0W+9sSpzOdzM8/UZKInzh+v0yOYPIW1y9oiJb2RtoIz0kJkg0IwR8JOIZ7Svfa62ifT/CFhIsBr6zIVdK7mlxmDqiD3MnlLvfqhyPfdgIbCRLmClXI6Jjpt4d7shzBHvOxCpEGwYw4hVCGTnVhPne8UWmgqU3BkSVBQsHU/7s6jNH/tvZjfkOgWoz81RrnrE8xMGRh5yn/F/bEa0igbyJ/4XlmAPRMkQ+CCIo/NbBlYtKvnMHTwatj3B4Z06hTFl0rnuGbQ9u9JXp/1x7bVztMdSM/T65VW8H/zcvZ7aZTbEMzcTUqMdo9IwOWVfyb6lwg5FSCANKzmyT//CJQtpacS9TjPZ0m4AOFyAwhj57fxY7xMPSYQIyTrpMRkoNACJ9QoSSAnyJ0u1aBTMbiFr8IgjgZm0XL2giz8yD5bi/kS+85qPGut+Hvx66VztumAQUoLpJYJSgVXO4ZYMNY0DraTE48l3Y2RG/KmerSGbjAjZjXPJlKxF94M8Y4Su18iy0BVpS7Ax+8nEzDPVfTqPUoSJctv/YLY6bdMqhi9/rTIrE/3Htm5YwHfZP+BV59JLFflT7iud4nBuRZ5rF7ONGMDELg/sglBOHqkv7bDaSoxgcD2SA0L3sptnW57ohUHwmFWuSE8zYkoUsT0sCwvClbmpcgPUxisSY3duAEC3Q+l+NibYhXsavUuHZ9h/O2oMUUvIxtmcF1t17c1f6QwhYpZlJYuYZ/wWTGWqD5MADslUUHCvla5hoZRhWOsDdQspP8O1Sa2Cpzh8zWuKAr2YaSNsUQi/orwzfWFZ56ss9JAH9d+W1Sqc0qOxeQgMoSF3UmHalDQ+xrRl/b1fcN5ZBNmDaM1o0JHGNl7gB7q0Va7NXH2KD1k21f7POPIAdTXlqquFS+MOdy+atPnhncht3bVzSRcerelIk/YGxKCJbsXqFB38s2tR7u4D56B6LiIl/1x4UmP9MmgvJDPMDwrpD9ExgCIyoordPiixYuOeq5LVG6VanIrrVgRlrGmW2lbVX5PMZfZsfhCPW9/JrvrqBPVtnqAjcappUGG4yJyHYFIXeE6Z1nd5DKdBHXEl6zACV6SwxJJ6qgapyOrXCnTmXqkmtI0ebJWGRJ+NHtgl29FF4LXV7HmNgrYrSFdgc6tv/ZBycEFPmsc/HK2Omo+dQKmVI/6w95ctKOsTQmim+pqz5QcZYE8LnCm+U/8iosivWaJ2s6jB+YXQ6Y4+IF9vSPonyqOViw97Moe9uq7qkSM+sfm2pL/oyGTsluOUftREbtIWFK4f4L9EEIWp9em/dAP6mQ==").trim(),"base64");if(!this._ml_dsa.verify(a,s,o))throw new Error("Quantum signature verification failed");if(this._validateLeaseWindow(n),n.exp&&Date.now()>n.exp)throw new Error("License key has expired");if(n.fid&&this.fileId&&String(n.fid)!==String(this.fileId))throw new Error("License key is bound to a different file");const c=n.dpk||n.devicePublicKeyFingerprint||n.device_public_key_fingerprint||n.deviceKeyFingerprint||null;if(c){const e=await this._ensureDeviceIdentity();if(String(c)!==String(e.publicKeyFingerprint))throw new Error("License key is bound to a different device identity")}return this.userId=n.id,this.tier=this._normalizeTier(n.tier||"free"),this.issuedAt=n.iat||null,this.expiry=n.exp,this.verified=!0,this.validationError="",this._enforceClockMonotonic(Date.now()),!0}catch(e){return this.verified=!1,this.tier="free",this.validationError=e&&e.message?String(e.message):"license_validation_failed",!1}}checkLimit(e,t){if("records"===e)return!0;if("mode"===e){const e=String(t||"").toLowerCase();if(!this._capsForTier(this.tier).modes.includes(e)){if(this.key&&!this.verified&&this.validationError)throw new Error(`Mumpix license is invalid for mode "${e}": ${this.validationError}`);if("strict"===e)throw new Error('MumpixDB "strict" mode requires Developer tier or higher. Upgrade at mumpixdb.com.');if("verified"===e)throw new Error('MumpixDB "verified" mode requires Compliance tier. Upgrade at mumpixdb.com.');throw new Error(`MumpixDB mode "${e}" is not available on your current tier.`)}return!0}return!0}assertActive(e="eventual"){const t=String(e||"eventual").toLowerCase();this.checkLimit("mode",t);const r=Date.now();if(this._enforceClockMonotonic(r),this.expiry&&r>Number(this.expiry)&&"eventual"!==t)throw new Error("Mumpix license expired. Renew license to continue using this mode.");return!0}hasVerifiedLicense(){return Boolean(this.key&&this.verified&&"free"!==this._licenseFingerprint)}_usageQueuePath(){return n.join(a(),"usage-queue.ndjson")}_usageChainPath(){return n.join(a(),"usage-chain.json")}_deviceIdentityPath(){return n.join(a(),"device-identity.json")}async _ensureMlDsa(){if(this._ml_dsa)return this._ml_dsa;void 0===globalThis.crypto&&(globalThis.crypto=require("node:crypto").webcrypto);const e="file://"+n.resolve(__dirname,"ml-dsa.mjs"),{ml_dsa44:t}=await import(e);return this._ml_dsa=t,this._ml_dsa}_publicKeyFingerprint(e){return`ml-dsa-44:${u(Buffer.from(String(e||""),"base64"))}`}async _ensureDeviceIdentity(){const e=this._deviceIdentityPath();try{const r=o(t.readFileSync(e,"utf8"));if(r&&"ml-dsa-44"===r.algorithm&&r.publicKeyB64&&r.secretKeyB64){const e=r.publicKeyFingerprint||this._publicKeyFingerprint(r.publicKeyB64);return{...r,publicKeyFingerprint:e}}}catch(e){}const r=(await this._ensureMlDsa()).keygen(),i=c(r.publicKey),s={version:1,algorithm:"ml-dsa-44",createdAt:Date.now(),publicKeyB64:i,secretKeyB64:c(r.secretKey),publicKeyFingerprint:this._publicKeyFingerprint(i)};t.mkdirSync(n.dirname(e),{recursive:!0});const a=`${e}.tmp`;t.writeFileSync(a,JSON.stringify(s,null,2),{encoding:"utf8",mode:384}),t.renameSync(a,e);try{t.chmodSync(e,384)}catch(e){}return s}_loadUsageChain(){try{const e=o(t.readFileSync(this._usageChainPath(),"utf8"));return e&&"object"==typeof e?e:{}}catch{return{}}}_saveUsageChain(e){const r=this._usageChainPath();t.mkdirSync(n.dirname(r),{recursive:!0});const i=`${r}.tmp`;t.writeFileSync(i,JSON.stringify(e,null,2),"utf8"),t.renameSync(i,r)}_readUsageQueue(){const e=this._usageQueuePath();try{return t.readFileSync(e,"utf8").split("\n").filter(e=>e.trim()).map(e=>o(e)).filter(e=>e&&"object"==typeof e)}catch{return[]}}_writeUsageQueue(e){const r=this._usageQueuePath();if(!e.length){try{t.unlinkSync(r)}catch(e){}return}t.mkdirSync(n.dirname(r),{recursive:!0});const i=`${r}.tmp`;t.writeFileSync(i,e.map(e=>JSON.stringify(e)).join("\n")+"\n","utf8"),t.renameSync(i,r)}async _buildUsageEvent(t,i=null){const n=Date.now(),s=await this._ensureDeviceIdentity(),a={eventId:e.randomUUID?e.randomUUID():e.randomBytes(16).toString("hex"),schema:1,algorithm:"ml-dsa-44",userId:this.userId,tier:this.tier,licenseFingerprint:this._licenseFingerprint,devicePublicKeyFingerprint:s.publicKeyFingerprint,devicePublicKeyB64:s.publicKeyB64,previousHash:i||null,machine:r.hostname(),platform:r.platform(),stats:t,ts:n,queuedAt:n},o=l(a),h=(await this._ensureMlDsa()).sign(Buffer.from(o,"utf8"),(d=s.secretKeyB64,new Uint8Array(Buffer.from(String(d||""),"base64"))));var d;const m=u(o);return{...a,payloadHash:m,eventHash:m,signature:c(h),signaturePayload:o}}_postUsageEvent(e){const t=JSON.stringify(e),r={hostname:"api.vdsx.cloud",port:443,path:"/api/mumpix/usage",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(t),"X-Mumpix-Key":this.key||"free","X-Mumpix-License-Fingerprint":this._licenseFingerprint},timeout:2e3};return new Promise((e,n)=>{const s=i.request(r,t=>{t.resume(),t.on("end",()=>{t.statusCode>=200&&t.statusCode<300?e(!0):n(new Error(`usage sync failed: HTTP ${t.statusCode}`))})});s.on("error",n),s.on("timeout",()=>s.destroy(new Error("usage sync timeout"))),s.write(t),s.end()})}async syncUsage(e){const t=function(e){if(!e||"object"!=typeof e)return e;const t={...e};return delete t.path,t}(e),r=this._readUsageQueue(),i=this._loadUsageChain(),n=r.length?r[r.length-1].eventHash||r[r.length-1].payloadHash||null:i.lastHash||null;r.push(await this._buildUsageEvent(t,n));const s=[];let a=0;for(let e=0;e<r.length;e++){const t=r[e];try{await this._postUsageEvent(t),a+=1,i.lastHash=t.eventHash||t.payloadHash||i.lastHash||null,i.lastSyncedAt=Date.now(),i.syncedEvents=Number(i.syncedEvents||0)+1}catch(i){s.push({...t,attempts:Number(t.attempts||0)+1,lastAttemptAt:Date.now()});for(const t of r.slice(e+1))s.push(t);break}}return this._writeUsageQueue(s),a>0&&this._saveUsageChain(i),{synced:a,queued:s.length}}async deviceIdentityInfo(){const e=await this._ensureDeviceIdentity();return{algorithm:e.algorithm,publicKeyFingerprint:e.publicKeyFingerprint,publicKeyB64:e.publicKeyB64,path:this._deviceIdentityPath()}}}};
|
package/src/core/ml-dsa.mjs
CHANGED
|
@@ -1,25 +1 @@
|
|
|
1
|
-
// Patch for browser and server environment
|
|
2
|
-
if (typeof window !== 'undefined') {
|
|
3
|
-
if (typeof window.require === 'undefined') {
|
|
4
|
-
window.require = function (name) {
|
|
5
|
-
if (name === 'semver') return window.semver;
|
|
6
|
-
return {};
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
const require = (typeof window !== 'undefined') ? window.require : function (n) { return {}; };
|
|
11
|
-
/* esm.sh - @noble/post-quantum@0.5.2/ml-dsa */
|
|
12
|
-
function Mt(t) { return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array" } function Ut(t, e = "") { if (!Number.isSafeInteger(t) || t < 0) { let n = e && `"${e}" `; throw new Error(`${n}expected integer >= 0, got ${t} `) } } function A(t, e, n = "") { let o = Mt(t), r = t?.length, i = e !== void 0; if (!o || i && r !== e) { let c = n && `"${n}" `, a = i ? ` of length ${e} ` : "", g = o ? `length = ${r} ` : `type = ${typeof t} `; throw new Error(c + "expected Uint8Array" + a + ", got " + g) } return t } function Ht(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called") } function ce(t, e) { A(t, void 0, "digestInto() output"); let n = e.outputLen; if (t.length < n) throw new Error('"digestInto() output" expected to be of length >=' + n) } function ie(t) { return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4)) } function St(...t) { for (let e = 0; e < t.length; e++)t[e].fill(0) } var je = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; function Ne(t) { return t << 24 & 4278190080 | t << 8 & 16711680 | t >>> 8 & 65280 | t >>> 24 & 255 } function Fe(t) { for (let e = 0; e < t.length; e++)t[e] = Ne(t[e]); return t } var Ct = je ? t => t : Fe; function Rt(...t) { let e = 0; for (let o = 0; o < t.length; o++) { let r = t[o]; A(r), e += r.length } let n = new Uint8Array(e); for (let o = 0, r = 0; o < t.length; o++) { let i = t[o]; n.set(i, r), r += i.length } return n } function fe(t, e = {}) { let n = (r, i) => t(i).update(r).digest(), o = t(void 0); return n.outputLen = o.outputLen, n.blockLen = o.blockLen, n.create = r => t(r), Object.assign(n, e), Object.freeze(n) } function ue(t = 32) { let e = typeof globalThis == "object" ? globalThis.crypto : null; if (typeof e?.getRandomValues != "function") throw new Error("crypto.getRandomValues must be defined"); return e.getRandomValues(new Uint8Array(t)) } var vt = t => ({ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, t]) }); function le(t, e = "") { if (typeof t != "boolean") { let n = e && `"${e}" `; throw new Error(n + "expected boolean, got type=" + typeof t) } return t } var Et = BigInt(4294967295), ae = BigInt(32); function $e(t, e = !1) { return e ? { h: Number(t & Et), l: Number(t >> ae & Et) } : { h: Number(t >> ae & Et) | 0, l: Number(t & Et) | 0 } } function de(t, e = !1) { let n = t.length, o = new Uint32Array(n), r = new Uint32Array(n); for (let i = 0; i < n; i++) { let { h: c, l: a } = $e(t[i], e);[o[i], r[i]] = [c, a] } return [o, r] } var he = (t, e, n) => t << n | e >>> 32 - n, pe = (t, e, n) => e << n | t >>> 32 - n, ge = (t, e, n) => e << n - 32 | t >>> 64 - n, ye = (t, e, n) => t << n - 32 | e >>> 64 - n; var Ge = BigInt(0), dt = BigInt(1), Ke = BigInt(2), De = BigInt(7), Ye = BigInt(256), Xe = BigInt(113), be = [], me = [], Ae = []; for (let t = 0, e = dt, n = 1, o = 0; t < 24; t++) { [n, o] = [o, (2 * n + 3 * o) % 5], be.push(2 * (5 * o + n)), me.push((t + 1) * (t + 2) / 2 % 64); let r = Ge; for (let i = 0; i < 7; i++)e = (e << dt ^ (e >> De) * Xe) % Ye, e & Ke && (r ^= dt << (dt << BigInt(i)) - dt); Ae.push(r) } var Ee = de(Ae, !0), Ve = Ee[0], Ze = Ee[1], xe = (t, e, n) => n > 32 ? ge(t, e, n) : he(t, e, n), we = (t, e, n) => n > 32 ? ye(t, e, n) : pe(t, e, n); function ze(t, e = 24) { let n = new Uint32Array(10); for (let o = 24 - e; o < 24; o++) { for (let c = 0; c < 10; c++)n[c] = t[c] ^ t[c + 10] ^ t[c + 20] ^ t[c + 30] ^ t[c + 40]; for (let c = 0; c < 10; c += 2) { let a = (c + 8) % 10, g = (c + 2) % 10, E = n[g], y = n[g + 1], C = xe(E, y, 1) ^ n[a], z = we(E, y, 1) ^ n[a + 1]; for (let R = 0; R < 50; R += 10)t[c + R] ^= C, t[c + R + 1] ^= z } let r = t[2], i = t[3]; for (let c = 0; c < 24; c++) { let a = me[c], g = xe(r, i, a), E = we(r, i, a), y = be[c]; r = t[y], i = t[y + 1], t[y] = g, t[y + 1] = E } for (let c = 0; c < 50; c += 10) { for (let a = 0; a < 10; a++)n[a] = t[c + a]; for (let a = 0; a < 10; a++)t[c + a] ^= ~n[(a + 2) % 10] & n[(a + 4) % 10] } t[0] ^= Ve[o], t[1] ^= Ze[o] } St(n) } var Pt = class t { state; pos = 0; posOut = 0; finished = !1; state32; destroyed = !1; blockLen; suffix; outputLen; enableXOF = !1; rounds; constructor(e, n, o, r = !1, i = 24) { if (this.blockLen = e, this.suffix = n, this.outputLen = o, this.enableXOF = r, this.rounds = i, Ut(o, "outputLen"), !(0 < e && e < 200)) throw new Error("only keccak-f1600 function is supported"); this.state = new Uint8Array(200), this.state32 = ie(this.state) } clone() { return this._cloneInto() } keccak() { Ct(this.state32), ze(this.state32, this.rounds), Ct(this.state32), this.posOut = 0, this.pos = 0 } update(e) { Ht(this), A(e); let { blockLen: n, state: o } = this, r = e.length; for (let i = 0; i < r;) { let c = Math.min(n - this.pos, r - i); for (let a = 0; a < c; a++)o[this.pos++] ^= e[i++]; this.pos === n && this.keccak() } return this } finish() { if (this.finished) return; this.finished = !0; let { state: e, suffix: n, pos: o, blockLen: r } = this; e[o] ^= n, (n & 128) !== 0 && o === r - 1 && this.keccak(), e[r - 1] ^= 128, this.keccak() } writeInto(e) { Ht(this, !1), A(e), this.finish(); let n = this.state, { blockLen: o } = this; for (let r = 0, i = e.length; r < i;) { this.posOut >= o && this.keccak(); let c = Math.min(o - this.posOut, i - r); e.set(n.subarray(this.posOut, this.posOut + c), r), this.posOut += c, r += c } return e } xofInto(e) { if (!this.enableXOF) throw new Error("XOF is not possible for this instance"); return this.writeInto(e) } xof(e) { return Ut(e), this.xofInto(new Uint8Array(e)) } digestInto(e) { if (ce(e, this), this.finished) throw new Error("digest() was already called"); return this.writeInto(e), this.destroy(), e } digest() { return this.digestInto(new Uint8Array(this.outputLen)) } destroy() { this.destroyed = !0, St(this.state) } _cloneInto(e) { let { blockLen: n, suffix: o, outputLen: r, rounds: i, enableXOF: c } = this; return e ||= new t(n, o, r, c, i), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = i, e.suffix = o, e.outputLen = r, e.enableXOF = c, e.destroyed = this.destroyed, e } }; var Be = (t, e, n, o = {}) => fe((r = {}) => new Pt(e, t, r.dkLen === void 0 ? n : r.dkLen, !0), o), Te = Be(31, 168, 16, vt(11)), P = Be(31, 136, 32, vt(12)); function jt(t) { if (!Number.isSafeInteger(t) || t < 0 || t > 4294967295) throw new Error("wrong u32 integer:" + t); return t } function ke(t) { return jt(t), (t & t - 1) === 0 && t !== 0 } function Nt(t, e) { jt(t); let n = 0; for (let o = 0; o < e; o++, t >>>= 1)n = n << 1 | t & 1; return n } function _e(t) { return jt(t), 31 - Math.clz32(t) } function Le(t) { let e = t.length; if (e < 2 || !ke(e)) throw new Error("n must be a power of 2 and greater than 1. Got " + e); let n = _e(e); for (let o = 0; o < e; o++) { let r = Nt(o, n); if (o < r) { let i = t[o]; t[o] = t[r], t[r] = i } } return t } var Ft = (t, e) => { let { N: n, roots: o, dit: r, invertButterflies: i = !1, skipStages: c = 0, brp: a = !0 } = e, g = _e(n); if (!ke(n)) throw new Error("FFT: Polynomial size should be power of two"); let E = r !== i; return y => { if (y.length !== n) throw new Error("FFT: wrong Polynomial length"); r && a && Le(y); for (let C = 0, z = 1; C < g - c; C++) { let R = r ? C + 1 + c : g - C, q = 1 << R, J = q >> 1, yt = n >> R; for (let rt = 0; rt < n; rt += q)for (let p = 0, w = z++; p < J; p++) { let I = i ? r ? n - w : w : p * yt, K = rt + p, j = rt + p + J, D = o[I], H = y[j], B = y[K]; if (E) { let S = t.mul(H, D); y[K] = t.add(B, S), y[j] = t.sub(B, S) } else i ? (y[K] = t.add(H, B), y[j] = t.mul(t.sub(H, B), D)) : (y[K] = t.add(B, H), y[j] = t.mul(t.sub(B, H), D)) } } return !r && a && Le(y), y } }; var $t = ue; function Gt(t, e) { if (t.length !== e.length) return !1; let n = 0; for (let o = 0; o < t.length; o++)n |= t[o] ^ e[o]; return n === 0 } function Kt(t) { if (typeof t != "object" || t === null || Mt(t)) throw new Error("expected opts to be an object") } function Bt(t) { Kt(t), t.context !== void 0 && A(t.context, void 0, "opts.context") } function Tt(t) { Bt(t), t.extraEntropy !== !1 && t.extraEntropy !== void 0 && A(t.extraEntropy, void 0, "opts.extraEntropy") } function ht(t, ...e) { let n = r => typeof r == "number" ? r : r.bytesLen, o = e.reduce((r, i) => r + n(i), 0); return { bytesLen: o, encode: r => { let i = new Uint8Array(o); for (let c = 0, a = 0; c < e.length; c++) { let g = e[c], E = n(g), y = typeof g == "number" ? r[c] : g.encode(r[c]); A(y, E, t), i.set(y, a), typeof g != "number" && y.fill(0), a += E } return i }, decode: r => { A(r, o, t); let i = []; for (let c of e) { let a = n(c), g = r.subarray(0, a); i.push(typeof c == "number" ? g : c.decode(g)), r = r.subarray(a) } return i } } } function st(t, e) { let n = e * t.bytesLen; return { bytesLen: n, encode: o => { if (o.length !== e) throw new Error(`vecCoder.encode: wrong length = ${o.length}.Expected: ${e} `); let r = new Uint8Array(n); for (let i = 0, c = 0; i < o.length; i++) { let a = t.encode(o[i]); r.set(a, c), a.fill(0), c += a.length } return r }, decode: o => { A(o, n); let r = []; for (let i = 0; i < o.length; i += t.bytesLen)r.push(t.decode(o.subarray(i, i + t.bytesLen))); return r } } } function Z(...t) { for (let e of t) if (Array.isArray(e)) for (let n of e) n.fill(0); else e.fill(0) } function Dt(t) { return (1 << t) - 1 } var Oe = Uint8Array.of(); function Yt(t, e = Oe) { if (A(t), A(e), e.length > 255) throw new Error("context should be less than 255 bytes"); return Rt(new Uint8Array([0, e.length]), e, t) } var qe = Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2]); function Ie(t, e = 0) { if (!t.oid || !Gt(t.oid.subarray(0, 10), qe)) throw new Error("hash.oid is invalid: expected NIST hash"); let n = t.outputLen * 8 / 2; if (e > n) throw new Error("Pre-hash security strength too low: " + n + ", required: " + e) } function Xt(t, e, n = Oe) { if (A(e), A(n), n.length > 255) throw new Error("context should be less than 255 bytes"); let o = t(e); return Rt(new Uint8Array([1, n.length]), n, t.oid, o) } var Me = t => { let { newPoly: e, N: n, Q: o, F: r, ROOT_OF_UNITY: i, brvBits: c, isKyber: a } = t, g = (p, w = o) => { let I = p % w | 0; return (I >= 0 ? I | 0 : w + I | 0) | 0 }, E = (p, w = o) => { let I = g(p, w) | 0; return (I > w >> 1 ? I - w | 0 : I) | 0 }; function y() { let p = e(n); for (let w = 0; w < n; w++) { let I = Nt(w, c), K = BigInt(i) ** BigInt(I) % BigInt(o); p[w] = Number(K) | 0 } return p } let C = y(), z = { add: (p, w) => g((p | 0) + (w | 0)) | 0, sub: (p, w) => g((p | 0) - (w | 0)) | 0, mul: (p, w) => g((p | 0) * (w | 0)) | 0, inv: p => { throw new Error("not implemented") } }, R = { N: n, roots: C, invertButterflies: !0, skipStages: a ? 1 : 0, brp: !1 }, q = Ft(z, { dit: !1, ...R }), J = Ft(z, { dit: !0, ...R }); return { mod: g, smod: E, nttZetas: C, NTT: { encode: p => q(p), decode: p => { J(p); for (let w = 0; w < p.length; w++)p[w] = g(r * p[w]); return p } }, bitsCoder: (p, w) => { let I = Dt(p), K = p * (n / 8); return { bytesLen: K, encode: j => { let D = new Uint8Array(K); for (let H = 0, B = 0, S = 0, ft = 0; H < j.length; H++)for (B |= (w.encode(j[H]) & I) << S, S += p; S >= 8; S -= 8, B >>= 8)D[ft++] = B & Dt(S); return D }, decode: j => { let D = e(n); for (let H = 0, B = 0, S = 0, ft = 0; H < j.length; H++)for (B |= j[H] << S, S += 8; S >= p; S -= p, B >>= p)D[ft++] = w.decode(B & I); return D } } } } }, Ue = t => (e, n) => { n || (n = t.blockLen); let o = new Uint8Array(e.length + 2); o.set(e); let r = e.length, i = new Uint8Array(n), c = t.create({}), a = 0, g = 0; return { stats: () => ({ calls: a, xofs: g }), get: (E, y) => (o[r + 0] = E, o[r + 1] = y, c.destroy(), c = t.create({}).update(o), a++, () => (g++, c.xofInto(i))), clean: () => { c.destroy(), Z(i, o) } } }, Lt = Ue(Te), kt = Ue(P); function He(t) { Kt(t), t.externalMu !== void 0 && le(t.externalMu, "opts.externalMu") } var m = 256, ot = 8380417, We = 1753, Qe = 8347681, it = 13, Vt = Math.floor((ot - 1) / 88) | 0, Zt = Math.floor((ot - 1) / 32) | 0, zt = { 2: { K: 4, L: 4, D: it, GAMMA1: 2 ** 17, GAMMA2: Vt, TAU: 39, ETA: 2, OMEGA: 80 }, 3: { K: 6, L: 5, D: it, GAMMA1: 2 ** 19, GAMMA2: Zt, TAU: 49, ETA: 4, OMEGA: 55 }, 5: { K: 8, L: 7, D: it, GAMMA1: 2 ** 19, GAMMA2: Zt, TAU: 60, ETA: 2, OMEGA: 75 } }, $ = t => new Int32Array(t), { mod: ct, smod: Ot, NTT: O, bitsCoder: Je } = Me({ N: m, Q: ot, F: Qe, ROOT_OF_UNITY: We, newPoly: $, isKyber: !1, brvBits: 8 }), Se = t => t, pt = (t, e = Se, n = Se) => Je(t, { encode: o => e(n(o)), decode: o => n(e(o)) }), et = (t, e) => { for (let n = 0; n < t.length; n++)t[n] = ct(t[n] + e[n]); return t }, Ce = (t, e) => { for (let n = 0; n < t.length; n++)t[n] = ct(t[n] - e[n]); return t }, tn = t => { for (let e = 0; e < m; e++)t[e] <<= it; return t }, gt = (t, e) => { for (let n = 0; n < m; n++)if (Math.abs(Ot(t[n])) >= e) return !0; return !1 }, nt = (t, e) => { let n = $(m); for (let o = 0; o < t.length; o++)n[o] = ct(t[o] * e[o]); return n }; function _t(t) { let e = $(m); for (let n = 0; n < m;) { let o = t(); if (o.length % 3) throw new Error("RejNTTPoly: unaligned block"); for (let r = 0; n < m && r <= o.length - 3; r += 3) { let i = (o[r + 0] | o[r + 1] << 8 | o[r + 2] << 16) & 8388607; i < ot && (e[n++] = i) } } return e } function qt(t) { let { K: e, L: n, GAMMA1: o, GAMMA2: r, TAU: i, ETA: c, OMEGA: a } = t, { CRH_BYTES: g, TR_BYTES: E, C_TILDE_BYTES: y, XOF128: C, XOF256: z, securityLevel: R } = t; if (![2, 4].includes(c)) throw new Error("Wrong ETA"); if (![1 << 17, 1 << 19].includes(o)) throw new Error("Wrong GAMMA1"); if (![Vt, Zt].includes(r)) throw new Error("Wrong GAMMA2"); let q = i * c, J = s => { let l = ct(s), f = Ot(l, 2 * r) | 0; return l - f === ot - 1 ? { r1: 0, r0: f - 1 | 0 } : { r1: Math.floor((l - f) / (2 * r)) | 0, r0: f } }, yt = s => J(s).r1, rt = s => J(s).r0, p = (s, l) => s <= r || s > ot - r || s === ot - r && l === 0 ? 0 : 1, w = (s, l) => { let f = Math.floor((ot - 1) / (2 * r)), { r1: u, r0: h } = J(l); return s === 1 ? h > 0 ? ct(u + 1, f) | 0 : ct(u - 1, f) | 0 : u | 0 }, I = s => { let l = ct(s), f = Ot(l, 2 ** it) | 0; return { r1: Math.floor((l - f) / 2 ** it) | 0, r0: f } }, K = { bytesLen: a + e, encode: s => { if (s === !1) throw new Error("hint.encode: hint is false"); let l = new Uint8Array(a + e); for (let f = 0, u = 0; f < e; f++) { for (let h = 0; h < m; h++)s[f][h] !== 0 && (l[u++] = h); l[a + f] = u } return l }, decode: s => { let l = [], f = 0; for (let u = 0; u < e; u++) { let h = $(m); if (s[a + u] < f || s[a + u] > a) return !1; for (let x = f; x < s[a + u]; x++) { if (x > f && s[x] <= s[x - 1]) return !1; h[s[x]] = 1 } f = s[a + u], l.push(h) } for (let u = f; u < a; u++)if (s[u] !== 0) return !1; return l } }, j = pt(c === 2 ? 3 : 4, s => c - s, s => { if (!(-c <= s && s <= c)) throw new Error(`malformed key s1 / s3 ${s} outside of ETA range[${-c}, ${c}]`); return s }), D = pt(13, s => (1 << it - 1) - s), H = pt(10), B = pt(o === 1 << 17 ? 18 : 20, s => Ot(o - s)), S = pt(r === Vt ? 6 : 4), ft = st(S, e), xt = ht("publicKey", 32, st(H, e)), wt = ht("secretKey", 32, 32, E, st(j, n), st(j, e), st(D, e)), bt = ht("signature", y, st(B, n), K), Wt = c === 2 ? s => s < 15 ? 2 - s % 5 : !1 : s => s < 9 ? 4 - s : !1; function Qt(s) { let l = $(m); for (let f = 0; f < m;) { let u = s(); for (let h = 0; f < m && h < u.length; h += 1) { let x = Wt(u[h] & 15), M = Wt(u[h] >> 4 & 15); x !== !1 && (l[f++] = x), f < m && M !== !1 && (l[f++] = M) } } return l } let Jt = s => { let l = $(m), f = P.create({}).update(s), u = new Uint8Array(P.blockLen); f.xofInto(u); let h = u.slice(0, 8); for (let x = m - i, M = 8, v = 0, T = 0; x < m; x++) { let L = x + 1; for (; L > x;)L = u[M++], !(M < P.blockLen) && (f.xofInto(u), M = 0); l[x] = l[L], l[L] = 1 - ((h[v] >> T++ & 1) << 1), T >= 8 && (v++, T = 0) } return l }, te = s => { let l = $(m), f = $(m); for (let u = 0; u < s.length; u++) { let { r0: h, r1: x } = I(s[u]); l[u] = h, f[u] = x } return { r0: l, r1: f } }, Re = (s, l) => { for (let f = 0; f < m; f++)s[f] = w(l[f], s[f]); return s }, ve = (s, l) => { let f = $(m), u = 0; for (let h = 0; h < m; h++) { let x = p(s[h], l[h]); f[h] = x, u += x } return { v: f, cnt: u } }, ee = 32, ne = ht("seed", 32, 64, 32), Y = { info: { type: "internal-ml-dsa" }, lengths: { secretKey: wt.bytesLen, publicKey: xt.bytesLen, seed: 32, signature: bt.bytesLen, signRand: ee }, keygen: s => { let l = new Uint8Array(34), f = s === void 0; f && (s = $t(32)), A(s, 32, "seed"), l.set(s), f && Z(s), l[32] = e, l[33] = n; let [u, h, x] = ne.decode(P(l, { dkLen: ne.bytesLen })), M = z(h), v = []; for (let d = 0; d < n; d++)v.push(Qt(M.get(d & 255, d >> 8 & 255))); let T = []; for (let d = n; d < n + e; d++)T.push(Qt(M.get(d & 255, d >> 8 & 255))); let L = v.map(d => O.encode(d.slice())), k = [], U = [], W = C(u), _ = $(m); for (let d = 0; d < e; d++) { Z(_); for (let F = 0; F < n; F++) { let V = _t(W.get(F, d)); et(_, nt(V, L[F])) } O.decode(_); let { r0: G, r1: N } = te(et(_, T[d])); k.push(G), U.push(N) } let X = xt.encode([u, U]), Q = P(X, { dkLen: E }), ut = wt.encode([u, x, Q, v, T, k]); return W.clean(), M.clean(), Z(u, h, x, v, T, L, _, k, U, Q, l), { publicKey: X, secretKey: ut } }, getPublicKey: s => { let [l, f, u, h, x, M] = wt.decode(s), v = C(l), T = h.map(U => O.encode(U.slice())), L = [], k = $(m); for (let U = 0; U < e; U++) { k.fill(0); for (let _ = 0; _ < n; _++) { let X = _t(v.get(_, U)); et(k, nt(X, T[_])) } O.decode(k), et(k, x[U]); let { r1: W } = te(k); L.push(W) } return v.clean(), Z(k, T, M, h, x), xt.encode([l, L]) }, sign: (s, l, f = {}) => { Tt(f), He(f); let { extraEntropy: u, externalMu: h = !1 } = f, [x, M, v, T, L, k] = wt.decode(l), U = [], W = C(x); for (let d = 0; d < e; d++) { let G = []; for (let N = 0; N < n; N++)G.push(_t(W.get(N, d))); U.push(G) } W.clean(); for (let d = 0; d < n; d++)O.encode(T[d]); for (let d = 0; d < e; d++)O.encode(L[d]), O.encode(k[d]); let _ = h ? s : P.create({ dkLen: g }).update(v).update(s).digest(), X = u === !1 ? new Uint8Array(32) : u === void 0 ? $t(ee) : u; A(X, 32, "extraEntropy"); let Q = P.create({ dkLen: g }).update(M).update(X).update(_).digest(); A(Q, g); let ut = z(Q, B.bytesLen); t: for (let d = 0; ;) { let G = []; for (let b = 0; b < n; b++, d++)G.push(B.decode(ut.get(d & 255, d >> 8)())); let N = G.map(b => O.encode(b.slice())), F = []; for (let b = 0; b < e; b++) { let at = $(m); for (let tt = 0; tt < n; tt++)et(at, nt(U[b][tt], N[tt])); O.decode(at), F.push(at) } let V = F.map(b => b.map(yt)), lt = P.create({ dkLen: y }).update(_).update(ft.encode(V)).digest(), mt = O.encode(Jt(lt)), At = T.map(b => nt(b, mt)); for (let b = 0; b < n; b++)if (et(O.decode(At[b]), G[b]), gt(At[b], o - q)) continue t; let oe = 0, It = []; for (let b = 0; b < e; b++) { let at = O.decode(nt(L[b], mt)), tt = Ce(F[b], at).map(rt); if (gt(tt, r - q)) continue t; let re = O.decode(nt(k[b], mt)); if (gt(re, r)) continue t; et(tt, re); let se = ve(tt, V[b]); It.push(se.v), oe += se.cnt } if (oe > a) continue; ut.clean(); let Pe = bt.encode([lt, At, It]); return Z(lt, At, It, mt, V, F, N, G, Q, _, T, L, k, ...U), Pe } throw new Error("Unreachable code path reached, report this error") }, verify: (s, l, f, u = {}) => { He(u); let { externalMu: h = !1 } = u, [x, M] = xt.decode(f), v = P(f, { dkLen: E }); if (s.length !== bt.bytesLen) return !1; let [T, L, k] = bt.decode(s); if (k === !1) return !1; for (let d = 0; d < n; d++)if (gt(L[d], o - q)) return !1; let U = h ? l : P.create({ dkLen: g }).update(v).update(l).digest(), W = O.encode(Jt(T)), _ = L.map(d => d.slice()); for (let d = 0; d < n; d++)O.encode(_[d]); let X = [], Q = C(x); for (let d = 0; d < e; d++) { let G = nt(O.encode(tn(M[d])), W), N = $(m); for (let V = 0; V < n; V++) { let lt = _t(Q.get(V, d)); et(N, nt(lt, _[V])) } let F = O.decode(Ce(N, G)); X.push(Re(F, k[d])) } Q.clean(); let ut = P.create({ dkLen: y }).update(U).update(ft.encode(X)).digest(); for (let d of k) if (!(d.reduce((N, F) => N + F, 0) <= a)) return !1; for (let d of L) if (gt(d, o - q)) return !1; return Gt(T, ut) } }; return { info: { type: "ml-dsa" }, internal: Y, securityLevel: R, keygen: Y.keygen, lengths: Y.lengths, getPublicKey: Y.getPublicKey, sign: (s, l, f = {}) => { Tt(f); let u = Yt(s, f.context), h = Y.sign(u, l, f); return Z(u), h }, verify: (s, l, f, u = {}) => (Bt(u), Y.verify(s, Yt(l, u.context), f)), prehash: s => (Ie(s, R), { info: { type: "hashml-dsa" }, securityLevel: R, lengths: Y.lengths, keygen: Y.keygen, getPublicKey: Y.getPublicKey, sign: (l, f, u = {}) => { Tt(u); let h = Xt(s, l, u.context), x = Y.sign(h, f, u); return Z(h), x }, verify: (l, f, u, h = {}) => (Bt(h), Y.verify(l, Xt(s, f, h.context), u)) }) } } var mn = qt({ ...zt[2], CRH_BYTES: 64, TR_BYTES: 64, C_TILDE_BYTES: 32, XOF128: Lt, XOF256: kt, securityLevel: 128 }), An = qt({ ...zt[3], CRH_BYTES: 64, TR_BYTES: 64, C_TILDE_BYTES: 48, XOF128: Lt, XOF256: kt, securityLevel: 192 }), En = qt({ ...zt[5], CRH_BYTES: 64, TR_BYTES: 64, C_TILDE_BYTES: 64, XOF128: Lt, XOF256: kt, securityLevel: 256 }); export { zt as PARAMS, mn as ml_dsa44, An as ml_dsa65, En as ml_dsa87 };
|
|
13
|
-
/*! Bundled license information:
|
|
14
|
-
|
|
15
|
-
@noble/hashes/utils.js:
|
|
16
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
17
|
-
|
|
18
|
-
@noble/curves/utils.js:
|
|
19
|
-
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
20
|
-
|
|
21
|
-
@noble/post-quantum/utils.js:
|
|
22
|
-
@noble/post-quantum/_crystals.js:
|
|
23
|
-
@noble/post-quantum/ml-dsa.js:
|
|
24
|
-
(*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
|
|
25
|
-
*/
|
|
1
|
+
"undefined"!=typeof window&&void 0===window.require&&(window.require=function(e){return"semver"===e?window.semver:{}});"undefined"!=typeof window&&window.require;function e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function t(e,t=""){if(!Number.isSafeInteger(e)||e<0){throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e} `)}}function r(t,r,n=""){let o=e(t),l=t?.length,i=void 0!==r;if(!o||i&&l!==r){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${r} `:"")+", got "+(o?`length = ${l} `:`type = ${typeof t} `))}return t}function n(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function o(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function l(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var i=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=l(e[t]);return e};function s(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];r(o),t+=o.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let o=e[t];n.set(o,r),r+=o.length}return n}var u=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var f=BigInt(4294967295),d=BigInt(32);function a(e,t=!1){return t?{h:Number(e&f),l:Number(e>>d&f)}:{h:0|Number(e>>d&f),l:0|Number(e&f)}}var c=BigInt(0),h=BigInt(1),y=BigInt(2),g=BigInt(7),p=BigInt(256),w=BigInt(113),b=[],A=[],E=[];for(let e=0,t=h,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],b.push(2*(5*n+r)),A.push((e+1)*(e+2)/2%64);let o=c;for(let e=0;e<7;e++)t=(t<<h^(t>>g)*w)%p,t&y&&(o^=h<<(h<<BigInt(e))-h);E.push(o)}var L=function(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let l=0;l<r;l++){let{h:r,l:i}=a(e[l],t);[n[l],o[l]]=[r,i]}return[n,o]}(E,!0),m=L[0],v=L[1],T=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),k=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);var x=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,r,n,o=!1,l=24){if(this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=l,t(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=function(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}(this.state)}clone(){return this._cloneInto()}keccak(){i(this.state32),function(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,o=(t+2)%10,l=r[o],i=r[o+1],s=T(l,i,1)^r[n],u=k(l,i,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=s,e[t+r+1]^=u}let t=e[2],o=e[3];for(let r=0;r<24;r++){let n=A[r],l=T(t,o,n),i=k(t,o,n),s=b[r];t=e[s],o=e[s+1],e[s]=l,e[s+1]=i}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=m[n],e[1]^=v[n]}o(r)}(this.state32,this.rounds),i(this.state32),this.posOut=0,this.pos=0}update(e){n(this),r(e);let{blockLen:t,state:o}=this,l=e.length;for(let r=0;r<l;){let n=Math.min(t-this.pos,l-r);for(let t=0;t<n;t++)o[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,!!(128&t)&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){n(this,!1),r(e),this.finish();let t=this.state,{blockLen:o}=this;for(let r=0,n=e.length;r<n;){this.posOut>=o&&this.keccak();let l=Math.min(o-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+l),r),this.posOut+=l,r+=l}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return t(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){r(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,o(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:l,enableXOF:i}=this;return t||=new e(r,n,o,i,l),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=l,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},M=(e,t,r,n={})=>function(e,t={}){let r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}((n={})=>new x(t,e,void 0===n.dkLen?r:n.dkLen,!0),n),I=M(31,168,16,u(11)),O=M(31,136,32,u(12));function U(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error("wrong u32 integer:"+e);return e}function B(e){return U(e),!(e&e-1)&&0!==e}function _(e,t){U(e);let r=0;for(let n=0;n<t;n++,e>>>=1)r=r<<1|1&e;return r}function F(e){return U(e),31-Math.clz32(e)}function S(e){let t=e.length;if(t<2||!B(t))throw new Error("n must be a power of 2 and greater than 1. Got "+t);let r=F(t);for(let n=0;n<t;n++){let t=_(n,r);if(n<t){let r=e[n];e[n]=e[t],e[t]=r}}return e}var K=(e,t)=>{let{N:r,roots:n,dit:o,invertButterflies:l=!1,skipStages:i=0,brp:s=!0}=t,u=F(r);if(!B(r))throw new Error("FFT: Polynomial size should be power of two");let f=o!==l;return t=>{if(t.length!==r)throw new Error("FFT: wrong Polynomial length");o&&s&&S(t);for(let s=0,d=1;s<u-i;s++){let a=o?s+1+i:u-s,c=1<<a,h=c>>1,y=r>>a;for(let i=0;i<r;i+=c)for(let s=0,u=d++;s<h;s++){let d=i+s,a=i+s+h,c=n[l?o?r-u:u:s*y],g=t[a],p=t[d];if(f){let r=e.mul(g,c);t[d]=e.add(p,r),t[a]=e.sub(p,r)}else l?(t[d]=e.add(g,p),t[a]=e.mul(e.sub(g,p),c)):(t[d]=e.add(p,g),t[a]=e.mul(e.sub(p,g),c))}}return!o&&s&&S(t),t}},N=function(e=32){let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))};function R(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}function G(t){if("object"!=typeof t||null===t||e(t))throw new Error("expected opts to be an object")}function X(e){G(e),void 0!==e.context&&r(e.context,void 0,"opts.context")}function Y(e){X(e),!1!==e.extraEntropy&&void 0!==e.extraEntropy&&r(e.extraEntropy,void 0,"opts.extraEntropy")}function $(e,...t){let n=e=>"number"==typeof e?e:e.bytesLen,o=t.reduce((e,t)=>e+n(t),0);return{bytesLen:o,encode:l=>{let i=new Uint8Array(o);for(let o=0,s=0;o<t.length;o++){let u=t[o],f=n(u),d="number"==typeof u?l[o]:u.encode(l[o]);r(d,f,e),i.set(d,s),"number"!=typeof u&&d.fill(0),s+=f}return i},decode:l=>{r(l,o,e);let i=[];for(let e of t){let t=n(e),r=l.subarray(0,t);i.push("number"==typeof e?r:e.decode(r)),l=l.subarray(t)}return i}}}function P(e,t){let n=t*e.bytesLen;return{bytesLen:n,encode:r=>{if(r.length!==t)throw new Error(`vecCoder.encode: wrong length = ${r.length}.Expected: ${t} `);let o=new Uint8Array(n);for(let t=0,n=0;t<r.length;t++){let l=e.encode(r[t]);o.set(l,n),l.fill(0),n+=l.length}return o},decode:t=>{r(t,n);let o=[];for(let r=0;r<t.length;r+=e.bytesLen)o.push(e.decode(t.subarray(r,r+e.bytesLen)));return o}}}function C(...e){for(let t of e)if(Array.isArray(t))for(let e of t)e.fill(0);else t.fill(0)}function D(e){return(1<<e)-1}var j=Uint8Array.of();function H(e,t=j){if(r(e),r(t),t.length>255)throw new Error("context should be less than 255 bytes");return s(new Uint8Array([0,t.length]),t,e)}var q=Uint8Array.from([6,9,96,134,72,1,101,3,4,2]);function V(e,t,n=j){if(r(t),r(n),n.length>255)throw new Error("context should be less than 255 bytes");let o=e(t);return s(new Uint8Array([1,n.length]),n,e.oid,o)}var z=e=>(t,r)=>{r||(r=e.blockLen);let n=new Uint8Array(t.length+2);n.set(t);let o=t.length,l=new Uint8Array(r),i=e.create({}),s=0,u=0;return{stats:()=>({calls:s,xofs:u}),get:(t,r)=>(n[o+0]=t,n[o+1]=r,i.destroy(),i=e.create({}).update(n),s++,()=>(u++,i.xofInto(l))),clean:()=>{i.destroy(),C(l,n)}}},W=z(I),Q=z(O);function Z(e){G(e),void 0!==e.externalMu&&function(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e)}(e.externalMu,"opts.externalMu")}var J=256,ee=8380417,te=13,re=0|Math.floor(95232),ne=0|Math.floor(261888),oe={2:{K:4,L:4,D:te,GAMMA1:2**17,GAMMA2:re,TAU:39,ETA:2,OMEGA:80},3:{K:6,L:5,D:te,GAMMA1:2**19,GAMMA2:ne,TAU:49,ETA:4,OMEGA:55},5:{K:8,L:7,D:te,GAMMA1:2**19,GAMMA2:ne,TAU:60,ETA:2,OMEGA:75}},le=e=>new Int32Array(e),{mod:ie,smod:se,NTT:ue,bitsCoder:fe}=(e=>{let{newPoly:t,N:r,Q:n,F:o,ROOT_OF_UNITY:l,brvBits:i,isKyber:s}=e,u=(e,t=n)=>{let r=e%t|0;return 0|(r>=0?r:t+r)};let f=function(){let e=t(r);for(let t=0;t<r;t++){let r=_(t,i),o=BigInt(l)**BigInt(r)%BigInt(n);e[t]=0|Number(o)}return e}(),d={add:(e,t)=>0|u((0|e)+(0|t)),sub:(e,t)=>0|u((0|e)-(0|t)),mul:(e,t)=>0|u((0|e)*(0|t)),inv:e=>{throw new Error("not implemented")}},a={N:r,roots:f,invertButterflies:!0,skipStages:s?1:0,brp:!1},c=K(d,{dit:!1,...a}),h=K(d,{dit:!0,...a});return{mod:u,smod:(e,t=n)=>{let r=0|u(e,t);return 0|(r>t>>1?r-t:r)},nttZetas:f,NTT:{encode:e=>c(e),decode:e=>{h(e);for(let t=0;t<e.length;t++)e[t]=u(o*e[t]);return e}},bitsCoder:(e,n)=>{let o=D(e),l=e*(r/8);return{bytesLen:l,encode:t=>{let r=new Uint8Array(l);for(let l=0,i=0,s=0,u=0;l<t.length;l++)for(i|=(n.encode(t[l])&o)<<s,s+=e;s>=8;s-=8,i>>=8)r[u++]=i&D(s);return r},decode:l=>{let i=t(r);for(let t=0,r=0,s=0,u=0;t<l.length;t++)for(r|=l[t]<<s,s+=8;s>=e;s-=e,r>>=e)i[u++]=n.decode(r&o);return i}}}}})({N:J,Q:ee,F:8347681,ROOT_OF_UNITY:1753,newPoly:le,isKyber:!1,brvBits:8}),de=e=>e,ae=(e,t=de,r=de)=>fe(e,{encode:e=>t(r(e)),decode:e=>r(t(e))}),ce=(e,t)=>{for(let r=0;r<e.length;r++)e[r]=ie(e[r]+t[r]);return e},he=(e,t)=>{for(let r=0;r<e.length;r++)e[r]=ie(e[r]-t[r]);return e},ye=e=>{for(let t=0;t<J;t++)e[t]<<=te;return e},ge=(e,t)=>{for(let r=0;r<J;r++)if(Math.abs(se(e[r]))>=t)return!0;return!1},pe=(e,t)=>{let r=le(J);for(let n=0;n<e.length;n++)r[n]=ie(e[n]*t[n]);return r};function we(e){let t=le(J);for(let r=0;r<J;){let n=e();if(n.length%3)throw new Error("RejNTTPoly: unaligned block");for(let e=0;r<J&&e<=n.length-3;e+=3){let o=8388607&(n[e+0]|n[e+1]<<8|n[e+2]<<16);o<ee&&(t[r++]=o)}}return t}function be(e){let{K:t,L:n,GAMMA1:o,GAMMA2:l,TAU:i,ETA:s,OMEGA:u}=e,{CRH_BYTES:f,TR_BYTES:d,C_TILDE_BYTES:a,XOF128:c,XOF256:h,securityLevel:y}=e;if(![2,4].includes(s))throw new Error("Wrong ETA");if(![1<<17,1<<19].includes(o))throw new Error("Wrong GAMMA1");if(![re,ne].includes(l))throw new Error("Wrong GAMMA2");let g=i*s,p=e=>{let t=ie(e),r=0|se(t,2*l);return t-r===ee-1?{r1:0,r0:r-1|0}:{r1:0|Math.floor((t-r)/(2*l)),r0:r}},w=e=>p(e).r1,b=e=>p(e).r0,A=(e,t)=>e<=l||e>ee-l||e===ee-l&&0===t?0:1,E=(e,t)=>{let r=Math.floor((ee-1)/(2*l)),{r1:n,r0:o}=p(t);return 1===e?o>0?0|ie(n+1,r):0|ie(n-1,r):0|n},L=e=>{let t=ie(e),r=0|se(t,8192);return{r1:0|Math.floor((t-r)/8192),r0:r}},m={bytesLen:u+t,encode:e=>{if(!1===e)throw new Error("hint.encode: hint is false");let r=new Uint8Array(u+t);for(let n=0,o=0;n<t;n++){for(let t=0;t<J;t++)0!==e[n][t]&&(r[o++]=t);r[u+n]=o}return r},decode:e=>{let r=[],n=0;for(let o=0;o<t;o++){let t=le(J);if(e[u+o]<n||e[u+o]>u)return!1;for(let r=n;r<e[u+o];r++){if(r>n&&e[r]<=e[r-1])return!1;t[e[r]]=1}n=e[u+o],r.push(t)}for(let t=n;t<u;t++)if(0!==e[t])return!1;return r}},v=ae(2===s?3:4,e=>s-e,e=>{if(!(-s<=e&&e<=s))throw new Error(`malformed key s1 / s3 ${e} outside of ETA range[${-s}, ${s}]`);return e}),T=ae(13,e=>4096-e),k=ae(10),x=ae(o===1<<17?18:20,e=>se(o-e)),M=P(ae(l===re?6:4),t),I=$("publicKey",32,P(k,t)),U=$("secretKey",32,32,d,P(v,n),P(v,t),P(T,t)),B=$("signature",a,P(x,n),m),_=2===s?e=>e<15&&2-e%5:e=>e<9&&4-e;function F(e){let t=le(J);for(let r=0;r<J;){let n=e();for(let e=0;r<J&&e<n.length;e+=1){let o=_(15&n[e]),l=_(n[e]>>4&15);!1!==o&&(t[r++]=o),r<J&&!1!==l&&(t[r++]=l)}}return t}let S=e=>{let t=le(J),r=O.create({}).update(e),n=new Uint8Array(O.blockLen);r.xofInto(n);let o=n.slice(0,8);for(let e=J-i,l=8,s=0,u=0;e<J;e++){let i=e+1;for(;i>e;)i=n[l++],!(l<O.blockLen)&&(r.xofInto(n),l=0);t[e]=t[i],t[i]=1-((o[s]>>u++&1)<<1),u>=8&&(s++,u=0)}return t},K=e=>{let t=le(J),r=le(J);for(let n=0;n<e.length;n++){let{r0:o,r1:l}=L(e[n]);t[n]=o,r[n]=l}return{r0:t,r1:r}},G=(e,t)=>{for(let r=0;r<J;r++)e[r]=E(t[r],e[r]);return e},D=(e,t)=>{let r=le(J),n=0;for(let o=0;o<J;o++){let l=A(e[o],t[o]);r[o]=l,n+=l}return{v:r,cnt:n}},j=$("seed",32,64,32),z={info:{type:"internal-ml-dsa"},lengths:{secretKey:U.bytesLen,publicKey:I.bytesLen,seed:32,signature:B.bytesLen,signRand:32},keygen:e=>{let o=new Uint8Array(34),l=void 0===e;l&&(e=N(32)),r(e,32,"seed"),o.set(e),l&&C(e),o[32]=t,o[33]=n;let[i,s,u]=j.decode(O(o,{dkLen:j.bytesLen})),f=h(s),a=[];for(let e=0;e<n;e++)a.push(F(f.get(255&e,e>>8&255)));let y=[];for(let e=n;e<n+t;e++)y.push(F(f.get(255&e,e>>8&255)));let g=a.map(e=>ue.encode(e.slice())),p=[],w=[],b=c(i),A=le(J);for(let e=0;e<t;e++){C(A);for(let t=0;t<n;t++){let r=we(b.get(t,e));ce(A,pe(r,g[t]))}ue.decode(A);let{r0:t,r1:r}=K(ce(A,y[e]));p.push(t),w.push(r)}let E=I.encode([i,w]),L=O(E,{dkLen:d}),m=U.encode([i,u,L,a,y,p]);return b.clean(),f.clean(),C(i,s,u,a,y,g,A,p,w,L,o),{publicKey:E,secretKey:m}},getPublicKey:e=>{let[r,o,l,i,s,u]=U.decode(e),f=c(r),d=i.map(e=>ue.encode(e.slice())),a=[],h=le(J);for(let e=0;e<t;e++){h.fill(0);for(let t=0;t<n;t++){let r=we(f.get(t,e));ce(h,pe(r,d[t]))}ue.decode(h),ce(h,s[e]);let{r1:t}=K(h);a.push(t)}return f.clean(),C(h,d,u,i,s),I.encode([r,a])},sign:(e,i,s={})=>{Y(s),Z(s);let{extraEntropy:d,externalMu:y=!1}=s,[p,A,E,L,m,v]=U.decode(i),T=[],k=c(p);for(let e=0;e<t;e++){let t=[];for(let r=0;r<n;r++)t.push(we(k.get(r,e)));T.push(t)}k.clean();for(let e=0;e<n;e++)ue.encode(L[e]);for(let e=0;e<t;e++)ue.encode(m[e]),ue.encode(v[e]);let I=y?e:O.create({dkLen:f}).update(E).update(e).digest(),_=!1===d?new Uint8Array(32):void 0===d?N(32):d;r(_,32,"extraEntropy");let F=O.create({dkLen:f}).update(A).update(_).update(I).digest();r(F,f);let K=h(F,x.bytesLen);e:for(let e=0;;){let r=[];for(let t=0;t<n;t++,e++)r.push(x.decode(K.get(255&e,e>>8)()));let i=r.map(e=>ue.encode(e.slice())),s=[];for(let e=0;e<t;e++){let t=le(J);for(let r=0;r<n;r++)ce(t,pe(T[e][r],i[r]));ue.decode(t),s.push(t)}let f=s.map(e=>e.map(w)),d=O.create({dkLen:a}).update(I).update(M.encode(f)).digest(),c=ue.encode(S(d)),h=L.map(e=>pe(e,c));for(let e=0;e<n;e++)if(ce(ue.decode(h[e]),r[e]),ge(h[e],o-g))continue e;let y=0,p=[];for(let e=0;e<t;e++){let t=ue.decode(pe(m[e],c)),r=he(s[e],t).map(b);if(ge(r,l-g))continue e;let n=ue.decode(pe(v[e],c));if(ge(n,l))continue e;ce(r,n);let o=D(r,f[e]);p.push(o.v),y+=o.cnt}if(y>u)continue;K.clean();let A=B.encode([d,h,p]);return C(d,h,p,c,f,s,i,r,F,I,L,m,v,...T),A}throw new Error("Unreachable code path reached, report this error")},verify:(e,r,l,i={})=>{Z(i);let{externalMu:s=!1}=i,[h,y]=I.decode(l),p=O(l,{dkLen:d});if(e.length!==B.bytesLen)return!1;let[w,b,A]=B.decode(e);if(!1===A)return!1;for(let e=0;e<n;e++)if(ge(b[e],o-g))return!1;let E=s?r:O.create({dkLen:f}).update(p).update(r).digest(),L=ue.encode(S(w)),m=b.map(e=>e.slice());for(let e=0;e<n;e++)ue.encode(m[e]);let v=[],T=c(h);for(let e=0;e<t;e++){let t=pe(ue.encode(ye(y[e])),L),r=le(J);for(let t=0;t<n;t++){let n=we(T.get(t,e));ce(r,pe(n,m[t]))}let o=ue.decode(he(r,t));v.push(G(o,A[e]))}T.clean();let k=O.create({dkLen:a}).update(E).update(M.encode(v)).digest();for(let e of A)if(!(e.reduce((e,t)=>e+t,0)<=u))return!1;for(let e of b)if(ge(e,o-g))return!1;return R(w,k)}};return{info:{type:"ml-dsa"},internal:z,securityLevel:y,keygen:z.keygen,lengths:z.lengths,getPublicKey:z.getPublicKey,sign:(e,t,r={})=>{Y(r);let n=H(e,r.context),o=z.sign(n,t,r);return C(n),o},verify:(e,t,r,n={})=>(X(n),z.verify(e,H(t,n.context),r)),prehash:e=>(function(e,t=0){if(!e.oid||!R(e.oid.subarray(0,10),q))throw new Error("hash.oid is invalid: expected NIST hash");let r=8*e.outputLen/2;if(t>r)throw new Error("Pre-hash security strength too low: "+r+", required: "+t)}(e,y),{info:{type:"hashml-dsa"},securityLevel:y,lengths:z.lengths,keygen:z.keygen,getPublicKey:z.getPublicKey,sign:(t,r,n={})=>{Y(n);let o=V(e,t,n.context),l=z.sign(o,r,n);return C(o),l},verify:(t,r,n,o={})=>(X(o),z.verify(t,V(e,r,o.context),n))})}}var Ae=be({...oe[2],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:32,XOF128:W,XOF256:Q,securityLevel:128}),Ee=be({...oe[3],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:48,XOF128:W,XOF256:Q,securityLevel:192}),Le=be({...oe[5],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:64,XOF128:W,XOF256:Q,securityLevel:256});export{oe as PARAMS,Ae as ml_dsa44,Ee as ml_dsa65,Le as ml_dsa87};
|
package/src/core/ml-kem.mjs
CHANGED
|
@@ -1,32 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Patch for browser and server environment
|
|
3
|
-
if (typeof window !== 'undefined') {
|
|
4
|
-
if (typeof window.require === 'undefined') {
|
|
5
|
-
window.require = function (name) {
|
|
6
|
-
if (name === 'semver') {
|
|
7
|
-
return {
|
|
8
|
-
valid: () => true,
|
|
9
|
-
clean: (v) => v,
|
|
10
|
-
satisfies: () => true,
|
|
11
|
-
gt: () => false,
|
|
12
|
-
lt: () => false,
|
|
13
|
-
coerce: (v) => v
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
return {};
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const require = (typeof window !== 'undefined') ? window.require : function (n) { return {}; };
|
|
21
|
-
/* esm.sh - @noble/post-quantum@0.5.2/ml-kem */
|
|
22
|
-
var $ = BigInt(4294967295), ut = BigInt(32); function Ct(t, e = !1) { return e ? { h: Number(t & $), l: Number(t >> ut & $) } : { h: Number(t >> ut & $) | 0, l: Number(t & $) | 0 } } function lt(t, e = !1) { let n = t.length, r = new Uint32Array(n), o = new Uint32Array(n); for (let c = 0; c < n; c++) { let { h: s, l: i } = Ct(t[c], e);[r[c], o[c]] = [s, i] } return [r, o] } var at = (t, e, n) => t << n | e >>> 32 - n, dt = (t, e, n) => e << n | t >>> 32 - n, pt = (t, e, n) => e << n - 32 | t >>> 64 - n, ht = (t, e, n) => t << n - 32 | e >>> 64 - n; function yt(t) { return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array" } function Y(t, e = "") { if (!Number.isSafeInteger(t) || t < 0) { let n = e && `"${e}" `; throw new Error(`${n}expected integer >= 0, got ${t}`) } } function O(t, e, n = "") { let r = yt(t), o = t?.length, c = e !== void 0; if (!r || c && o !== e) { let s = n && `"${n}" `, i = c ? ` of length ${e}` : "", a = r ? `length=${o}` : `type=${typeof t}`; throw new Error(s + "expected Uint8Array" + i + ", got " + a) } return t } function Q(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called") } function gt(t, e) { O(t, void 0, "digestInto() output"); let n = e.outputLen; if (t.length < n) throw new Error('"digestInto() output" expected to be of length >=' + n) } function X(t) { return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4)) } function J(...t) { for (let e = 0; e < t.length; e++)t[e].fill(0) } var Pt = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; function jt(t) { return t << 24 & 4278190080 | t << 8 & 16711680 | t >>> 8 & 65280 | t >>> 24 & 255 } function vt(t) { for (let e = 0; e < t.length; e++)t[e] = jt(t[e]); return t } var W = Pt ? t => t : vt; function tt(t, e = {}) { let n = (o, c) => t(c).update(o).digest(), r = t(void 0); return n.outputLen = r.outputLen, n.blockLen = r.blockLen, n.create = o => t(o), Object.assign(n, e), Object.freeze(n) } function xt(t = 32) { let e = typeof globalThis == "object" ? globalThis.crypto : null; if (typeof e?.getRandomValues != "function") throw new Error("crypto.getRandomValues must be defined"); return e.getRandomValues(new Uint8Array(t)) } var R = t => ({ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, t]) }); var Mt = BigInt(0), F = BigInt(1), $t = BigInt(2), Xt = BigInt(7), Dt = BigInt(256), Vt = BigInt(113), mt = [], At = [], kt = []; for (let t = 0, e = F, n = 1, r = 0; t < 24; t++) { [n, r] = [r, (2 * n + 3 * r) % 5], mt.push(2 * (5 * r + n)), At.push((t + 1) * (t + 2) / 2 % 64); let o = Mt; for (let c = 0; c < 7; c++)e = (e << F ^ (e >> Xt) * Vt) % Dt, e & $t && (o ^= F << (F << BigInt(c)) - F); kt.push(o) } var Et = lt(kt, !0), Zt = Et[0], zt = Et[1], bt = (t, e, n) => n > 32 ? pt(t, e, n) : at(t, e, n), wt = (t, e, n) => n > 32 ? ht(t, e, n) : dt(t, e, n); function Gt(t, e = 24) { let n = new Uint32Array(10); for (let r = 24 - e; r < 24; r++) { for (let s = 0; s < 10; s++)n[s] = t[s] ^ t[s + 10] ^ t[s + 20] ^ t[s + 30] ^ t[s + 40]; for (let s = 0; s < 10; s += 2) { let i = (s + 8) % 10, a = (s + 2) % 10, w = n[a], f = n[a + 1], p = bt(w, f, 1) ^ n[i], b = wt(w, f, 1) ^ n[i + 1]; for (let d = 0; d < 50; d += 10)t[s + d] ^= p, t[s + d + 1] ^= b } let o = t[2], c = t[3]; for (let s = 0; s < 24; s++) { let i = At[s], a = bt(o, c, i), w = wt(o, c, i), f = mt[s]; o = t[f], c = t[f + 1], t[f] = a, t[f + 1] = w } for (let s = 0; s < 50; s += 10) { for (let i = 0; i < 10; i++)n[i] = t[s + i]; for (let i = 0; i < 10; i++)t[s + i] ^= ~n[(i + 2) % 10] & n[(i + 4) % 10] } t[0] ^= Zt[r], t[1] ^= zt[r] } J(n) } var D = class t { state; pos = 0; posOut = 0; finished = !1; state32; destroyed = !1; blockLen; suffix; outputLen; enableXOF = !1; rounds; constructor(e, n, r, o = !1, c = 24) { if (this.blockLen = e, this.suffix = n, this.outputLen = r, this.enableXOF = o, this.rounds = c, Y(r, "outputLen"), !(0 < e && e < 200)) throw new Error("only keccak-f1600 function is supported"); this.state = new Uint8Array(200), this.state32 = X(this.state) } clone() { return this._cloneInto() } keccak() { W(this.state32), Gt(this.state32, this.rounds), W(this.state32), this.posOut = 0, this.pos = 0 } update(e) { Q(this), O(e); let { blockLen: n, state: r } = this, o = e.length; for (let c = 0; c < o;) { let s = Math.min(n - this.pos, o - c); for (let i = 0; i < s; i++)r[this.pos++] ^= e[c++]; this.pos === n && this.keccak() } return this } finish() { if (this.finished) return; this.finished = !0; let { state: e, suffix: n, pos: r, blockLen: o } = this; e[r] ^= n, (n & 128) !== 0 && r === o - 1 && this.keccak(), e[o - 1] ^= 128, this.keccak() } writeInto(e) { Q(this, !1), O(e), this.finish(); let n = this.state, { blockLen: r } = this; for (let o = 0, c = e.length; o < c;) { this.posOut >= r && this.keccak(); let s = Math.min(r - this.posOut, c - o); e.set(n.subarray(this.posOut, this.posOut + s), o), this.posOut += s, o += s } return e } xofInto(e) { if (!this.enableXOF) throw new Error("XOF is not possible for this instance"); return this.writeInto(e) } xof(e) { return Y(e), this.xofInto(new Uint8Array(e)) } digestInto(e) { if (gt(e, this), this.finished) throw new Error("digest() was already called"); return this.writeInto(e), this.destroy(), e } digest() { return this.digestInto(new Uint8Array(this.outputLen)) } destroy() { this.destroyed = !0, J(this.state) } _cloneInto(e) { let { blockLen: n, suffix: r, outputLen: o, rounds: c, enableXOF: s } = this; return e ||= new t(n, r, o, s, c), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = c, e.suffix = r, e.outputLen = o, e.enableXOF = s, e.destroyed = this.destroyed, e } }, Bt = (t, e, n, r = {}) => tt(() => new D(e, t, n), r); var Ot = Bt(6, 136, 32, R(8)); var Lt = Bt(6, 72, 64, R(10)); var Tt = (t, e, n, r = {}) => tt((o = {}) => new D(e, t, o.dkLen === void 0 ? n : o.dkLen, !0), r), _t = Tt(31, 168, 16, R(11)), V = Tt(31, 136, 32, R(12)); function et(t) { if (!Number.isSafeInteger(t) || t < 0 || t > 4294967295) throw new Error("wrong u32 integer:" + t); return t } function It(t) { return et(t), (t & t - 1) === 0 && t !== 0 } function nt(t, e) { et(t); let n = 0; for (let r = 0; r < e; r++, t >>>= 1)n = n << 1 | t & 1; return n } function Ut(t) { return et(t), 31 - Math.clz32(t) } function Ht(t) { let e = t.length; if (e < 2 || !It(e)) throw new Error("n must be a power of 2 and greater than 1. Got " + e); let n = Ut(e); for (let r = 0; r < e; r++) { let o = nt(r, n); if (r < o) { let c = t[r]; t[r] = t[o], t[o] = c } } return t } var rt = (t, e) => { let { N: n, roots: r, dit: o, invertButterflies: c = !1, skipStages: s = 0, brp: i = !0 } = e, a = Ut(n); if (!It(n)) throw new Error("FFT: Polynomial size should be power of two"); let w = o !== c; return f => { if (f.length !== n) throw new Error("FFT: wrong Polynomial length"); o && i && Ht(f); for (let p = 0, b = 1; p < a - s; p++) { let d = o ? p + 1 + s : a - p, B = 1 << d, I = B >> 1, H = n >> d; for (let L = 0; L < n; L += B)for (let u = 0, l = b++; u < I; u++) { let y = c ? o ? n - l : l : u * H, g = L + u, x = L + u + I, A = r[y], m = f[x], h = f[g]; if (w) { let k = t.mul(m, A); f[g] = t.add(h, k), f[x] = t.sub(h, k) } else c ? (f[g] = t.add(m, h), f[x] = t.mul(t.sub(m, h), A)) : (f[g] = t.add(h, m), f[x] = t.mul(t.sub(h, m), A)) } } return !o && i && Ht(f), f } }; var ot = xt; function Z(t, e) { if (t.length !== e.length) return !1; let n = 0; for (let r = 0; r < t.length; r++)n |= t[r] ^ e[r]; return n === 0 } function St(t) { return Uint8Array.from(t) } function N(t, ...e) { let n = o => typeof o == "number" ? o : o.bytesLen, r = e.reduce((o, c) => o + n(c), 0); return { bytesLen: r, encode: o => { let c = new Uint8Array(r); for (let s = 0, i = 0; s < e.length; s++) { let a = e[s], w = n(a), f = typeof a == "number" ? o[s] : a.encode(o[s]); O(f, w, t), c.set(f, i), typeof a != "number" && f.fill(0), i += w } return c }, decode: o => { O(o, r, t); let c = []; for (let s of e) { let i = n(s), a = o.subarray(0, i); c.push(typeof s == "number" ? a : s.decode(a)), o = o.subarray(i) } return c } } } function z(t, e) { let n = e * t.bytesLen; return { bytesLen: n, encode: r => { if (r.length !== e) throw new Error(`vecCoder.encode: wrong length=${r.length}. Expected: ${e}`); let o = new Uint8Array(n); for (let c = 0, s = 0; c < r.length; c++) { let i = t.encode(r[c]); o.set(i, s), i.fill(0), s += i.length } return o }, decode: r => { O(r, n); let o = []; for (let c = 0; c < r.length; c += t.bytesLen)o.push(t.decode(r.subarray(c, c + t.bytesLen))); return o } } } function _(...t) { for (let e of t) if (Array.isArray(e)) for (let n of e) n.fill(0); else e.fill(0) } function st(t) { return (1 << t) - 1 } var pe = Uint8Array.of(); var Kt = t => { let { newPoly: e, N: n, Q: r, F: o, ROOT_OF_UNITY: c, brvBits: s, isKyber: i } = t, a = (u, l = r) => { let y = u % l | 0; return (y >= 0 ? y | 0 : l + y | 0) | 0 }, w = (u, l = r) => { let y = a(u, l) | 0; return (y > l >> 1 ? y - l | 0 : y) | 0 }; function f() { let u = e(n); for (let l = 0; l < n; l++) { let y = nt(l, s), g = BigInt(c) ** BigInt(y) % BigInt(r); u[l] = Number(g) | 0 } return u } let p = f(), b = { add: (u, l) => a((u | 0) + (l | 0)) | 0, sub: (u, l) => a((u | 0) - (l | 0)) | 0, mul: (u, l) => a((u | 0) * (l | 0)) | 0, inv: u => { throw new Error("not implemented") } }, d = { N: n, roots: p, invertButterflies: !0, skipStages: i ? 1 : 0, brp: !1 }, B = rt(b, { dit: !1, ...d }), I = rt(b, { dit: !0, ...d }); return { mod: a, smod: w, nttZetas: p, NTT: { encode: u => B(u), decode: u => { I(u); for (let l = 0; l < u.length; l++)u[l] = a(o * u[l]); return u } }, bitsCoder: (u, l) => { let y = st(u), g = u * (n / 8); return { bytesLen: g, encode: x => { let A = new Uint8Array(g); for (let m = 0, h = 0, k = 0, E = 0; m < x.length; m++)for (h |= (l.encode(x[m]) & y) << k, k += u; k >= 8; k -= 8, h >>= 8)A[E++] = h & st(k); return A }, decode: x => { let A = e(n); for (let m = 0, h = 0, k = 0, E = 0; m < x.length; m++)for (h |= x[m] << k, k += 8; k >= u; k -= u, h >>= u)A[E++] = l.decode(h & y); return A } } } } }, qt = t => (e, n) => { n || (n = t.blockLen); let r = new Uint8Array(e.length + 2); r.set(e); let o = e.length, c = new Uint8Array(n), s = t.create({}), i = 0, a = 0; return { stats: () => ({ calls: i, xofs: a }), get: (w, f) => (r[o + 0] = w, r[o + 1] = f, s.destroy(), s = t.create({}).update(r), i++, () => (a++, s.xofInto(c))), clean: () => { s.destroy(), _(c, r) } } }, Rt = qt(_t); var T = 256, U = 3329, Yt = 3303, Qt = 17, { mod: j, nttZetas: Jt, NTT: S, bitsCoder: Wt } = Kt({ N: T, Q: U, F: Yt, ROOT_OF_UNITY: Qt, newPoly: t => new Uint16Array(t), brvBits: 7, isKyber: !0 }), ct = { 512: { N: T, Q: U, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }, 768: { N: T, Q: U, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }, 1024: { N: T, Q: U, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 } }, te = t => { if (t >= 12) return { encode: n => n, decode: n => n }; let e = 2 ** (t - 1); return { encode: n => ((n << t) + U / 2) / U, decode: n => n * U + e >>> t } }, C = t => Wt(t, te(t)); function K(t, e) { for (let n = 0; n < T; n++)t[n] = j(t[n] + e[n]) } function ee(t, e) { for (let n = 0; n < T; n++)t[n] = j(t[n] - e[n]) } function ne(t, e, n, r, o) { let c = j(e * r * o + t * n), s = j(t * r + e * n); return { c0: c, c1: s } } function G(t, e) { for (let n = 0; n < T / 2; n++) { let r = Jt[64 + (n >> 1)]; n & 1 && (r = -r); let { c0: o, c1: c } = ne(t[2 * n + 0], t[2 * n + 1], e[2 * n + 0], e[2 * n + 1], r); t[2 * n + 0] = o, t[2 * n + 1] = c } return t } function Ft(t) { let e = new Uint16Array(T); for (let n = 0; n < T;) { let r = t(); if (r.length % 3) throw new Error("SampleNTT: unaligned block"); for (let o = 0; n < T && o + 3 <= r.length; o += 3) { let c = (r[o + 0] >> 0 | r[o + 1] << 8) & 4095, s = (r[o + 1] >> 4 | r[o + 2] << 4) & 4095; c < U && (e[n++] = c), n < T && s < U && (e[n++] = s) } } return e } function P(t, e, n, r) { let o = t(r * T / 4, e, n), c = new Uint16Array(T), s = X(o), i = 0; for (let a = 0, w = 0, f = 0, p = 0; a < s.length; a++) { let b = s[a]; for (let d = 0; d < 32; d++)f += b & 1, b >>= 1, i += 1, i === r ? (p = f, f = 0) : i === 2 * r && (c[w++] = j(p - f), f = 0, i = 0) } if (i) throw new Error(`sampleCBD: leftover bits: ${i}`); return c } var re = t => { let { K: e, PRF: n, XOF: r, HASH512: o, ETA1: c, ETA2: s, du: i, dv: a } = t, w = C(1), f = C(a), p = C(i), b = N("publicKey", z(C(12), e), 32), d = z(C(12), e), B = N("ciphertext", z(p, e), f), I = N("seed", 32, 32); return { secretCoder: d, lengths: { secretKey: d.bytesLen, publicKey: b.bytesLen, cipherText: B.bytesLen }, keygen: H => { O(H, 32, "seed"); let L = new Uint8Array(33); L.set(H), L[32] = e; let u = o(L), [l, y] = I.decode(u), g = [], x = []; for (let h = 0; h < e; h++)g.push(S.encode(P(n, y, h, c))); let A = r(l); for (let h = 0; h < e; h++) { let k = S.encode(P(n, y, e + h, c)); for (let E = 0; E < e; E++) { let v = Ft(A.get(E, h)); K(k, G(v, g[E])) } x.push(k) } A.clean(); let m = { publicKey: b.encode([x, l]), secretKey: d.encode(g) }; return _(l, y, g, x, L, u), m }, encrypt: (H, L, u) => { let [l, y] = b.decode(H), g = []; for (let E = 0; E < e; E++)g.push(S.encode(P(n, u, E, c))); let x = r(y), A = new Uint16Array(T), m = []; for (let E = 0; E < e; E++) { let v = P(n, u, e + E, s), q = new Uint16Array(T); for (let M = 0; M < e; M++) { let Nt = Ft(x.get(E, M)); K(q, G(Nt, g[M])) } K(v, S.decode(q)), m.push(v), K(A, G(l[E], g[E])), _(q) } x.clean(); let h = P(n, u, 2 * e, s); K(h, S.decode(A)); let k = w.decode(L); return K(k, h), _(l, g, A, h), B.encode([m, k]) }, decrypt: (H, L) => { let [u, l] = B.decode(H), y = d.decode(L), g = new Uint16Array(T); for (let x = 0; x < e; x++)K(g, G(y[x], S.encode(u[x]))); return ee(l, S.decode(g)), _(g, y, u), w.encode(l) } } }; function it(t) { let e = re(t), { HASH256: n, HASH512: r, KDF: o } = t, { secretCoder: c, lengths: s } = e, i = N("secretKey", s.secretKey, s.publicKey, 32, 32), a = 32, w = 64; return { info: { type: "ml-kem" }, lengths: { ...s, seed: w, msg: a, msgRand: a, secretKey: i.bytesLen }, keygen: (f = ot(w)) => { O(f, w, "seed"); let { publicKey: p, secretKey: b } = e.keygen(f.subarray(0, 32)), d = n(p), B = i.encode([b, p, d, f.subarray(32)]); return _(b, d), { publicKey: p, secretKey: B } }, getPublicKey: f => { let [p, b, d, B] = i.decode(f); return Uint8Array.from(b) }, encapsulate: (f, p = ot(a)) => { O(f, s.publicKey, "publicKey"), O(p, a, "message"); let b = f.subarray(0, 384 * t.K), d = c.encode(c.decode(St(b))); if (!Z(d, b)) throw _(d), new Error("ML-KEM.encapsulate: wrong publicKey modulus"); _(d); let B = r.create().update(p).update(n(f)).digest(), I = e.encrypt(f, p, B.subarray(32, 64)); return _(B.subarray(32)), { cipherText: I, sharedSecret: B.subarray(0, 32) } }, decapsulate: (f, p) => { O(p, i.bytesLen, "secretKey"), O(f, s.cipherText, "cipherText"); let b = i.bytesLen - 96, d = b + 32, B = n(p.subarray(b / 2, d)); if (!Z(B, p.subarray(d, d + 32))) throw new Error("invalid secretKey: hash check failed"); let [I, H, L, u] = i.decode(p), l = e.decrypt(f, I), y = r.create().update(l).update(L).digest(), g = y.subarray(0, 32), x = e.encrypt(H, l, y.subarray(32, 64)), A = Z(f, x), m = o.create({ dkLen: 32 }).update(u).update(f).digest(); return _(l, x, A ? m : g), A ? g : m } } } function oe(t, e, n) { return V.create({ dkLen: t }).update(e).update(new Uint8Array([n])).digest() } var ft = { HASH256: Ot, HASH512: Lt, KDF: V, XOF: Rt, PRF: oe }, Be = it({ ...ft, ...ct[512] }), Oe = it({ ...ft, ...ct[768] }), Le = it({ ...ft, ...ct[1024] }); export { ct as PARAMS, Le as ml_kem1024, Be as ml_kem512, Oe as ml_kem768 };
|
|
23
|
-
/*! Bundled license information:
|
|
24
|
-
|
|
25
|
-
@noble/hashes/utils.js:
|
|
26
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
27
|
-
|
|
28
|
-
@noble/post-quantum/utils.js:
|
|
29
|
-
@noble/post-quantum/_crystals.js:
|
|
30
|
-
@noble/post-quantum/ml-kem.js:
|
|
31
|
-
(*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
|
|
32
|
-
*/
|
|
1
|
+
"undefined"!=typeof window&&void 0===window.require&&(window.require=function(e){return"semver"===e?{valid:()=>!0,clean:e=>e,satisfies:()=>!0,gt:()=>!1,lt:()=>!1,coerce:e=>e}:{}});"undefined"!=typeof window&&window.require;var e=BigInt(4294967295),t=BigInt(32);function r(r,n=!1){return n?{h:Number(r&e),l:Number(r>>t&e)}:{h:0|Number(r>>t&e),l:0|Number(r&e)}}function n(e,t=""){if(!Number.isSafeInteger(e)||e<0){throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}}function o(e,t,r=""){let n=function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e),o=e?.length,i=void 0!==t;if(!n||i&&o!==t){throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(n?`length=${o}`:"type="+typeof e))}return e}function i(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function s(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function l(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function u(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var d=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=u(e[t]);return e};function a(e,t={}){let r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}var f=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),c=BigInt(0),h=BigInt(1),y=BigInt(2),p=BigInt(7),g=BigInt(256),b=BigInt(113),w=[],m=[],A=[];for(let e=0,t=h,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],w.push(2*(5*n+r)),m.push((e+1)*(e+2)/2%64);let o=c;for(let e=0;e<7;e++)t=(t<<h^(t>>p)*b)%g,t&y&&(o^=h<<(h<<BigInt(e))-h);A.push(o)}var L=function(e,t=!1){let n=e.length,o=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){let{h:n,l:l}=r(e[s],t);[o[s],i[s]]=[n,l]}return[o,i]}(A,!0),k=L[0],U=L[1],E=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),K=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);var v=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,i=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=i,n(r,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=s(this.state)}clone(){return this._cloneInto()}keccak(){d(this.state32),function(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,o=(t+2)%10,i=r[o],s=r[o+1],l=E(i,s,1)^r[n],u=K(i,s,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=l,e[t+r+1]^=u}let t=e[2],o=e[3];for(let r=0;r<24;r++){let n=m[r],i=E(t,o,n),s=K(t,o,n),l=w[r];t=e[l],o=e[l+1],e[l]=i,e[l+1]=s}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=k[n],e[1]^=U[n]}l(r)}(this.state32,this.rounds),d(this.state32),this.posOut=0,this.pos=0}update(e){i(this),o(e);let{blockLen:t,state:r}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(t-this.pos,n-o);for(let t=0;t<i;t++)r[this.pos++]^=e[o++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,!!(128&t)&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){i(this,!1),o(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return n(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){o(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,l(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||=new e(r,n,o,s,i),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.destroyed=this.destroyed,t}},I=(e,t,r,n={})=>a(()=>new v(t,e,r),n),O=I(6,136,32,f(8)),T=I(6,72,64,f(10)),B=(e,t,r,n={})=>a((n={})=>new v(t,e,void 0===n.dkLen?r:n.dkLen,!0),n),x=B(31,168,16,f(11)),F=B(31,136,32,f(12));function N(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error("wrong u32 integer:"+e);return e}function H(e){return N(e),!(e&e-1)&&0!==e}function R(e,t){N(e);let r=0;for(let n=0;n<t;n++,e>>>=1)r=r<<1|1&e;return r}function S(e){return N(e),31-Math.clz32(e)}function $(e){let t=e.length;if(t<2||!H(t))throw new Error("n must be a power of 2 and greater than 1. Got "+t);let r=S(t);for(let n=0;n<t;n++){let t=R(n,r);if(n<t){let r=e[n];e[n]=e[t],e[t]=r}}return e}var _=(e,t)=>{let{N:r,roots:n,dit:o,invertButterflies:i=!1,skipStages:s=0,brp:l=!0}=t,u=S(r);if(!H(r))throw new Error("FFT: Polynomial size should be power of two");let d=o!==i;return t=>{if(t.length!==r)throw new Error("FFT: wrong Polynomial length");o&&l&&$(t);for(let l=0,a=1;l<u-s;l++){let f=o?l+1+s:u-l,c=1<<f,h=c>>1,y=r>>f;for(let s=0;s<r;s+=c)for(let l=0,u=a++;l<h;l++){let a=s+l,f=s+l+h,c=n[i?o?r-u:u:l*y],p=t[f],g=t[a];if(d){let r=e.mul(p,c);t[a]=e.add(g,r),t[f]=e.sub(g,r)}else i?(t[a]=e.add(p,g),t[f]=e.mul(e.sub(p,g),c)):(t[a]=e.add(g,p),t[f]=e.mul(e.sub(g,p),c))}}return!o&&l&&$(t),t}},P=function(e=32){let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))};function X(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}function M(e,...t){let r=e=>"number"==typeof e?e:e.bytesLen,n=t.reduce((e,t)=>e+r(t),0);return{bytesLen:n,encode:i=>{let s=new Uint8Array(n);for(let n=0,l=0;n<t.length;n++){let u=t[n],d=r(u),a="number"==typeof u?i[n]:u.encode(i[n]);o(a,d,e),s.set(a,l),"number"!=typeof u&&a.fill(0),l+=d}return s},decode:i=>{o(i,n,e);let s=[];for(let e of t){let t=r(e),n=i.subarray(0,t);s.push("number"==typeof e?n:e.decode(n)),i=i.subarray(t)}return s}}}function C(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:n=>{if(n.length!==t)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${t}`);let o=new Uint8Array(r);for(let t=0,r=0;t<n.length;t++){let i=e.encode(n[t]);o.set(i,r),i.fill(0),r+=i.length}return o},decode:t=>{o(t,r);let n=[];for(let r=0;r<t.length;r+=e.bytesLen)n.push(e.decode(t.subarray(r,r+e.bytesLen)));return n}}}function Q(...e){for(let t of e)if(Array.isArray(t))for(let e of t)e.fill(0);else t.fill(0)}function G(e){return(1<<e)-1}Uint8Array.of();var V,j=(V=x,(e,t)=>{t||(t=V.blockLen);let r=new Uint8Array(e.length+2);r.set(e);let n=e.length,o=new Uint8Array(t),i=V.create({}),s=0,l=0;return{stats:()=>({calls:s,xofs:l}),get:(e,t)=>(r[n+0]=e,r[n+1]=t,i.destroy(),i=V.create({}).update(r),s++,()=>(l++,i.xofInto(o))),clean:()=>{i.destroy(),Q(o,r)}}}),q=256,z=3329,{mod:D,nttZetas:Y,NTT:Z,bitsCoder:J}=(e=>{let{newPoly:t,N:r,Q:n,F:o,ROOT_OF_UNITY:i,brvBits:s,isKyber:l}=e,u=(e,t=n)=>{let r=e%t|0;return 0|(r>=0?r:t+r)};let d=function(){let e=t(r);for(let t=0;t<r;t++){let r=R(t,s),o=BigInt(i)**BigInt(r)%BigInt(n);e[t]=0|Number(o)}return e}(),a={add:(e,t)=>0|u((0|e)+(0|t)),sub:(e,t)=>0|u((0|e)-(0|t)),mul:(e,t)=>0|u((0|e)*(0|t)),inv:e=>{throw new Error("not implemented")}},f={N:r,roots:d,invertButterflies:!0,skipStages:l?1:0,brp:!1},c=_(a,{dit:!1,...f}),h=_(a,{dit:!0,...f});return{mod:u,smod:(e,t=n)=>{let r=0|u(e,t);return 0|(r>t>>1?r-t:r)},nttZetas:d,NTT:{encode:e=>c(e),decode:e=>{h(e);for(let t=0;t<e.length;t++)e[t]=u(o*e[t]);return e}},bitsCoder:(e,n)=>{let o=G(e),i=e*(r/8);return{bytesLen:i,encode:t=>{let r=new Uint8Array(i);for(let i=0,s=0,l=0,u=0;i<t.length;i++)for(s|=(n.encode(t[i])&o)<<l,l+=e;l>=8;l-=8,s>>=8)r[u++]=s&G(l);return r},decode:i=>{let s=t(r);for(let t=0,r=0,l=0,u=0;t<i.length;t++)for(r|=i[t]<<l,l+=8;l>=e;l-=e,r>>=e)s[u++]=n.decode(r&o);return s}}}}})({N:q,Q:z,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),W={512:{N:q,Q:z,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:q,Q:z,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:q,Q:z,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},ee=e=>J(e,(e=>{if(e>=12)return{encode:e=>e,decode:e=>e};let t=2**(e-1);return{encode:t=>((t<<e)+z/2)/z,decode:r=>r*z+t>>>e}})(e));function te(e,t){for(let r=0;r<q;r++)e[r]=D(e[r]+t[r])}function re(e,t,r,n,o){return{c0:D(t*n*o+e*r),c1:D(e*n+t*r)}}function ne(e,t){for(let r=0;r<128;r++){let n=Y[64+(r>>1)];1&r&&(n=-n);let{c0:o,c1:i}=re(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],n);e[2*r+0]=o,e[2*r+1]=i}return e}function oe(e){let t=new Uint16Array(q);for(let r=0;r<q;){let n=e();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let e=0;r<q&&e+3<=n.length;e+=3){let o=4095&(n[e+0]|n[e+1]<<8),i=4095&(n[e+1]>>4|n[e+2]<<4);o<z&&(t[r++]=o),r<q&&i<z&&(t[r++]=i)}}return t}function ie(e,t,r,n){let o=e(n*q/4,t,r),i=new Uint16Array(q),l=s(o),u=0;for(let e=0,t=0,r=0,o=0;e<l.length;e++){let s=l[e];for(let e=0;e<32;e++)r+=1&s,s>>=1,u+=1,u===n?(o=r,r=0):u===2*n&&(i[t++]=D(o-r),r=0,u=0)}if(u)throw new Error(`sampleCBD: leftover bits: ${u}`);return i}var se=e=>{let{K:t,PRF:r,XOF:n,HASH512:i,ETA1:s,ETA2:l,du:u,dv:d}=e,a=ee(1),f=ee(d),c=ee(u),h=M("publicKey",C(ee(12),t),32),y=C(ee(12),t),p=M("ciphertext",C(c,t),f),g=M("seed",32,32);return{secretCoder:y,lengths:{secretKey:y.bytesLen,publicKey:h.bytesLen,cipherText:p.bytesLen},keygen:e=>{o(e,32,"seed");let l=new Uint8Array(33);l.set(e),l[32]=t;let u=i(l),[d,a]=g.decode(u),f=[],c=[];for(let e=0;e<t;e++)f.push(Z.encode(ie(r,a,e,s)));let p=n(d);for(let e=0;e<t;e++){let n=Z.encode(ie(r,a,t+e,s));for(let r=0;r<t;r++){te(n,ne(oe(p.get(r,e)),f[r]))}c.push(n)}p.clean();let b={publicKey:h.encode([c,d]),secretKey:y.encode(f)};return Q(d,a,f,c,l,u),b},encrypt:(e,o,i)=>{let[u,d]=h.decode(e),f=[];for(let e=0;e<t;e++)f.push(Z.encode(ie(r,i,e,s)));let c=n(d),y=new Uint16Array(q),g=[];for(let e=0;e<t;e++){let n=ie(r,i,t+e,l),o=new Uint16Array(q);for(let r=0;r<t;r++){te(o,ne(oe(c.get(e,r)),f[r]))}te(n,Z.decode(o)),g.push(n),te(y,ne(u[e],f[e])),Q(o)}c.clean();let b=ie(r,i,2*t,l);te(b,Z.decode(y));let w=a.decode(o);return te(w,b),Q(u,f,y,b),p.encode([g,w])},decrypt:(e,r)=>{let[n,o]=p.decode(e),i=y.decode(r),s=new Uint16Array(q);for(let e=0;e<t;e++)te(s,ne(i[e],Z.encode(n[e])));return function(e,t){for(let r=0;r<q;r++)e[r]=D(e[r]-t[r])}(o,Z.decode(s)),Q(s,i,n),a.encode(o)}}};function le(e){let t=se(e),{HASH256:r,HASH512:n,KDF:i}=e,{secretCoder:s,lengths:l}=t,u=M("secretKey",l.secretKey,l.publicKey,32,32);return{info:{type:"ml-kem"},lengths:{...l,seed:64,msg:32,msgRand:32,secretKey:u.bytesLen},keygen:(e=P(64))=>{o(e,64,"seed");let{publicKey:n,secretKey:i}=t.keygen(e.subarray(0,32)),s=r(n),l=u.encode([i,n,s,e.subarray(32)]);return Q(i,s),{publicKey:n,secretKey:l}},getPublicKey:e=>{let[t,r,n,o]=u.decode(e);return Uint8Array.from(r)},encapsulate:(i,u=P(32))=>{o(i,l.publicKey,"publicKey"),o(u,32,"message");let d=i.subarray(0,384*e.K),a=s.encode(s.decode(function(e){return Uint8Array.from(e)}(d)));if(!X(a,d))throw Q(a),new Error("ML-KEM.encapsulate: wrong publicKey modulus");Q(a);let f=n.create().update(u).update(r(i)).digest(),c=t.encrypt(i,u,f.subarray(32,64));return Q(f.subarray(32)),{cipherText:c,sharedSecret:f.subarray(0,32)}},decapsulate:(e,s)=>{o(s,u.bytesLen,"secretKey"),o(e,l.cipherText,"cipherText");let d=u.bytesLen-96,a=d+32;if(!X(r(s.subarray(d/2,a)),s.subarray(a,a+32)))throw new Error("invalid secretKey: hash check failed");let[f,c,h,y]=u.decode(s),p=t.decrypt(e,f),g=n.create().update(p).update(h).digest(),b=g.subarray(0,32),w=t.encrypt(c,p,g.subarray(32,64)),m=X(e,w),A=i.create({dkLen:32}).update(y).update(e).digest();return Q(p,w,m?A:b),m?b:A}}}var ue={HASH256:O,HASH512:T,KDF:F,XOF:j,PRF:function(e,t,r){return F.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}},de=le({...ue,...W[512]}),ae=le({...ue,...W[768]}),fe=le({...ue,...W[1024]});export{W as PARAMS,fe as ml_kem1024,de as ml_kem512,ae as ml_kem768};
|