mirror of
https://github.com/cupcakearmy/occulto.git
synced 2025-12-09 23:35:01 +00:00
Compare commits
15 Commits
f4503bbf2b
...
2.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 534cf8c800 | |||
| 5b4a043f6c | |||
| f87c1aef53 | |||
| 91693e55e1 | |||
| 4c61c067e6 | |||
| 48138b673b | |||
| e5910f2abc | |||
| c485d5c715 | |||
| 72a31ab3e2 | |||
| 629e3af60d | |||
| bfc4ca3c48 | |||
| 0798993f84 | |||
| bac19fa91d | |||
|
|
6bbc5979ae | ||
|
|
be04f9c546 |
4
.github/workflows/release.yaml
vendored
4
.github/workflows/release.yaml
vendored
@@ -24,8 +24,10 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright
|
||||
- name: Install Playwright Dependencies
|
||||
run: pnpm exec playwright install-deps
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
|
||||
|
||||
4
.github/workflows/test.yaml
vendored
4
.github/workflows/test.yaml
vendored
@@ -24,7 +24,9 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright
|
||||
- name: Install Playwright Dependencies
|
||||
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,3 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
docs
|
||||
__screenshots__
|
||||
|
||||
21
.karma.cjs
21
.karma.cjs
@@ -1,21 +0,0 @@
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
spec:
|
||||
- test/**/*.spec.js
|
||||
require:
|
||||
- test/hooks.js
|
||||
12
CHANGELOG.md
12
CHANGELOG.md
@@ -5,6 +5,18 @@ 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
|
||||
|
||||
66
package.json
66
package.json
@@ -1,64 +1,50 @@
|
||||
{
|
||||
"name": "occulto",
|
||||
"version": "2.0.2",
|
||||
"packageManager": "pnpm@8.4.0",
|
||||
"license": "MIT",
|
||||
"description": "crypt utility",
|
||||
"version": "2.1.0",
|
||||
"description": "encryption utility",
|
||||
"keywords": [
|
||||
"isomorphic",
|
||||
"crypto",
|
||||
"aes",
|
||||
"rsa"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16",
|
||||
"npm": "please-use-pnpm",
|
||||
"yarn": "please-use-pnpm",
|
||||
"pnpm": ">=8"
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cupcakearmy/occulto"
|
||||
},
|
||||
"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:node": "mocha",
|
||||
"test:browser": "karma start .karma.cjs --single-run",
|
||||
"test": "run-s build test:*",
|
||||
"test": "vitest",
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf ./dist",
|
||||
"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"
|
||||
"dev": "vitest",
|
||||
"prepublishOnly": "run-s clean test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@endyjasmi/karma-playwright-launcher": "^0.0.4",
|
||||
"@types/node": "^20.1.5",
|
||||
"chai": "^4.3.7",
|
||||
"karma": "^6.4.2",
|
||||
"karma-mocha": "^2.0.1",
|
||||
"mocha": "^10.2.0",
|
||||
"@tsconfig/strictest": "^2.0.5",
|
||||
"@types/node": "^22.13.0",
|
||||
"@vitest/browser": "^3.0.4",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"playwright": "^1.33.0",
|
||||
"typedoc": "^0.24.7",
|
||||
"typescript": "^5.0.4"
|
||||
"playwright": "^1.50.1",
|
||||
"typedoc": "^0.27.6",
|
||||
"typedoc-material-theme": "^1.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.4"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cupcakearmy/occulto"
|
||||
},
|
||||
"author": {
|
||||
"name": "Niccolo Borgioli",
|
||||
"email": "opensource@nicco.io",
|
||||
"url": "https://nicco.io"
|
||||
}
|
||||
"packageManager": "pnpm@9.15.4"
|
||||
}
|
||||
|
||||
4128
pnpm-lock.yaml
generated
4128
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,3 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Base64, Bytes } from './encoding.js'
|
||||
import { Hashes } from './hash.js'
|
||||
@@ -15,7 +14,7 @@ export type KeyData = {
|
||||
name: 'PBKDF2'
|
||||
hash: Hashes
|
||||
iterations: number
|
||||
salt: TypedArray
|
||||
salt: ArrayBufferLike
|
||||
length: number
|
||||
}
|
||||
|
||||
@@ -35,12 +34,12 @@ export class AES {
|
||||
|
||||
private static InvalidCiphertext = new Error('Invalid ciphertext')
|
||||
|
||||
private static async join(...args: TypedArray[]): Promise<string> {
|
||||
private static async join(...args: ArrayBufferLike[]): Promise<string> {
|
||||
const strings = await Promise.all(args.map(Base64.encode))
|
||||
return strings.join(AES.delimiter)
|
||||
}
|
||||
|
||||
private static async split(ciphertext: string): Promise<TypedArray[]> {
|
||||
private static async split(ciphertext: string): Promise<ArrayBufferLike[]> {
|
||||
const splitted = ciphertext.split(AES.delimiter)
|
||||
return Promise.all(splitted.map(Base64.decode))
|
||||
}
|
||||
@@ -49,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<[TypedArray, KeyData]> {
|
||||
static async derive(key: string, options?: KeyData): Promise<[ArrayBufferLike, KeyData]> {
|
||||
options ??= {
|
||||
name: 'PBKDF2',
|
||||
hash: Hashes.SHA_512,
|
||||
@@ -66,7 +65,7 @@ export class AES {
|
||||
return [new Uint8Array(bits), options]
|
||||
}
|
||||
|
||||
static async encrypt(data: TypedArray, key: TypedArray, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
static async encrypt(data: ArrayBufferLike, key: ArrayBufferLike, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
const c = await getCrypto()
|
||||
|
||||
let iv: Uint8Array
|
||||
@@ -88,7 +87,7 @@ export class AES {
|
||||
return AES.join(Bytes.encode(alg), iv, encryptedBuffer)
|
||||
}
|
||||
|
||||
static async decrypt(ciphertext: string, key: TypedArray): Promise<TypedArray> {
|
||||
static async decrypt(ciphertext: string, key: ArrayBufferLike): Promise<ArrayBufferLike> {
|
||||
const c = await getCrypto()
|
||||
|
||||
const [alg, iv, data] = await AES.split(ciphertext)
|
||||
@@ -107,7 +106,7 @@ export class AES {
|
||||
return new Uint8Array(decrypted)
|
||||
}
|
||||
|
||||
static async encryptEasy(data: string | TypedArray, key: string, mode: Modes = Modes.AES_GCM): Promise<string> {
|
||||
static async encryptEasy(data: string | ArrayBufferLike, 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)
|
||||
|
||||
@@ -143,7 +142,7 @@ export class AES {
|
||||
return Bytes.decode(decrypted)
|
||||
}
|
||||
|
||||
static async generateKey(): Promise<TypedArray> {
|
||||
static async generateKey(): Promise<ArrayBufferLike> {
|
||||
const c = await getCrypto()
|
||||
const key = await c.subtle.generateKey(
|
||||
{
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { split, type TypedArray } from '../utils/base.js'
|
||||
import { split } from '../utils/base.js'
|
||||
|
||||
export class Base64 {
|
||||
private static prefix = 'data:application/octet-stream;base64,'
|
||||
|
||||
static encode(s: TypedArray): Promise<string> {
|
||||
static encode(s: ArrayBufferLike): Promise<string> {
|
||||
return split({
|
||||
async node() {
|
||||
return Buffer.from(s).toString('base64')
|
||||
@@ -22,7 +22,7 @@ export class Base64 {
|
||||
})
|
||||
}
|
||||
|
||||
static decode(s: string): Promise<TypedArray> {
|
||||
static decode(s: string): Promise<ArrayBufferLike> {
|
||||
return split({
|
||||
async node() {
|
||||
return Buffer.from(s, 'base64')
|
||||
@@ -38,7 +38,7 @@ export class Base64 {
|
||||
}
|
||||
|
||||
export class Hex {
|
||||
static encode(buffer: TypedArray): string {
|
||||
static encode(buffer: ArrayBufferLike): 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): TypedArray {
|
||||
static decode(s: string): ArrayBufferLike {
|
||||
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: TypedArray): string {
|
||||
static decode(data: ArrayBufferLike): string {
|
||||
return split({
|
||||
node() {
|
||||
return Buffer.from(data).toString('utf-8')
|
||||
@@ -70,7 +70,7 @@ export class Bytes {
|
||||
})
|
||||
}
|
||||
|
||||
static encode(data: string): TypedArray {
|
||||
static encode(data: string): ArrayBufferLike {
|
||||
return split({
|
||||
node() {
|
||||
return Buffer.from(data)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Bytes, Hex } from './encoding.js'
|
||||
|
||||
@@ -21,8 +20,8 @@ export enum Hashes {
|
||||
|
||||
export class Hash {
|
||||
static async hash(data: string, hash: Hashes): Promise<string>
|
||||
static async hash(data: TypedArray, hash: Hashes): Promise<TypedArray>
|
||||
static async hash(data: string | TypedArray, hash: Hashes): Promise<string | TypedArray> {
|
||||
static async hash(data: ArrayBufferLike, hash: Hashes): Promise<ArrayBufferLike>
|
||||
static async hash(data: string | ArrayBufferLike, hash: Hashes): Promise<string | ArrayBufferLike> {
|
||||
const isString = typeof data === 'string'
|
||||
const c = await getCrypto()
|
||||
const result = await c.subtle.digest(hash, isString ? Bytes.encode(data) : data)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { type TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
|
||||
export async function getRandomBytes(bytes: number): Promise<TypedArray> {
|
||||
export async function getRandomBytes(bytes: number): Promise<ArrayBufferLike> {
|
||||
if (bytes <= 0) throw new Error('Invalid number of bytes')
|
||||
|
||||
const buffer = new Uint8Array(bytes)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { TypedArray } from '../utils/base.js'
|
||||
import { getCrypto } from './crypto.js'
|
||||
import { Base64 } from './encoding.js'
|
||||
|
||||
@@ -71,7 +70,8 @@ class Key {
|
||||
// @ts-ignore
|
||||
const mod = key?.algorithm?.modulusLength
|
||||
if (isNaN(mod)) throw Constants.error.invalidKey
|
||||
return mod / 8 - (2 * 512) / 8 - 2
|
||||
const maxBytes = mod / 8 - (2 * 512) / 8 - 2
|
||||
return maxBytes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ export class RSA {
|
||||
}
|
||||
}
|
||||
|
||||
static async encrypt(data: TypedArray, key: string): Promise<TypedArray> {
|
||||
static async encrypt(data: ArrayBufferLike, key: string): Promise<ArrayBufferLike> {
|
||||
let keyObj: CryptoKey
|
||||
try {
|
||||
keyObj = await Key.decode(key)
|
||||
@@ -112,14 +112,14 @@ export class RSA {
|
||||
}
|
||||
|
||||
// Check if data is too large
|
||||
if (data.length > Key.getMaxMessageSize(keyObj)) throw Constants.error.dataTooLong
|
||||
if (new Uint8Array(data).byteLength > 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: TypedArray, key: string): Promise<TypedArray> {
|
||||
static async decrypt(data: ArrayBufferLike, key: string): Promise<ArrayBufferLike> {
|
||||
let keyObj: CryptoKey
|
||||
try {
|
||||
keyObj = await Key.decode(key)
|
||||
|
||||
@@ -3,4 +3,3 @@ export * from './crypto/encoding.js'
|
||||
export * from './crypto/hash.js'
|
||||
export * from './crypto/random.js'
|
||||
export * from './crypto/rsa.js'
|
||||
export { TypedArray } from './utils/base.js'
|
||||
|
||||
@@ -8,17 +8,6 @@ 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
|
||||
*/
|
||||
|
||||
5
test/__snapshots__/random.spec.ts.snap
Normal file
5
test/__snapshots__/random.spec.ts.snap
Normal file
@@ -0,0 +1,5 @@
|
||||
// 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]`;
|
||||
5
test/__snapshots__/rsa.spec.ts.snap
Normal file
5
test/__snapshots__/rsa.spec.ts.snap
Normal file
@@ -0,0 +1,5 @@
|
||||
// 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.]`;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AES, Bytes, Hashes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
@@ -15,10 +16,10 @@ describe('AES', () => {
|
||||
length: keySize,
|
||||
salt: Hex.decode(Precomputed.Crypto.Bytes[16]),
|
||||
})
|
||||
const ciphertext = await AES.encrypt(data, key, AES.Modes.GCM)
|
||||
const ciphertext = await AES.encrypt(data, key, AES.Modes.AES_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))
|
||||
expect(data.buffer).toEqual(plaintext.buffer)
|
||||
expect(message).toEqual(Bytes.decode(plaintext))
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -28,15 +29,15 @@ describe('AES', () => {
|
||||
const data = Bytes.encode(message)
|
||||
const ciphertext = await AES.encrypt(data, key)
|
||||
const plaintext = await AES.decrypt(ciphertext, key)
|
||||
chai.expect(data).to.be.deep.equal(plaintext)
|
||||
chai.expect(message).to.be.equal(Bytes.decode(plaintext))
|
||||
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)
|
||||
chai.expect(message).to.be.equal(decrypted)
|
||||
expect(message).toEqual(decrypted)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Base64, Bytes, Hex } from '../dist/index.js'
|
||||
import { compareArrayLike } from './utils.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 () => {
|
||||
compareArrayLike(Bytes.encode(input), output)
|
||||
expect(Bytes.encode(input).buffer).toEqual(output.buffer)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
compareArrayLike(await Bytes.decode(output), input)
|
||||
expect(Bytes.decode(output)).toEqual(input)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -17,10 +17,10 @@ describe('Encoding', () => {
|
||||
for (const [input, output] of Object.entries(Precomputed.Encoding.Hex)) {
|
||||
const buffer = Bytes.encode(input)
|
||||
it(`Should encode ${input} to ${output}`, async () => {
|
||||
chai.expect(await Hex.encode(buffer)).to.equal(output)
|
||||
expect(Hex.encode(buffer)).toEqual(output)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
chai.expect(await Hex.decode(output)).to.deep.equal(buffer)
|
||||
expect(Hex.decode(output).buffer).toEqual(buffer.buffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -28,10 +28,10 @@ describe('Encoding', () => {
|
||||
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)
|
||||
expect(await Base64.encode(buffer)).toEqual(output)
|
||||
})
|
||||
it(`Should decode ${output} to ${input}`, async () => {
|
||||
chai.expect(await Base64.decode(output)).to.deep.equal(buffer)
|
||||
expect((await Base64.decode(output)).buffer).toEqual(buffer.buffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Bytes, Hash, Hashes, Hex } from '../dist/index.js'
|
||||
import { Precomputed } from './values.js'
|
||||
|
||||
@@ -6,16 +7,18 @@ 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])
|
||||
chai.expect(hashed).to.equal(output)
|
||||
expect(hashed).toEqual(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])
|
||||
chai.expect(hashed).to.deep.equal(outputBuffer)
|
||||
expect(hashed).toEqual(outputBuffer)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
/**
|
||||
* 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)
|
||||
chai.expect(buffer).to.be.instanceOf(Uint8Array)
|
||||
chai.expect(buffer.byteLength).to.equal(8)
|
||||
expect(buffer).instanceOf(Uint8Array)
|
||||
expect(buffer.byteLength).toEqual(8)
|
||||
})
|
||||
|
||||
it('Should throw error on empty array', async () => {
|
||||
await Promises.reject(() => getRandomBytes(0))
|
||||
await expect(() => getRandomBytes(0)).rejects.toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
|
||||
it('Should throw error on negative bytes', async () => {
|
||||
await Promises.reject(() => getRandomBytes(-1))
|
||||
await expect(() => getRandomBytes(-1)).rejects.toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
})
|
||||
@@ -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(10_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 Promises.reject(() => RSA.generateKeyPair(1024))
|
||||
await expect(() => RSA.generateKeyPair(1024)).rejects.toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
it('Should not be able to generate a key below 2048bit', async () => {
|
||||
await Promises.reject(() => RSA.generateKeyPair(-1))
|
||||
await expect(() => RSA.generateKeyPair(-1)).rejects.toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -30,10 +30,9 @@ 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)
|
||||
chai.expect(decrypted).to.be.deep.equal(bytes)
|
||||
chai.expect(message).to.be.equal(Bytes.decode(decrypted))
|
||||
expect(decrypted).toEqual(bytes)
|
||||
expect(message).toEqual(Bytes.decode(decrypted))
|
||||
} catch {}
|
||||
})
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
export class Promises {
|
||||
static async reject(fn) {
|
||||
try {
|
||||
await fn()
|
||||
chai.expect.fail('Should have thrown error')
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
export function compareArrayLike(a, b) {
|
||||
chai.expect(a.length).to.equal(b.length)
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
chai.expect(a[i]).to.equal(b[i])
|
||||
}
|
||||
}
|
||||
@@ -57,4 +57,4 @@ export const Precomputed = {
|
||||
'Marvelous intentions joy deceptions overcome sexuality spirit against. Selfish of marvelous play dead war snare eternal-return ultimate. Reason aversion suicide.',
|
||||
},
|
||||
},
|
||||
}
|
||||
} as const
|
||||
@@ -1,104 +1,16 @@
|
||||
{
|
||||
"extends": ["@tsconfig/strictest"],
|
||||
"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. */
|
||||
|
||||
/* 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 */
|
||||
"target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
||||
"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. */,
|
||||
// "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. */
|
||||
"isolatedModules": false
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
"name": "Occulto",
|
||||
"includeVersion": true,
|
||||
|
||||
"plugin": ["typedoc-material-theme"],
|
||||
"themeColor": "#cb9820",
|
||||
|
||||
"excludeInternal": true,
|
||||
"excludePrivate": true
|
||||
}
|
||||
|
||||
11
vitest.config.ts.old
Normal file
11
vitest.config.ts.old
Normal file
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
export default defineConfig({
|
||||
test: {
|
||||
browser: {
|
||||
provider: 'playwright',
|
||||
enabled: true,
|
||||
headless: true,
|
||||
instances: [{ browser: 'firefox' }, { browser: 'webkit' }, { browser: 'chromium' }],
|
||||
},
|
||||
},
|
||||
})
|
||||
21
vitest.workspace.ts
Normal file
21
vitest.workspace.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
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