mirror of
https://github.com/cupcakearmy/occulto.git
synced 2025-12-11 14:54:59 +00:00
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 413592a9d0 | |||
| 1d9ed32438 | |||
| 77884250ae | |||
| 91605aa434 | |||
| dbc5bf97d9 | |||
| c2869e2746 | |||
| f587853432 | |||
| dffb5a7b13 | |||
| 07751ac477 | |||
| 877a0cd564 | |||
| a2f0255895 | |||
| f933df1908 | |||
| ef44dab3bc | |||
| 70093a4ba8 | |||
| 5fde1797a5 | |||
| f309294560 | |||
| 062d8df713 | |||
| 947c468cd4 | |||
| f5f796cc13 | |||
| de042d485c | |||
| 6d58350575 | |||
| be4e736ffd | |||
| d52f59f709 | |||
| 7fa0cbfe93 | |||
| d3b9e9bc42 | |||
| 0c08dcc678 | |||
| 7a6a24d631 | |||
| 75d702a5c7 | |||
| 4ee5666033 | |||
| c87fd3eaf5 |
18
.github/workflows/release.yaml
vendored
18
.github/workflows/release.yaml
vendored
@@ -1,9 +1,7 @@
|
||||
name: 'Publish to NPM'
|
||||
name: "Publish to NPM"
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
release:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -16,22 +14,22 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
node-version: 16
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 7
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Dependencies
|
||||
- name: Install Playwright
|
||||
run: pnpm exec playwright install-deps
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
|
||||
- name: Release
|
||||
run: pnpm publish --no-git-checks
|
||||
run: pnpm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
10
.github/workflows/test.yaml
vendored
10
.github/workflows/test.yaml
vendored
@@ -1,4 +1,4 @@
|
||||
name: 'Run Tests'
|
||||
name: "Run Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
@@ -17,16 +17,16 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
node-version: 16
|
||||
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 7
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Dependencies
|
||||
- name: Install Playwright
|
||||
run: pnpm exec playwright install-deps
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,4 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
docs
|
||||
__screenshots__
|
||||
|
||||
21
.karma.cjs
Normal file
21
.karma.cjs
Normal file
@@ -0,0 +1,21 @@
|
||||
module.exports = function (config) {
|
||||
config.set({
|
||||
frameworks: ['mocha'],
|
||||
|
||||
plugins: ['karma-mocha', '@endyjasmi/karma-playwright-launcher'],
|
||||
|
||||
basePath: '',
|
||||
files: [
|
||||
{ pattern: 'node_modules/chai/chai.js', type: 'module' },
|
||||
{ pattern: 'dist/**/*.js', type: 'module' },
|
||||
{ pattern: 'test/**/*.js', type: 'module' },
|
||||
],
|
||||
|
||||
browsers: ['ChromiumHeadless', 'FirefoxHeadless', 'WebKitHeadless'],
|
||||
|
||||
preprocessors: {},
|
||||
reporters: ['progress'],
|
||||
singleRun: false,
|
||||
concurrency: Infinity,
|
||||
})
|
||||
}
|
||||
4
.mocharc.yaml
Normal file
4
.mocharc.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
spec:
|
||||
- test/**/*.spec.js
|
||||
require:
|
||||
- test/hooks.js
|
||||
24
CHANGELOG.md
24
CHANGELOG.md
@@ -5,30 +5,6 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2.0.4]
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated dependencies.
|
||||
|
||||
## [2.0.3]
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated dependencies.
|
||||
|
||||
## [2.0.2]
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated dependencies.
|
||||
|
||||
## [2.0.1]
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated dependencies.
|
||||
|
||||
## [2.0.0]
|
||||
|
||||
### Added
|
||||
|
||||
38
README.md
38
README.md
@@ -33,10 +33,8 @@ npm i occulto
|
||||
```typescript
|
||||
import { RSA } from 'occulto'
|
||||
|
||||
const pair = await RSA.generateKeyPair(2 ** 11)
|
||||
const bytes = Bytes.encode(message)
|
||||
|
||||
const encrypted = await RSA.encrypt(bytes, pair.public)
|
||||
const pair = await RSA.generateKeyPair()
|
||||
const encrypted = await RSA.encrypt('some text', pair.public)
|
||||
const decrypted = await RSA.decrypt(encrypted, pair.private)
|
||||
```
|
||||
|
||||
@@ -44,29 +42,11 @@ const decrypted = await RSA.decrypt(encrypted, pair.private)
|
||||
|
||||
[Available Modes](https://occulto.pages.dev/enums/Modes)
|
||||
|
||||
There is an _easy_ API, that will take care of everything for you.
|
||||
```javascript
|
||||
import { Symmetric } from 'occulto'
|
||||
|
||||
```typescript
|
||||
import { AES } from 'occulto'
|
||||
|
||||
const password = 'foobar'
|
||||
const message = 'this is a secret'
|
||||
|
||||
const encrypted = await AES.encryptEasy(message, password)
|
||||
const decrypted = await AES.decryptEasy(encrypted, password)
|
||||
```
|
||||
|
||||
The low level API is also exposed for advanced usages.
|
||||
|
||||
```typescript
|
||||
import { AES } from 'occulto'
|
||||
|
||||
const message = 'this is a secret'
|
||||
const key = await AES.generateKey()
|
||||
const data = Bytes.encode(message)
|
||||
|
||||
const ciphertext = await AES.encrypt(data, key)
|
||||
const plaintext = await AES.decrypt(ciphertext, key)
|
||||
const encrypted = await Symmetric.encryptEasy('some string', 'myPass')
|
||||
const decrypted = await Symmetric.decryptEasy(encrypted, 'myPass')
|
||||
```
|
||||
|
||||
### [Hash](https://occulto.pages.dev/classes/Hash)
|
||||
@@ -74,7 +54,9 @@ const plaintext = await AES.decrypt(ciphertext, key)
|
||||
[Available hashes](https://occulto.pages.dev/enums/Hashes)
|
||||
|
||||
```typescript
|
||||
import { Hash, Hashes } from 'occulto'
|
||||
import { Hash } from 'occulto'
|
||||
|
||||
const hashed = await Hash.hash('Some value', Hashes.SHA_512)
|
||||
const hash = Hash.digest('something')
|
||||
|
||||
const h = Hash.digest('something', Hash.Hashes.MD5)
|
||||
```
|
||||
|
||||
65
package.json
65
package.json
@@ -1,50 +1,63 @@
|
||||
{
|
||||
"name": "occulto",
|
||||
"version": "2.1.0",
|
||||
"description": "encryption utility",
|
||||
"version": "2.0.0-rc.7",
|
||||
"license": "MIT",
|
||||
"description": "crypt utility",
|
||||
"keywords": [
|
||||
"isomorphic",
|
||||
"crypto",
|
||||
"aes",
|
||||
"rsa"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cupcakearmy/occulto"
|
||||
"engines": {
|
||||
"node": ">=16",
|
||||
"npm": "please-use-pnpm",
|
||||
"yarn": "please-use-pnpm",
|
||||
"pnpm": "7"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
"name": "Niccolo Borgioli",
|
||||
"email": "opensource@nicco.io",
|
||||
"url": "https://nicco.io"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"docs": "typedoc",
|
||||
"test": "vitest",
|
||||
"test:node": "mocha",
|
||||
"test:browser": "karma start .karma.cjs --single-run",
|
||||
"test": "run-s build test:*",
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf ./dist",
|
||||
"dev": "vitest",
|
||||
"prepublishOnly": "run-s clean test"
|
||||
"dev": "run-p -ln dev:*",
|
||||
"dev:build": "tsc -w",
|
||||
"dev:test:node": "mocha --parallel --watch",
|
||||
"dev:test:browser": "karma start .karma.cjs",
|
||||
"prepublishOnly": "run-s clean build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/strictest": "^2.0.5",
|
||||
"@types/node": "^22.13.0",
|
||||
"@vitest/browser": "^3.0.4",
|
||||
"@endyjasmi/karma-playwright-launcher": "^0.0.4",
|
||||
"@types/node": "^16.11.66",
|
||||
"chai": "^4.3.6",
|
||||
"karma": "^6.4.1",
|
||||
"karma-mocha": "^2.0.1",
|
||||
"mocha": "^10.1.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"playwright": "^1.50.1",
|
||||
"typedoc": "^0.27.6",
|
||||
"typedoc-material-theme": "^1.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.4"
|
||||
"playwright": "^1.27.1",
|
||||
"typedoc": "^0.23.17",
|
||||
"typescript": "^4.8.4"
|
||||
},
|
||||
"packageManager": "pnpm@9.15.4"
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cupcakearmy/occulto"
|
||||
},
|
||||
"author": {
|
||||
"name": "Niccolo Borgioli",
|
||||
"email": "opensource@nicco.io",
|
||||
"url": "https://nicco.io"
|
||||
}
|
||||
}
|
||||
|
||||
4020
pnpm-lock.yaml
generated
4020
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Base64, Bytes } from './encoding.js'
|
||||
import { Hashes } from './hash.js'
|
||||
@@ -14,7 +15,7 @@ export type KeyData = {
|
||||
name: 'PBKDF2'
|
||||
hash: Hashes
|
||||
iterations: number
|
||||
salt: ArrayBufferLike
|
||||
salt: TypedArray
|
||||
length: number
|
||||
}
|
||||
|
||||
@@ -28,18 +29,17 @@ export enum Modes {
|
||||
export class AES {
|
||||
static Modes = Modes
|
||||
|
||||
// delimiter with a character that is not allowed in base64 or hex
|
||||
private static delimiter = '--'
|
||||
private static delimiter = '--' // delimiter with a character that is not allowed in base64 or hex
|
||||
private static delimiterEasy = '---'
|
||||
|
||||
private static InvalidCiphertext = new Error('Invalid ciphertext')
|
||||
|
||||
private static async join(...args: ArrayBufferLike[]): Promise<string> {
|
||||
private static async join(...args: TypedArray[]): Promise<string> {
|
||||
const strings = await Promise.all(args.map(Base64.encode))
|
||||
return strings.join(AES.delimiter)
|
||||
}
|
||||
|
||||
private static async split(ciphertext: string): Promise<ArrayBufferLike[]> {
|
||||
private static async split(ciphertext: string): Promise<TypedArray[]> {
|
||||
const splitted = ciphertext.split(AES.delimiter)
|
||||
return Promise.all(splitted.map(Base64.decode))
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export class AES {
|
||||
* Derive a key from a password.
|
||||
* To be used if the password is not 128, 192 or 256 bits or human made, non generated keys.
|
||||
*/
|
||||
static async derive(key: string, options?: KeyData): Promise<[ArrayBufferLike, KeyData]> {
|
||||
static async derive(key: string, options?: KeyData): Promise<[TypedArray, KeyData]> {
|
||||
options ??= {
|
||||
name: 'PBKDF2',
|
||||
hash: Hashes.SHA_512,
|
||||
@@ -65,7 +65,7 @@ export class AES {
|
||||
return [new Uint8Array(bits), options]
|
||||
}
|
||||
|
||||
static async encrypt(data: ArrayBufferLike, key: ArrayBufferLike, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
static async encrypt(data: TypedArray, key: TypedArray, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
const c = await getCrypto()
|
||||
|
||||
let iv: Uint8Array
|
||||
@@ -87,7 +87,7 @@ export class AES {
|
||||
return AES.join(Bytes.encode(alg), iv, encryptedBuffer)
|
||||
}
|
||||
|
||||
static async decrypt(ciphertext: string, key: ArrayBufferLike): Promise<ArrayBufferLike> {
|
||||
static async decrypt(ciphertext: string, key: TypedArray): Promise<TypedArray> {
|
||||
const c = await getCrypto()
|
||||
|
||||
const [alg, iv, data] = await AES.split(ciphertext)
|
||||
@@ -106,7 +106,7 @@ export class AES {
|
||||
return new Uint8Array(decrypted)
|
||||
}
|
||||
|
||||
static async encryptEasy(data: string | ArrayBufferLike, key: string, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
static async encryptEasy(data: string | TypedArray, key: string, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
const dataBuffer = typeof data === 'string' ? Bytes.encode(data) : data
|
||||
const [keyDerived, options] = await AES.derive(key)
|
||||
|
||||
@@ -141,18 +141,4 @@ export class AES {
|
||||
const decrypted = await this.decrypt(data, keyDerived)
|
||||
return Bytes.decode(decrypted)
|
||||
}
|
||||
|
||||
static async generateKey(): Promise<ArrayBufferLike> {
|
||||
const c = await getCrypto()
|
||||
const key = await c.subtle.generateKey(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
length: 256,
|
||||
},
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
)
|
||||
const buffer = await c.subtle.exportKey('raw', key)
|
||||
return new Uint8Array(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { split } from '../utils/base.js'
|
||||
import { split, type TypedArray } from '../utils/base.js'
|
||||
|
||||
export class Base64 {
|
||||
private static prefix = 'data:application/octet-stream;base64,'
|
||||
|
||||
static encode(s: ArrayBufferLike): Promise<string> {
|
||||
static encode(s: TypedArray): Promise<string> {
|
||||
return split({
|
||||
async node() {
|
||||
return Buffer.from(s).toString('base64')
|
||||
@@ -22,7 +22,7 @@ export class Base64 {
|
||||
})
|
||||
}
|
||||
|
||||
static decode(s: string): Promise<ArrayBufferLike> {
|
||||
static decode(s: string): Promise<TypedArray> {
|
||||
return split({
|
||||
async node() {
|
||||
return Buffer.from(s, 'base64')
|
||||
@@ -38,7 +38,7 @@ export class Base64 {
|
||||
}
|
||||
|
||||
export class Hex {
|
||||
static encode(buffer: ArrayBufferLike): string {
|
||||
static encode(buffer: TypedArray): string {
|
||||
let s = ''
|
||||
for (const i of new Uint8Array(buffer)) {
|
||||
s += i.toString(16).padStart(2, '0')
|
||||
@@ -46,7 +46,7 @@ export class Hex {
|
||||
return s
|
||||
}
|
||||
|
||||
static decode(s: string): ArrayBufferLike {
|
||||
static decode(s: string): TypedArray {
|
||||
const size = s.length / 2
|
||||
const buffer = new Uint8Array(size)
|
||||
for (let i = 0; i < size; i++) {
|
||||
@@ -59,7 +59,7 @@ export class Hex {
|
||||
}
|
||||
|
||||
export class Bytes {
|
||||
static decode(data: ArrayBufferLike): string {
|
||||
static decode(data: TypedArray): string {
|
||||
return split({
|
||||
node() {
|
||||
return Buffer.from(data).toString('utf-8')
|
||||
@@ -70,7 +70,7 @@ export class Bytes {
|
||||
})
|
||||
}
|
||||
|
||||
static encode(data: string): ArrayBufferLike {
|
||||
static encode(data: string): TypedArray {
|
||||
return split({
|
||||
node() {
|
||||
return Buffer.from(data)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Bytes, Hex } from './encoding.js'
|
||||
|
||||
@@ -20,8 +21,8 @@ export enum Hashes {
|
||||
|
||||
export class Hash {
|
||||
static async hash(data: string, hash: Hashes): Promise<string>
|
||||
static async hash(data: ArrayBufferLike, hash: Hashes): Promise<ArrayBufferLike>
|
||||
static async hash(data: string | ArrayBufferLike, hash: Hashes): Promise<string | ArrayBufferLike> {
|
||||
static async hash(data: TypedArray, hash: Hashes): Promise<TypedArray>
|
||||
static async hash(data: string | TypedArray, hash: Hashes): Promise<string | TypedArray> {
|
||||
const isString = typeof data === 'string'
|
||||
const c = await getCrypto()
|
||||
const result = await c.subtle.digest(hash, isString ? Bytes.encode(data) : data)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
|
||||
export async function getRandomBytes(bytes: number): Promise<ArrayBufferLike> {
|
||||
export async function getRandomBytes(bytes: number): Promise<TypedArray> {
|
||||
if (bytes <= 0) throw new Error('Invalid number of bytes')
|
||||
|
||||
const buffer = new Uint8Array(bytes)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Base64 } from './encoding.js'
|
||||
|
||||
@@ -70,8 +71,7 @@ class Key {
|
||||
// @ts-ignore
|
||||
const mod = key?.algorithm?.modulusLength
|
||||
if (isNaN(mod)) throw Constants.error.invalidKey
|
||||
const maxBytes = mod / 8 - (2 * 512) / 8 - 2
|
||||
return maxBytes
|
||||
return mod / 8 - (2 * 512) / 8 - 2
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ export class RSA {
|
||||
}
|
||||
}
|
||||
|
||||
static async encrypt(data: ArrayBufferLike, key: string): Promise<ArrayBufferLike> {
|
||||
static async encrypt(data: TypedArray, key: string): Promise<TypedArray> {
|
||||
let keyObj: CryptoKey
|
||||
try {
|
||||
keyObj = await Key.decode(key)
|
||||
@@ -112,14 +112,14 @@ export class RSA {
|
||||
}
|
||||
|
||||
// Check if data is too large
|
||||
if (new Uint8Array(data).byteLength > Key.getMaxMessageSize(keyObj)) throw Constants.error.dataTooLong
|
||||
if (data.length > Key.getMaxMessageSize(keyObj)) throw Constants.error.dataTooLong
|
||||
|
||||
const c = await getCrypto()
|
||||
const encrypted = await c.subtle.encrypt({ name: Constants.name }, keyObj, data)
|
||||
return new Uint8Array(encrypted)
|
||||
}
|
||||
|
||||
static async decrypt(data: ArrayBufferLike, key: string): Promise<ArrayBufferLike> {
|
||||
static async decrypt(data: TypedArray, key: string): Promise<TypedArray> {
|
||||
let keyObj: CryptoKey
|
||||
try {
|
||||
keyObj = await Key.decode(key)
|
||||
|
||||
@@ -3,3 +3,4 @@ export * from './crypto/encoding.js'
|
||||
export * from './crypto/hash.js'
|
||||
export * from './crypto/random.js'
|
||||
export * from './crypto/rsa.js'
|
||||
export * from './utils/base.js'
|
||||
|
||||
@@ -8,6 +8,17 @@ export const isBrowser = typeof window !== 'undefined'
|
||||
*/
|
||||
export type PromiseOrValue<T> = T | Promise<T>
|
||||
|
||||
export type TypedArray =
|
||||
| Int8Array
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Int16Array
|
||||
| Uint16Array
|
||||
| Int32Array
|
||||
| Uint32Array
|
||||
| BigInt64Array
|
||||
| BigUint64Array
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`Random > Should throw error on empty array 1`] = `[Error: Invalid number of bytes]`;
|
||||
|
||||
exports[`Random > Should throw error on negative bytes 1`] = `[Error: Invalid number of bytes]`;
|
||||
@@ -1,5 +0,0 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`RSA > Generate keys > Should not be able to generate a key below 2048bit 1`] = `[Error: bit sizes below 2048 are considered insecure.]`;
|
||||
|
||||
exports[`RSA > Generate keys > Should not be able to generate a key below 2048bit 2`] = `[Error: bit sizes below 2048 are considered insecure.]`;
|
||||
28
test/aes.spec.js
Normal file
28
test/aes.spec.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import { AES, Bytes, Hashes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
describe('AES', () => {
|
||||
it('Basic API', async () => {
|
||||
const message = Precomputed.Crypto.Messages.nietzscheIpsum
|
||||
const data = Bytes.encode(message)
|
||||
const [key] = await AES.derive('foo', {
|
||||
name: 'PBKDF2',
|
||||
hash: Hashes.SHA_512,
|
||||
iterations: 1000,
|
||||
length: 256,
|
||||
salt: Hex.decode(Precomputed.Crypto.Bytes[16]),
|
||||
})
|
||||
const ciphertext = await AES.encrypt(data, key, AES.Modes.GCM)
|
||||
const plaintext = await AES.decrypt(ciphertext, key)
|
||||
chai.expect(data).to.be.deep.equal(plaintext)
|
||||
chai.expect(message).to.be.equal(Bytes.decode(plaintext))
|
||||
})
|
||||
|
||||
it('Easy API', async () => {
|
||||
const message = Precomputed.Crypto.Messages.nietzscheIpsum
|
||||
const password = 'foobar'
|
||||
const encrypted = await AES.encryptEasy(message, password)
|
||||
const decrypted = await AES.decryptEasy(encrypted, password)
|
||||
chai.expect(message).to.be.equal(decrypted)
|
||||
})
|
||||
})
|
||||
@@ -1,44 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AES, Bytes, Hashes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
describe('AES', () => {
|
||||
for (const message of Object.values(Precomputed.Crypto.Messages)) {
|
||||
describe(`Message: ${message.slice(0, 8)}...`, () => {
|
||||
describe('Basic API', () => {
|
||||
for (const keySize of [128, 256]) {
|
||||
it('Key Size: ' + keySize, async () => {
|
||||
const data = Bytes.encode(message)
|
||||
const [key] = await AES.derive('foo', {
|
||||
name: 'PBKDF2',
|
||||
hash: Hashes.SHA_512,
|
||||
iterations: 1000,
|
||||
length: keySize,
|
||||
salt: Hex.decode(Precomputed.Crypto.Bytes[16]),
|
||||
})
|
||||
const ciphertext = await AES.encrypt(data, key, AES.Modes.AES_GCM)
|
||||
const plaintext = await AES.decrypt(ciphertext, key)
|
||||
expect(data.buffer).toEqual(plaintext.buffer)
|
||||
expect(message).toEqual(Bytes.decode(plaintext))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('Generated Key', async () => {
|
||||
const key = await AES.generateKey()
|
||||
const data = Bytes.encode(message)
|
||||
const ciphertext = await AES.encrypt(data, key)
|
||||
const plaintext = await AES.decrypt(ciphertext, key)
|
||||
expect(data.buffer).toEqual(plaintext.buffer)
|
||||
expect(message).toEqual(Bytes.decode(plaintext))
|
||||
})
|
||||
|
||||
it('Easy API', async () => {
|
||||
const password = 'foobar'
|
||||
const encrypted = await AES.encryptEasy(message, password)
|
||||
const decrypted = await AES.decryptEasy(encrypted, password)
|
||||
expect(message).toEqual(decrypted)
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
16
test/encoding.spec.js
Normal file
16
test/encoding.spec.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Base64, Bytes } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
describe('Encoding', () => {
|
||||
describe('Base64', () => {
|
||||
for (const [input, output] of Object.entries(Precomputed.Encoding.Base64)) {
|
||||
const buffer = Bytes.encode(input)
|
||||
it(`Should encode ${input} to ${output}`, async () => {
|
||||
chai.expect(await Base64.encode(buffer)).to.equal(output)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
chai.expect(await Base64.decode(output)).to.deep.equal(buffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Base64, Bytes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
describe('Encoding', () => {
|
||||
describe('Bytes', () => {
|
||||
for (const [input, output] of Object.entries(Precomputed.Encoding.Bytes)) {
|
||||
it(`Should encode ${input} to ${output}`, async () => {
|
||||
expect(Bytes.encode(input).buffer).toEqual(output.buffer)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
expect(Bytes.decode(output)).toEqual(input)
|
||||
})
|
||||
}
|
||||
})
|
||||
describe('Hex', () => {
|
||||
for (const [input, output] of Object.entries(Precomputed.Encoding.Hex)) {
|
||||
const buffer = Bytes.encode(input)
|
||||
it(`Should encode ${input} to ${output}`, async () => {
|
||||
expect(Hex.encode(buffer)).toEqual(output)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
expect(Hex.decode(output).buffer).toEqual(buffer.buffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
describe('Base64', () => {
|
||||
for (const [input, output] of Object.entries(Precomputed.Encoding.Base64)) {
|
||||
const buffer = Bytes.encode(input)
|
||||
it(`Should encode ${input} to ${output}`, async () => {
|
||||
expect(await Base64.encode(buffer)).toEqual(output)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
expect((await Base64.decode(output)).buffer).toEqual(buffer.buffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,3 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Bytes, Hash, Hashes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
@@ -7,18 +6,16 @@ describe('Hash', () => {
|
||||
describe(type, () => {
|
||||
const values = Precomputed.Hash[type]
|
||||
for (const [input, output] of Object.entries(values)) {
|
||||
if (typeof output !== 'string') throw new Error('Bad test data')
|
||||
|
||||
it(`Should hash "${input}" to "${output.slice(0, 8)}..."`, async () => {
|
||||
const hashed = await Hash.hash(input, Hashes[type])
|
||||
expect(hashed).toEqual(output)
|
||||
chai.expect(hashed).to.equal(output)
|
||||
})
|
||||
|
||||
it(`Should hash "${input}" to "${output.slice(0, 8)}..." as buffer`, async () => {
|
||||
const outputBuffer = Hex.decode(output)
|
||||
const inputBuffer = Bytes.encode(input)
|
||||
const hashed = await Hash.hash(inputBuffer, Hashes[type])
|
||||
expect(hashed).toEqual(outputBuffer)
|
||||
chai.expect(hashed).to.deep.equal(outputBuffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
12
test/hooks.js
Normal file
12
test/hooks.js
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Hook for mocha tests in node
|
||||
* Initialises chai and chai-as-promised as global variables
|
||||
*/
|
||||
|
||||
export const mochaHooks = {
|
||||
async beforeEach() {
|
||||
if (typeof chai === 'undefined') {
|
||||
global.chai = await import('chai')
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getRandomBytes } from '../dist/index.js'
|
||||
import { Promises } from './utils.js'
|
||||
|
||||
describe('Random', () => {
|
||||
it('Should be able to create random values', async () => {
|
||||
const buffer = await getRandomBytes(8)
|
||||
expect(buffer).instanceOf(Uint8Array)
|
||||
expect(buffer.byteLength).toEqual(8)
|
||||
chai.expect(buffer).to.be.instanceOf(Uint8Array)
|
||||
chai.expect(buffer.byteLength).to.equal(8)
|
||||
})
|
||||
|
||||
it('Should throw error on empty array', async () => {
|
||||
await expect(() => getRandomBytes(0)).rejects.toThrowErrorMatchingSnapshot()
|
||||
await Promises.reject(() => getRandomBytes(0))
|
||||
})
|
||||
|
||||
it('Should throw error on negative bytes', async () => {
|
||||
await expect(() => getRandomBytes(-1)).rejects.toThrowErrorMatchingSnapshot()
|
||||
await Promises.reject(() => getRandomBytes(-1))
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe } from 'vitest'
|
||||
import { Bytes, RSA } from '../dist/index.js'
|
||||
import { Promises } from './utils.js'
|
||||
import { Precomputed } from './values.js'
|
||||
import { it } from 'vitest'
|
||||
import { expect } from 'vitest'
|
||||
|
||||
describe('RSA', () => {
|
||||
describe('Generate keys', function () {
|
||||
this.timeout(5_000)
|
||||
|
||||
it('Should be able to generate a keypair', async () => {
|
||||
await RSA.generateKeyPair()
|
||||
})
|
||||
@@ -16,10 +16,10 @@ describe('RSA', () => {
|
||||
await RSA.generateKeyPair(4096)
|
||||
})
|
||||
it('Should not be able to generate a key below 2048bit', async () => {
|
||||
await expect(() => RSA.generateKeyPair(1024)).rejects.toThrowErrorMatchingSnapshot()
|
||||
await Promises.reject(() => RSA.generateKeyPair(1024))
|
||||
})
|
||||
it('Should not be able to generate a key below 2048bit', async () => {
|
||||
await expect(() => RSA.generateKeyPair(-1)).rejects.toThrowErrorMatchingSnapshot()
|
||||
await Promises.reject(() => RSA.generateKeyPair(-1))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -30,9 +30,10 @@ describe('RSA', () => {
|
||||
const bytes = Bytes.encode(message)
|
||||
try {
|
||||
const encrypted = await RSA.encrypt(bytes, pair.public)
|
||||
chai.expect.fail('Should have thrown error')
|
||||
const decrypted = await RSA.decrypt(encrypted, pair.private)
|
||||
expect(decrypted).toEqual(bytes)
|
||||
expect(message).toEqual(Bytes.decode(decrypted))
|
||||
chai.expect(decrypted).to.be.deep.equal(bytes)
|
||||
chai.expect(message).to.be.equal(Bytes.decode(decrypted))
|
||||
} catch {}
|
||||
})
|
||||
}
|
||||
8
test/utils.js
Normal file
8
test/utils.js
Normal file
@@ -0,0 +1,8 @@
|
||||
export class Promises {
|
||||
static async reject(fn) {
|
||||
try {
|
||||
await fn()
|
||||
chai.expect.fail('Should have thrown error')
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,6 @@ export const Precomputed = {
|
||||
test: 'dGVzdA==',
|
||||
'hello world': 'aGVsbG8gd29ybGQ=',
|
||||
},
|
||||
Hex: {
|
||||
test: '74657374',
|
||||
occulto: '6f6363756c746f',
|
||||
'hello world': '68656c6c6f20776f726c64',
|
||||
},
|
||||
Bytes: {
|
||||
test: new Uint8Array([0x74, 0x65, 0x73, 0x74]),
|
||||
occulto: new Uint8Array([0x6f, 0x63, 0x63, 0x75, 0x6c, 0x74, 0x6f]),
|
||||
'entropy is king': new Uint8Array([
|
||||
0x65, 0x6e, 0x74, 0x72, 0x6f, 0x70, 0x79, 0x20, 0x69, 0x73, 0x20, 0x6b, 0x69, 0x6e, 0x67,
|
||||
]),
|
||||
},
|
||||
},
|
||||
Hash: {
|
||||
SHA_1: {
|
||||
@@ -51,10 +39,8 @@ export const Precomputed = {
|
||||
},
|
||||
Messages: {
|
||||
test: 'test',
|
||||
occulto: 'occulto',
|
||||
weird: 'Some 🃏 weird 🃏 text',
|
||||
nietzscheIpsum:
|
||||
'Marvelous intentions joy deceptions overcome sexuality spirit against. Selfish of marvelous play dead war snare eternal-return ultimate. Reason aversion suicide.',
|
||||
},
|
||||
},
|
||||
} as const
|
||||
}
|
||||
@@ -1,16 +1,104 @@
|
||||
{
|
||||
"extends": ["@tsconfig/strictest"],
|
||||
"compilerOptions": {
|
||||
"target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
||||
/* 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. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "ES2015" /* Specify what module code is generated. */,
|
||||
"rootDir": "./src" /* Specify the root folder within your source files. */,
|
||||
"moduleResolution": "node" /* 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. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* 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. */,
|
||||
// "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. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "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. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "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. */,
|
||||
"isolatedModules": false
|
||||
// "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": false /* Disable error reporting for unused labels. */,
|
||||
"allowUnreachableCode": false /* 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. */
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
|
||||
@@ -5,9 +5,6 @@
|
||||
"name": "Occulto",
|
||||
"includeVersion": true,
|
||||
|
||||
"plugin": ["typedoc-material-theme"],
|
||||
"themeColor": "#cb9820",
|
||||
|
||||
"excludeInternal": true,
|
||||
"excludePrivate": true
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
export default defineConfig({
|
||||
test: {
|
||||
browser: {
|
||||
provider: 'playwright',
|
||||
enabled: true,
|
||||
headless: true,
|
||||
instances: [{ browser: 'firefox' }, { browser: 'webkit' }, { browser: 'chromium' }],
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineWorkspace } from 'vitest/config'
|
||||
|
||||
export default defineWorkspace([
|
||||
{
|
||||
test: {
|
||||
name: 'node',
|
||||
environment: 'node',
|
||||
},
|
||||
},
|
||||
{
|
||||
test: {
|
||||
name: 'browser',
|
||||
browser: {
|
||||
provider: 'playwright',
|
||||
enabled: true,
|
||||
headless: true,
|
||||
instances: [{ browser: 'firefox' }, { browser: 'webkit' }, { browser: 'chromium' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
Reference in New Issue
Block a user