Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vault-storage

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vault-storage - npm Package Compare versions

Comparing version 1.0.8 to 1.1.0

build.js

61

dist/index.js

@@ -1,59 +0,2 @@

const RW = 'readwrite';
const R = 'readonly';
let db = null;
const storeName = "vault";
const vault = new Proxy({
async setItem(key, value) {
return $(RW, store => store.put({ key, value }));
},
async getItem(key) {
return $(R, store => store.get(key))
.then(result => result ? result.value : null);
},
async removeItem(key) {
return $(RW, store => store.delete(key));
},
async clear() {
return $(RW, store => store.clear());
},
async length() {
return $(R, store => store.count());
}
}, {
get(target, key) {
return target[key] || target.getItem(key);
},
set(target, key, value) {
target.setItem(key, value);
return true;
},
deleteProperty(target, key) {
return target.removeItem(key);
}
});
async function $(operationType, operation) {
db = db || await initDB(location.host, storeName);
return new Promise((resolve, reject) => {
const request = operation(db.transaction(storeName, operationType)
.objectStore(storeName));
request.onsuccess = () => resolve(operationType === R ? request.result : void 0);
request.onerror = (event) => reject(event);
});
}
async function initDB(dbName, storeName) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onupgradeneeded = (event) => {
const db = request.result;
db.createObjectStore(storeName, { keyPath: 'key' });
};
request.onsuccess = (event) => {
resolve(request.result);
};
request.onerror = (event) => {
reject(event);
};
});
}
export default vault;
//# sourceMappingURL=index.js.map
var l={get(n,e){return typeof n[e]=="function"?n[e].bind(n):e in n?n[e]:n.getItem(e)},set(n,e,t){return n.setItem(e,t)},deleteProperty(n,e){return n.removeItem(e)}},u=l;var i="readonly",a="readwrite",d="store",o=class{dbName="vault";db=null;constructor(e,t=!1){if(this.dbName=e||this.dbName,!t)return new Proxy(this,u)}async setItem(e,t){return this.do(a,r=>r.put({key:e,value:t}))}async getItem(e){return this.do(i,t=>t.get(e)).then(t=>t?.value??null)}async removeItem(e){return this.do(a,t=>t.delete(e))}async clear(){return this.do(a,e=>e.clear())}async keys(){return this.do(i,e=>e.getAllKeys())}async length(){return this.do(i,e=>e.count())}async init(){return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=s=>{s.target.result.createObjectStore(d,{keyPath:"key"})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=s=>t(s)})}async do(e,t){this.db||await this.init();let r=this.db.transaction(d,e),s=t(r.objectStore(d));return new Promise((c,y)=>{s.onsuccess=()=>c(e===i?s.result:void 0),s.onerror=()=>y(s.error)})}};var m=new o,f=m;export{f as default};
//# sourceMappingURL=index.js.map

@@ -29,5 +29,9 @@ // Karma configuration

