qscl-nimo-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -6,22 +6,45 @@ const sign_1 = require("./crypto/sign");
6
6
  const handshake_1 = require("./handshake");
7
7
  const errors_1 = require("./errors");
8
8
  const transport_1 = require("./transport");
9
+ const kyber_1 = require("./crypto/wasm/kyber");
10
+ const dilithium_1 = require("./crypto/wasm/dilithium");
11
+ const oqs_wasm_loader_1 = require("./crypto/wasm/oqs_wasm_loader");
9
12
  class QSCLClient {
10
13
  config;
11
14
  sessionContext = null;
12
15
  transport = null;
13
- kem;
14
- sign;
16
+ kem = null;
17
+ sign = null;
15
18
  constructor(config) {
16
19
  this.config = config;
17
- // Default to fallback JS mocks until true WebAssembly payloads load
18
- this.kem = config.customKEM || new kem_1.MockKyberKEM();
19
- this.sign = config.customSign || new sign_1.MockDilithiumProvider();
20
20
  }
21
21
  /**
22
22
  * Initializes the hybrid PQC handshake. Must be called prior to fetching proxy routes.
23
23
  */
24
24
  async connect() {
25
+ if (!this.kem || !this.sign) {
26
+ if (this.config.customKEM && this.config.customSign) {
27
+ this.kem = this.config.customKEM;
28
+ this.sign = this.config.customSign;
29
+ }
30
+ else {
31
+ try {
32
+ await (0, oqs_wasm_loader_1.loadOQS)();
33
+ this.kem = new kyber_1.WasmKyberKEM();
34
+ this.sign = new dilithium_1.WasmDilithiumProvider();
35
+ }
36
+ catch (e) {
37
+ if (process.env?.NODE_ENV === "development") {
38
+ console.warn("[QSCL] ⚠️ WebAssembly LibOQS Engine omitted! Falling back to JS-mock cryptography natively (DEV ONLY).");
39
+ this.kem = new kem_1.MockKyberKEM();
40
+ this.sign = new sign_1.MockDilithiumProvider();
41
+ }
42
+ else {
43
+ throw new Error(`QSCL Client Critical Failure: WebAssembly PQC Engine could not be instantiated natively. ${e}`);
44
+ }
45
+ }
46
+ }
47
+ }
25
48
  const manager = new handshake_1.HandshakeManager({
26
49
  baseURL: this.config.baseURL,
27
50
  apiKey: this.config.apiKey,
@@ -0,0 +1,12 @@
1
+ import { ISignatureProvider } from '../sign';
2
+ export declare class WasmDilithiumProvider implements ISignatureProvider {
3
+ private readonly PK_LEN;
4
+ private readonly SK_LEN;
5
+ private readonly SIG_MAX_LEN;
6
+ generateKeyPair(): Promise<{
7
+ publicKey: Uint8Array;
8
+ privateKey: Uint8Array;
9
+ }>;
10
+ sign(message: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array>;
11
+ verify(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
12
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WasmDilithiumProvider = void 0;
4
+ const oqs_wasm_loader_1 = require("./oqs_wasm_loader");
5
+ class WasmDilithiumProvider {
6
+ PK_LEN = 1952; // ML-DSA-65 standard (Dilithium3)
7
+ SK_LEN = 4032; // ML-DSA-65 standard
8
+ SIG_MAX_LEN = 3309; // ML-DSA-65 standard
9
+ async generateKeyPair() {
10
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
11
+ const sigPtr = mod.ccall('OQS_SIG_new', 'number', ['string'], ['ML-DSA-65']);
12
+ if (sigPtr === 0)
13
+ throw new Error("Failed to instantiate ML-DSA-65 via WASM.");
14
+ const pkPtr = mod._malloc(this.PK_LEN);
15
+ const skPtr = mod._malloc(this.SK_LEN);
16
+ try {
17
+ const status = mod.ccall('OQS_SIG_keypair', 'number', ['number', 'number', 'number'], [sigPtr, pkPtr, skPtr]);
18
+ if (status !== 0)
19
+ throw new Error("WASM SIG Keypair generation failed.");
20
+ const pubData = new Uint8Array(mod.HEAPU8.buffer, pkPtr, this.PK_LEN).slice();
21
+ const secData = new Uint8Array(mod.HEAPU8.buffer, skPtr, this.SK_LEN).slice();
22
+ return { publicKey: pubData, privateKey: secData };
23
+ }
24
+ finally {
25
+ mod._free(pkPtr);
26
+ mod._free(skPtr);
27
+ mod.ccall('OQS_SIG_free', 'void', ['number'], [sigPtr]);
28
+ }
29
+ }
30
+ async sign(message, privateKey) {
31
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
32
+ const sigPtr = mod.ccall('OQS_SIG_new', 'number', ['string'], ['ML-DSA-65']);
33
+ const skPtr = mod._malloc(this.SK_LEN);
34
+ const msgPtr = mod._malloc(message.length);
35
+ const signaturePtr = mod._malloc(this.SIG_MAX_LEN);
36
+ const sigLenPtr = mod._malloc(4); // Uint32 pointer natively handling WASM32 size_t
37
+ try {
38
+ mod.HEAPU8.set(privateKey, skPtr);
39
+ mod.HEAPU8.set(message, msgPtr);
40
+ // Output requires signature, sigLenPtr, message, msgLen, skPtr
41
+ const status = mod.ccall('OQS_SIG_sign', 'number', ['number', 'number', 'number', 'number', 'number', 'number'], [sigPtr, signaturePtr, sigLenPtr, msgPtr, message.length, skPtr]);
42
+ if (status !== 0)
43
+ throw new Error("WASM Signature computation failed");
44
+ // Extract the actual length of the signature output
45
+ const actualSigLen = new Uint32Array(mod.HEAPU8.buffer, sigLenPtr, 1)[0];
46
+ return new Uint8Array(mod.HEAPU8.buffer, signaturePtr, actualSigLen).slice();
47
+ }
48
+ finally {
49
+ mod._free(skPtr);
50
+ mod._free(msgPtr);
51
+ mod._free(signaturePtr);
52
+ mod._free(sigLenPtr);
53
+ mod.ccall('OQS_SIG_free', 'void', ['number'], [sigPtr]);
54
+ }
55
+ }
56
+ async verify(message, signature, publicKey) {
57
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
58
+ const sigPtr = mod.ccall('OQS_SIG_new', 'number', ['string'], ['ML-DSA-65']);
59
+ const pkPtr = mod._malloc(this.PK_LEN);
60
+ const msgPtr = mod._malloc(message.length);
61
+ const sigPtrMem = mod._malloc(signature.length);
62
+ try {
63
+ mod.HEAPU8.set(publicKey, pkPtr);
64
+ mod.HEAPU8.set(message, msgPtr);
65
+ mod.HEAPU8.set(signature, sigPtrMem);
66
+ // Function strictly requires: `const OQS_SIG *sig, const uint8_t *message, size_t message_len, const uint8_t *signature, size_t signature_len, const uint8_t *public_key`
67
+ const status = mod.ccall('OQS_SIG_verify', 'number', ['number', 'number', 'number', 'number', 'number', 'number'], [sigPtr, msgPtr, message.length, sigPtrMem, signature.length, pkPtr]);
68
+ // 0 equates exactly to Success
69
+ return status === 0;
70
+ }
71
+ finally {
72
+ mod._free(pkPtr);
73
+ mod._free(msgPtr);
74
+ mod._free(sigPtrMem);
75
+ mod.ccall('OQS_SIG_free', 'void', ['number'], [sigPtr]);
76
+ }
77
+ }
78
+ }
79
+ exports.WasmDilithiumProvider = WasmDilithiumProvider;
@@ -0,0 +1,16 @@
1
+ import { IKEMProvider } from '../kem';
2
+ export declare class WasmKyberKEM implements IKEMProvider {
3
+ private readonly PK_LEN;
4
+ private readonly SK_LEN;
5
+ private readonly CT_LEN;
6
+ private readonly SS_LEN;
7
+ generateKeyPair(): Promise<{
8
+ publicKey: Uint8Array;
9
+ privateKey: Uint8Array;
10
+ }>;
11
+ encapsulate(publicKey: Uint8Array): Promise<{
12
+ ciphertext: Uint8Array;
13
+ sharedSecret: Uint8Array;
14
+ }>;
15
+ decapsulate(ciphertext: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array>;
16
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WasmKyberKEM = void 0;
4
+ const oqs_wasm_loader_1 = require("./oqs_wasm_loader");
5
+ class WasmKyberKEM {
6
+ PK_LEN = 1184; // ML-KEM-768 standard
7
+ SK_LEN = 2400; // ML-KEM-768 standard
8
+ CT_LEN = 1088; // ML-KEM-768 standard
9
+ SS_LEN = 32; // ML-KEM-768 standard
10
+ async generateKeyPair() {
11
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
12
+ const kemPtr = mod.ccall('OQS_KEM_new', 'number', ['string'], ['ML-KEM-768']);
13
+ if (kemPtr === 0)
14
+ throw new Error("Failed to instantiate ML-KEM-768 via WASM. Not mapped in binary.");
15
+ const pkPtr = mod._malloc(this.PK_LEN);
16
+ const skPtr = mod._malloc(this.SK_LEN);
17
+ try {
18
+ const status = mod.ccall('OQS_KEM_keypair', 'number', ['number', 'number', 'number'], [kemPtr, pkPtr, skPtr]);
19
+ if (status !== 0)
20
+ throw new Error("WASM KEM Keypair generation failed natively.");
21
+ const pubData = new Uint8Array(mod.HEAPU8.buffer, pkPtr, this.PK_LEN).slice();
22
+ const secData = new Uint8Array(mod.HEAPU8.buffer, skPtr, this.SK_LEN).slice();
23
+ return { publicKey: pubData, privateKey: secData };
24
+ }
25
+ finally {
26
+ mod._free(pkPtr);
27
+ mod._free(skPtr);
28
+ mod.ccall('OQS_KEM_free', 'void', ['number'], [kemPtr]);
29
+ }
30
+ }
31
+ async encapsulate(publicKey) {
32
+ if (publicKey.length !== this.PK_LEN)
33
+ throw new Error("Invalid PK length");
34
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
35
+ const kemPtr = mod.ccall('OQS_KEM_new', 'number', ['string'], ['ML-KEM-768']);
36
+ const pkPtr = mod._malloc(this.PK_LEN);
37
+ const ctPtr = mod._malloc(this.CT_LEN);
38
+ const ssPtr = mod._malloc(this.SS_LEN);
39
+ try {
40
+ mod.HEAPU8.set(publicKey, pkPtr);
41
+ const status = mod.ccall('OQS_KEM_encaps', 'number', ['number', 'number', 'number', 'number'], [kemPtr, ctPtr, ssPtr, pkPtr]);
42
+ if (status !== 0)
43
+ throw new Error("WASM KEM Encapsulation extraction failed");
44
+ const ctData = new Uint8Array(mod.HEAPU8.buffer, ctPtr, this.CT_LEN).slice();
45
+ const ssData = new Uint8Array(mod.HEAPU8.buffer, ssPtr, this.SS_LEN).slice();
46
+ return { ciphertext: ctData, sharedSecret: ssData };
47
+ }
48
+ finally {
49
+ mod._free(pkPtr);
50
+ mod._free(ctPtr);
51
+ mod._free(ssPtr);
52
+ mod.ccall('OQS_KEM_free', 'void', ['number'], [kemPtr]);
53
+ }
54
+ }
55
+ async decapsulate(ciphertext, privateKey) {
56
+ if (ciphertext.length !== this.CT_LEN)
57
+ throw new Error("Invalid CT length");
58
+ const mod = await (0, oqs_wasm_loader_1.loadOQS)();
59
+ const kemPtr = mod.ccall('OQS_KEM_new', 'number', ['string'], ['ML-KEM-768']);
60
+ const ctPtr = mod._malloc(this.CT_LEN);
61
+ const skPtr = mod._malloc(this.SK_LEN);
62
+ const ssPtr = mod._malloc(this.SS_LEN);
63
+ try {
64
+ mod.HEAPU8.set(ciphertext, ctPtr);
65
+ mod.HEAPU8.set(privateKey, skPtr);
66
+ const status = mod.ccall('OQS_KEM_decaps', 'number', ['number', 'number', 'number', 'number'], [kemPtr, ssPtr, ctPtr, skPtr]);
67
+ if (status !== 0)
68
+ throw new Error("WASM KEM Decapsulation structure failed!");
69
+ return new Uint8Array(mod.HEAPU8.buffer, ssPtr, this.SS_LEN).slice();
70
+ }
71
+ finally {
72
+ mod._free(ctPtr);
73
+ mod._free(skPtr);
74
+ mod._free(ssPtr);
75
+ mod.ccall('OQS_KEM_free', 'void', ['number'], [kemPtr]);
76
+ }
77
+ }
78
+ }
79
+ exports.WasmKyberKEM = WasmKyberKEM;
@@ -0,0 +1,2 @@
1
+ var createOQSModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["i"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("oqs.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);function getValue(ptr,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":return HEAP8[ptr];case"i8":return HEAP8[ptr];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP64[ptr>>3];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];case"*":return HEAPU32[ptr>>2];default:abort(`invalid type for getValue: ${type}`)}}var noExitRuntime=true;function setValue(ptr,value,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":HEAP8[ptr]=value;break;case"i8":HEAP8[ptr]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":HEAP64[ptr>>3]=BigInt(value);break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;case"*":HEAPU32[ptr>>2]=value;break;default:abort(`invalid type for setValue: ${type}`)}}var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var _fd_close=fd=>52;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var flush_NO_FILESYSTEM=()=>{if(printCharBuffers[1].length)printChar(1,10);if(printCharBuffers[2].length)printChar(2,10)};var SYSCALLS={varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var _random_get=(buffer,size)=>{randomFill(HEAPU8.subarray(buffer,buffer+size));return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["setValue"]=setValue;Module["getValue"]=getValue;Module["ExitStatus"]=ExitStatus;Module["HEAP16"]=HEAP16;Module["HEAP32"]=HEAP32;Module["HEAP64"]=HEAP64;Module["HEAP8"]=HEAP8;Module["HEAPF32"]=HEAPF32;Module["HEAPF64"]=HEAPF64;Module["HEAPU16"]=HEAPU16;Module["HEAPU32"]=HEAPU32;Module["HEAPU64"]=HEAPU64;Module["HEAPU8"]=HEAPU8;Module["addOnPostRun"]=addOnPostRun;Module["onPostRuns"]=onPostRuns;Module["callRuntimeCallbacks"]=callRuntimeCallbacks;Module["addOnPreRun"]=addOnPreRun;Module["onPreRuns"]=onPreRuns;Module["getValue"]=getValue;Module["noExitRuntime"]=noExitRuntime;Module["setValue"]=setValue;Module["stackRestore"]=stackRestore;Module["stackSave"]=stackSave;Module["___assert_fail"]=___assert_fail;Module["UTF8ToString"]=UTF8ToString;Module["UTF8ArrayToString"]=UTF8ArrayToString;Module["UTF8Decoder"]=UTF8Decoder;Module["findStringEnd"]=findStringEnd;Module["_emscripten_resize_heap"]=_emscripten_resize_heap;Module["getHeapMax"]=getHeapMax;Module["alignMemory"]=alignMemory;Module["growMemory"]=growMemory;Module["_exit"]=_exit;Module["exitJS"]=exitJS;Module["_proc_exit"]=_proc_exit;Module["keepRuntimeAlive"]=keepRuntimeAlive;Module["runtimeKeepaliveCounter"]=runtimeKeepaliveCounter;Module["_fd_close"]=_fd_close;Module["_fd_seek"]=_fd_seek;Module["bigintToI53Checked"]=bigintToI53Checked;Module["INT53_MAX"]=INT53_MAX;Module["INT53_MIN"]=INT53_MIN;Module["_fd_write"]=_fd_write;Module["flush_NO_FILESYSTEM"]=flush_NO_FILESYSTEM;Module["printChar"]=printChar;Module["printCharBuffers"]=printCharBuffers;Module["SYSCALLS"]=SYSCALLS;Module["_random_get"]=_random_get;Module["randomFill"]=randomFill;Module["initRandomFill"]=initRandomFill;Module["ccall"]=ccall;Module["getCFunc"]=getCFunc;Module["writeArrayToMemory"]=writeArrayToMemory;Module["stringToUTF8OnStack"]=stringToUTF8OnStack;Module["lengthBytesUTF8"]=lengthBytesUTF8;Module["stringToUTF8"]=stringToUTF8;Module["stringToUTF8Array"]=stringToUTF8Array;Module["stackAlloc"]=stackAlloc;Module["cwrap"]=cwrap;var _OQS_KEM_new,_OQS_KEM_keypair,_OQS_KEM_encaps,_OQS_KEM_decaps,_OQS_KEM_free,_OQS_SIG_new,_OQS_SIG_keypair,_OQS_SIG_sign,_OQS_SIG_verify,_OQS_SIG_free,_malloc,_free,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_OQS_KEM_new=Module["_OQS_KEM_new"]=wasmExports["j"];_OQS_KEM_keypair=Module["_OQS_KEM_keypair"]=wasmExports["k"];_OQS_KEM_encaps=Module["_OQS_KEM_encaps"]=wasmExports["l"];_OQS_KEM_decaps=Module["_OQS_KEM_decaps"]=wasmExports["m"];_OQS_KEM_free=Module["_OQS_KEM_free"]=wasmExports["n"];_OQS_SIG_new=Module["_OQS_SIG_new"]=wasmExports["o"];_OQS_SIG_keypair=Module["_OQS_SIG_keypair"]=wasmExports["p"];_OQS_SIG_sign=Module["_OQS_SIG_sign"]=wasmExports["q"];_OQS_SIG_verify=Module["_OQS_SIG_verify"]=wasmExports["r"];_OQS_SIG_free=Module["_OQS_SIG_free"]=wasmExports["s"];_malloc=Module["_malloc"]=wasmExports["t"];_free=Module["_free"]=wasmExports["u"];__emscripten_stack_restore=Module["__emscripten_stack_restore"]=wasmExports["v"];__emscripten_stack_alloc=Module["__emscripten_stack_alloc"]=wasmExports["w"];_emscripten_stack_get_current=Module["_emscripten_stack_get_current"]=wasmExports["x"];memory=Module["memory"]=wasmMemory=wasmExports["h"];__indirect_function_table=Module["__indirect_function_table"]=wasmExports["y"]}var wasmImports={a:___assert_fail,g:_emscripten_resize_heap,b:_exit,e:_fd_close,d:_fd_seek,c:_fd_write,f:_random_get};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
2
+ ;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=createOQSModule;module.exports.default=createOQSModule}else if(typeof define==="function"&&define["amd"])define([],()=>createOQSModule);
Binary file
@@ -0,0 +1,14 @@
1
+ export interface OQSModule {
2
+ ccall: (ident: string, returnType: string | null, argTypes: string[], args: any[]) => any;
3
+ cwrap: (ident: string, returnType: string | null, argTypes: string[]) => any;
4
+ getValue: (ptr: number, type: string) => any;
5
+ setValue: (ptr: number, value: any, type: string) => void;
6
+ _malloc: (size: number) => number;
7
+ _free: (ptr: number) => void;
8
+ HEAPU8: Uint8Array;
9
+ }
10
+ /**
11
+ * Ensures the WebAssembly LibOQS Engine is dynamically loaded securely
12
+ * Abstracting away C-binding asynchronous compilations into a Single Global Instance securely
13
+ */
14
+ export declare function loadOQS(): Promise<OQSModule>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadOQS = loadOQS;
4
+ let oqsInstance = null;
5
+ let initPromise = null;
6
+ /**
7
+ * Ensures the WebAssembly LibOQS Engine is dynamically loaded securely
8
+ * Abstracting away C-binding asynchronous compilations into a Single Global Instance securely
9
+ */
10
+ async function loadOQS() {
11
+ if (oqsInstance)
12
+ return oqsInstance;
13
+ if (initPromise)
14
+ return initPromise;
15
+ initPromise = new Promise(async (resolve, reject) => {
16
+ const timeout = setTimeout(() => reject(new Error("QSCL WASM Engine Load Timeout (5s)")), 5000);
17
+ try {
18
+ // Natively bind to the Emscripten factory dynamically preventing TS from static import constraints
19
+ const factory = require('./oqs.js');
20
+ const mod = await factory();
21
+ clearTimeout(timeout);
22
+ oqsInstance = mod;
23
+ resolve(oqsInstance);
24
+ }
25
+ catch (e) {
26
+ clearTimeout(timeout);
27
+ reject(e);
28
+ }
29
+ });
30
+ return initPromise;
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qscl-nimo-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Quantum-Safe Communication Layer (QSCL) Developer SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -12,11 +12,17 @@
12
12
  "url": "git+https://github.com/Namoj-design/PQC-API-SDK-Payments.git"
13
13
  },
14
14
  "scripts": {
15
- "build": "tsc",
15
+ "build": "tsc && mkdir -p dist/crypto/wasm && cp src/crypto/wasm/oqs.wasm dist/crypto/wasm/ || true && cp src/crypto/wasm/oqs.js dist/crypto/wasm/ || true",
16
16
  "dev": "tsc --watch",
17
17
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
18
18
  },
19
- "keywords": ["quantum-safe", "pqc", "kyber", "dilithium", "security"],
19
+ "keywords": [
20
+ "quantum-safe",
21
+ "pqc",
22
+ "kyber",
23
+ "dilithium",
24
+ "security"
25
+ ],
20
26
  "author": "QSCL Admin",
21
27
  "license": "UNLICENSED",
22
28
  "devDependencies": {