preprocessors: {
'**/*.ts': 'karma-typescript' // Preprocess all TypeScript files with karma-typescript
'**/*.js': ['sourcemap']
},
// plugins: [
// 'karma-sourcemap-loader'
// ],
karmaTypescriptConfig: {

@@ -34,0 +38,0 @@ tsconfig: './tsconfig.json'

{
"name": "vault-storage",
"version": "1.0.8",
"description": "Vault, a tiny yet robuts storage library for your browser applications",
"main": "dist/index.js",
"types": "typings/index.d.ts",
"description": "Vault, a micro yet robust browser storage library",
"version": "1.1.0",
"author": "ManiarTech®️ - Mohamed Aamir Maniar",
"license": "MIT",
"repository": {
"type": "git",
"url": "git@github.com:maniartech/vault.git"
},
"keywords": [

@@ -11,4 +15,4 @@ "vault",

"storage",
"storage",
"indexeddb",
"idb",
"database",

@@ -22,9 +26,8 @@ "client-storage",

"asynchronous",
"browser-database",
"local-storage",
"data-management",
"browser-storage",
"idb",
"browser-database",
"nosql",
"indexdb-wrapper",
"browser-storage",
"data-cache",

@@ -34,19 +37,14 @@ "javascript-storage",

],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"test": "karma start",
"watch": "tsc -w"
"test": "karma start karma.conf.js",
"build:types": "tsc",
"build": "node ./build.js && npm run build:types",
"watch": "node ./build.js --watch --debug"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "jsdom"
},
"author": "ManiarTech®️ - Mohamed Aamir Maniar",
"license": "ISC",
"repository": {
"type": "git",
"url": "git@github.com:maniartech/vault.git"
},
"devDependencies": {
"@types/jasmine": "^5.1.4",
"@types/node": "^20.10.6",
"esbuild": "^0.19.11",
"jasmine-core": "^5.1.1",

@@ -57,2 +55,4 @@ "karma": "^6.4.2",

"karma-jasmine": "^5.1.0",
"karma-sourcemap-loader": "^0.4.0",
"karma-spec-reporter": "^0.0.36",
"karma-typescript": "^5.5.4",

@@ -59,0 +59,0 @@ "ts-node": "^10.9.2",

@@ -12,3 +12,7 @@ # vault

- **Similar API**: Easy to use, similar to LocalStorage.
- **Lightweight**: No dependencies, micro footprint (~800 bytes minified, ~400 bytes gzipped).
- **Lightweight**: No dependencies, micro footprint
- Less than a KB (minified and gzipped), unsecured vault
- Aroound 1.5 KB (minified and gzipped), secured vault
- **Multiple Stores Support**: Supports multiple stores with single api.
- **Encrypted Vault**: Provides a secure storage for sensitive data.
- **Asynchronous**: Non-blocking, asynchronous API.

@@ -57,2 +61,59 @@ - **Structured Data**: Supports structured data, including objects and arrays.

### Custom Storage
You can also use a custom database name and store name. This is useful when you
want to use multiple databases or stores.
```javascript
import Vault from 'vault-storage/vault';
const myStorage = new Vault("my-storage")
myStorage.setItem("key", "value")
console.log("key", await myStorage.getItem("key"))
```
### Custom Secure Database
Secured databases are useful when you want to store sensitive data. It provides
similar API to the `vault` but it encrypts the data before storing it in the
database. It uses browser's native crypto API to encrypt the data.
```javascript
import SecuredVault from 'vault-storage/secured-vault';
// Secured storage using fixed password and salt.
const securedStorage1 = new SecuredVault("secured-storage", {
password: "my-password",
salt: "my-salt",
});
// Secured storage using dynamic password and salt.
const securedStorage2 = new SecuredVault("secured-storage", (key) => {
const password = key.startsWith("key1") ? "my-password1" : "my-password2";
const salt = key.startsWith("key1") ? "my-salt1" : "my-salt2";
return { password, salt };
});
// Secured storage using promise based password and salt.
const securedStorage3 = new SecuredVault("secured-storage", async (key) => {
return new Promise(async (resolve) => {
const res = await fetch("/get-key")
const { password, salt } = generatePasswordFromKey(res.key)
resolve({ password, salt })
});
});
// Once the secured valued is setup, usage is similar to the regular vault storage.
// Just start using it!
// Set the values. It stores the encrypted Uint8Array in the database
// against the key. If you want to immediately use the value, then
// you must use await while setting the value.
await securedStorage1.setItem("key1", "value1");
// Get the values. Remember to use await! As it's asynchronous.
const value1 = await securedStorage1.key1; // "value1"
```
### Setting Values

@@ -131,12 +192,41 @@

## Comparing `vault` with LocalStorage
## Comparing Vault with LocalStorage
| Feature | `vault` (IndexedDB) | LocalStorage |
| Feature | Vault | LocalStorage |
|--------------------------|--------------------------|------------------------|
| **API Complexity** | Simple, intuitive API | Simple, intuitive API |
| **Capacity** | Large (up to browser limit, often no less than 250MB) | Limited (5MB typical) |
| **Multiple Stores** | Supports multiple stores | Single store |
| **Encrypted Storage** | Supports built-in secured storage | No built-in encryption support |
| **Data Types** | Supports structured data, including objects and arrays | Only stores strings |
| **Performance** | Asynchronous, non-blocking | Synchronous, can block UI |
| **Transaction Support** | Complete transaction support for reliable data operations | None |
## Vault Roadmap
Since the vault is baesd on IndexDB database as storage provider, it is possible
to make it more powerful and useful. Here are some planned features and their
implementation status.
### Core Features (v1.0.*)
- [x] Extensible Vault class that has following qualities
- Provides a simple interface similar to local and session storages
- Supports indexers and dot notation for intuitive and ergonomic access
- Store large amount of data
- Perorm transactional in non-blocking asynchronous manner
- [x] Global default vault instance for ease of use
- [x] Support custom databases
### Advanced Features - Encryption (v1.1.*)
- [x] Support for secured vault storage
- [x] Support for dynamic password and salt for secured vault storage
### Other Advanced Features (Future)
- [ ] Support multiple update in a single transaction
- [ ] Automatic expiration of values based on TTL, Session Timeout and other
expiration policies
- [ ] Support for vault data backup and restore
## Contributing

@@ -143,0 +233,0 @@

@@ -1,138 +0,8 @@

// Constants for read and write operations
const RW = 'readwrite'
const R = 'readonly'
import Vault from './vault';
// The database instance
let db = null as IDBDatabase | null
// The name of the store within the database
const storeName = "vault"
/**
* The vault, an object provides an easy to
* The default vault instance.
*/
const vault = new Proxy({
/**
* Sets a value in the store.
* @param {string} key - The key to set.
* @param {any} value - The value to set.
* @returns {Promise<void>}
*/
async setItem(key: string, value: any): Promise<void> {
return $(RW, store => store.put({ key, value }));
},
const vault = new Vault();
/**
* Get a value from the store.
* @param {string} key - The key to get.
* @returns {Promise<any>} - The value associated with the key, or null if not found.
*/
async getItem(key: string): Promise<any> {
return $(R, store => store.get(key))
.then(result => result ? result.value : null);
},
/**
* Remove a key-value pair from the store.
* @param {string} key - The key to remove.
* @returns {Promise<void>}
*/
async removeItem(key: string): Promise<void> {
return $(RW, store => store.delete(key));
},
/**
* Clear all key-value pairs from the store.
* @returns {Promise<void>}
*/
async clear(): Promise<void> {
return $(RW, store => store.clear());
},
/**
* Get the number of key-value pairs in the store.
* @returns {Promise<number>} - The number of key-value pairs in the store.
*/
async length(): Promise<number> {
return $(R, store => store.count());
}
}, {
/**
* Proxy get handler.
* If the property exists on the target, return it.
* Otherwise, get the value from the store.
*/
get(target: any, key: string) {
return target[key] || target.getItem(key);
},
/**
* Proxy set handler.
* If the property exists on the target, set it.
* Otherwise, set the value in the store.
*/
set(target: any, key: string, value: any) {
target.setItem(key, value);
return true; // Return true immediately, indicating the set was "handled"
},
/**
* Proxy deleteProperty handler.
* Deletes the value from the store.
*/
deleteProperty(target, key) {
return target.removeItem(key);
}
});
/**
* Perform a database operation.
* @param {typeof vault} v - The vault instance.
* @param {string} operationType - The type of operation (read or write).
* @param {(store: IDBObjectStore) => IDBRequest} operation - The operation to perform.
* @returns {Promise<any>} - The result of the operation.
*/
async function $(
operationType: IDBTransactionMode,
operation: (store: IDBObjectStore) => IDBRequest
): Promise<any> {
db = db || await initDB(location.host, storeName); // Function to initialize the default database
return new Promise((resolve, reject) => {
const request = operation(
db!.transaction(storeName, operationType) // transaction
.objectStore(storeName) // store
);
request.onsuccess = () => resolve(operationType === R ? request.result : void 0)
request.onerror = (event) => reject(event);
});
}
/**
* Initialize the default database.
* @param {string} dbName - The name of the database.
* @param {string} storeName - The name of the store within the database.
* @returns {Promise<IDBDatabase>} - The initialized database.
*/
async function initDB(dbName:string, storeName: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onupgradeneeded = (event) => {
const db = request.result;
db.createObjectStore(storeName, { keyPath: 'key' }); // "vault" is an example store name
};
request.onsuccess = (event) => {
resolve(request.result);
};
request.onerror = (event) => {
reject(event);
};
});
}
// Export the vault object
export default vault
export default vault;

@@ -1,12 +0,8 @@

import vault from '../dist/index.js';
describe("A suite", () => {
it("contains a spec with an expectation", async () => {
vault.name = "John Doe2";
const value = await vault.getItem("name")
expect(value).toBe("John Doe2");
it("wip tests useful during development", async () => {
// TODO: Write tests
});
})
delete vault["name"];
expect(await vault.name).toBe(null);
});
})
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
"incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
"incremental": true,
/* Language and Environment */
"target": "ES2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["ES2018", "DOM"], /* Specify a set of bundled library declaration files that describe the target
"target": "ESNext",
"lib": ["ESNext", "DOM"],
/* Modules */
"module": "ESNext", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
"module": "ESNext",
"rootDir": "./src",
"moduleResolution": "node",
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./dist",
"removeComments": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
"strict": true,
},
"include": [
"src/**/*" // Include all files in the src directory
"src/**/*.ts"
],
"exclude": [
"node_modules", // Exclude the node_modules directory
"**/*.spec.ts" // Exclude test files
"dist"
]
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc