treadwheel 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/core/cipher.d.ts +2 -2
- package/dist/core/cipher.js +7 -6
- package/dist/core/defaults.js +1 -0
- package/dist/core/index.js +1 -1
- package/dist/core/io.d.ts +2 -2
- package/dist/core/io.js +21 -8
- package/dist/core/puzzle.d.ts +1 -1
- package/dist/core/puzzle.js +7 -3
- package/dist/core/types.d.ts +13 -1
- package/dist/node/cli.js +11 -2
- package/dist/treadwheel-widget.min.js +1 -1
- package/dist/treadwheel-widget.min.js.map +1 -1
- package/dist/treadwheel.min.js +1 -1
- package/dist/treadwheel.min.js.map +1 -1
- package/package.json +10 -10
package/README.md
CHANGED
|
@@ -24,6 +24,8 @@ making mass collection more expensive and potentially less attractive.
|
|
|
24
24
|
|
|
25
25
|
- A secure context (HTTPS or localhost) for the Web Crypto API.
|
|
26
26
|
- ES2020 support, including BigInt.
|
|
27
|
+
- ESM Web Worker support (not required if you use the provided CDN bundle or
|
|
28
|
+
bundle the worker as an IIFE).
|
|
27
29
|
|
|
28
30
|
## Installation
|
|
29
31
|
|
package/dist/core/cipher.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { Cipher } from './types.js';
|
|
2
|
-
export declare function encrypt(payload: Uint8Array<ArrayBuffer>, keyData: BufferSource): Promise<
|
|
1
|
+
import type { Cipher, CipherV2 } from './types.js';
|
|
2
|
+
export declare function encrypt(payload: Uint8Array<ArrayBuffer>, keyData: BufferSource): Promise<CipherV2>;
|
|
3
3
|
export declare function decrypt(cipher: Cipher, keyData: BufferSource): Promise<Uint8Array<ArrayBuffer>>;
|
package/dist/core/cipher.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
async function deriveKey(keyData, salt, version) {
|
|
2
|
+
const info = new TextEncoder().encode(`treadwheel-v${version}`);
|
|
3
3
|
const baseKey = await globalThis.crypto.subtle.importKey('raw', keyData, 'HKDF', false, ['deriveKey']);
|
|
4
|
-
return await globalThis.crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt
|
|
4
|
+
return await globalThis.crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt, info }, baseKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
5
5
|
}
|
|
6
6
|
export async function encrypt(payload, keyData) {
|
|
7
|
+
const v = 2;
|
|
7
8
|
const salt = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
8
9
|
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
9
|
-
const derivedKey = await deriveKey(keyData, salt);
|
|
10
|
+
const derivedKey = await deriveKey(keyData, salt, v);
|
|
10
11
|
const ciphertext = new Uint8Array(await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv }, derivedKey, payload));
|
|
11
|
-
return { salt, iv, ciphertext };
|
|
12
|
+
return { v, salt, iv, ciphertext };
|
|
12
13
|
}
|
|
13
14
|
export async function decrypt(cipher, keyData) {
|
|
14
|
-
const derivedKey = await deriveKey(keyData, cipher.salt);
|
|
15
|
+
const derivedKey = await deriveKey(keyData, cipher.salt, cipher.v);
|
|
15
16
|
return new Uint8Array(await globalThis.crypto.subtle.decrypt({ name: 'AES-GCM', iv: cipher.iv }, derivedKey, cipher.ciphertext));
|
|
16
17
|
}
|
package/dist/core/defaults.js
CHANGED
package/dist/core/index.js
CHANGED
|
@@ -14,7 +14,7 @@ export async function sealFromPrimes(plaintext, p, q, puzzleParams) {
|
|
|
14
14
|
finally {
|
|
15
15
|
keyData.fill(0);
|
|
16
16
|
}
|
|
17
|
-
return envelopeToBytes({
|
|
17
|
+
return envelopeToBytes({ ...puzzle, ...cipher });
|
|
18
18
|
}
|
|
19
19
|
export async function unsealFromBytes(bytes) {
|
|
20
20
|
const envelope = bytesToEnvelope(bytes);
|
package/dist/core/io.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Envelope } from './types.js';
|
|
1
|
+
import type { Envelope, EnvelopeV2 } from './types.js';
|
|
2
2
|
export declare function bytesToBigInt(bytes: Uint8Array): bigint;
|
|
3
3
|
export declare function bigIntToBytes(bigint: bigint, byteLength: number): Uint8Array<ArrayBuffer>;
|
|
4
|
-
export declare function envelopeToBytes({ v, modulusByteLength, time, modulus, base, salt, iv, ciphertext, }:
|
|
4
|
+
export declare function envelopeToBytes({ v, modulusByteLength, baseByteLength, time, modulus, base, salt, iv, ciphertext, }: EnvelopeV2): Uint8Array<ArrayBuffer>;
|
|
5
5
|
export declare function bytesToEnvelope(bytes: Uint8Array<ArrayBuffer>): Envelope;
|
package/dist/core/io.js
CHANGED
|
@@ -70,11 +70,12 @@ export function bigIntToBytes(bigint, byteLength) {
|
|
|
70
70
|
}
|
|
71
71
|
return buffer;
|
|
72
72
|
}
|
|
73
|
-
export function envelopeToBytes({ v, modulusByteLength, time, modulus, base, salt, iv, ciphertext, }) {
|
|
74
|
-
//
|
|
75
|
-
const headerSize = MAGIC_BYTES.byteLength +
|
|
73
|
+
export function envelopeToBytes({ v, modulusByteLength, baseByteLength, time, modulus, base, salt, iv, ciphertext, }) {
|
|
74
|
+
// magic bytes, 1 version, 8 for t, 2 mod length, 2 base length, 4 ct length
|
|
75
|
+
const headerSize = MAGIC_BYTES.byteLength + 17;
|
|
76
76
|
const totalSize = headerSize +
|
|
77
|
-
|
|
77
|
+
modulusByteLength +
|
|
78
|
+
baseByteLength +
|
|
78
79
|
salt.byteLength +
|
|
79
80
|
iv.byteLength +
|
|
80
81
|
ciphertext.byteLength;
|
|
@@ -83,10 +84,11 @@ export function envelopeToBytes({ v, modulusByteLength, time, modulus, base, sal
|
|
|
83
84
|
writer.writeBytes(MAGIC_BYTES);
|
|
84
85
|
writer.writeUint8(v);
|
|
85
86
|
writer.writeUint16(modulusByteLength);
|
|
87
|
+
writer.writeUint16(baseByteLength);
|
|
86
88
|
writer.writeUint32(ciphertext.byteLength);
|
|
87
89
|
writer.writeBigUInt64(time);
|
|
88
90
|
writer.writeBytes(bigIntToBytes(modulus, modulusByteLength));
|
|
89
|
-
writer.writeBytes(bigIntToBytes(base,
|
|
91
|
+
writer.writeBytes(bigIntToBytes(base, baseByteLength));
|
|
90
92
|
writer.writeBytes(salt);
|
|
91
93
|
writer.writeBytes(iv);
|
|
92
94
|
writer.writeBytes(ciphertext);
|
|
@@ -98,15 +100,26 @@ export function bytesToEnvelope(bytes) {
|
|
|
98
100
|
if (!magicBytes.every((b, i) => b === MAGIC_BYTES[i]))
|
|
99
101
|
throw new Error('Invalid envelope: magic bytes mismatch');
|
|
100
102
|
const v = reader.readUint8();
|
|
101
|
-
if (v !== 1)
|
|
103
|
+
if (v !== 1 && v !== 2)
|
|
102
104
|
throw new Error(`Unsupported envelope version ${v}`);
|
|
103
105
|
const modulusByteLength = reader.readUint16();
|
|
106
|
+
const baseByteLength = v === 1 ? modulusByteLength : reader.readUint16();
|
|
104
107
|
const ciphertextLength = reader.readUint32();
|
|
105
108
|
const time = reader.readBigUInt64();
|
|
106
109
|
const modulus = bytesToBigInt(reader.readBytes(modulusByteLength));
|
|
107
|
-
const base = bytesToBigInt(reader.readBytes(
|
|
110
|
+
const base = bytesToBigInt(reader.readBytes(baseByteLength));
|
|
108
111
|
const salt = reader.readBytes(32);
|
|
109
112
|
const iv = reader.readBytes(12);
|
|
110
113
|
const ciphertext = reader.readBytes(ciphertextLength);
|
|
111
|
-
return {
|
|
114
|
+
return {
|
|
115
|
+
v,
|
|
116
|
+
modulusByteLength,
|
|
117
|
+
baseByteLength,
|
|
118
|
+
modulus,
|
|
119
|
+
base,
|
|
120
|
+
time,
|
|
121
|
+
salt,
|
|
122
|
+
iv,
|
|
123
|
+
ciphertext,
|
|
124
|
+
};
|
|
112
125
|
}
|
package/dist/core/puzzle.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Puzzle, PuzzleParams } from './types.js';
|
|
2
|
-
export declare function mint(p: bigint, q: bigint, { time, modulusLength }: PuzzleParams): {
|
|
2
|
+
export declare function mint(p: bigint, q: bigint, { time, modulusLength, randomBase }: PuzzleParams): {
|
|
3
3
|
puzzle: Puzzle;
|
|
4
4
|
solution: bigint;
|
|
5
5
|
};
|
package/dist/core/puzzle.js
CHANGED
|
@@ -14,17 +14,21 @@ function randomBigInt(strictUpperBound, byteLength) {
|
|
|
14
14
|
globalThis.crypto.getRandomValues(randomBytes);
|
|
15
15
|
return bytesToBigInt(randomBytes) % strictUpperBound;
|
|
16
16
|
}
|
|
17
|
-
export function mint(p, q, { time, modulusLength }) {
|
|
17
|
+
export function mint(p, q, { time, modulusLength, randomBase }) {
|
|
18
18
|
if (!Number.isSafeInteger(time) || time < 0)
|
|
19
19
|
throw new RangeError("Option 'time' must be a non-negative safe integer");
|
|
20
20
|
const t = BigInt(time);
|
|
21
21
|
const modulusByteLength = Math.ceil(modulusLength / 8);
|
|
22
22
|
const modulus = p * q;
|
|
23
|
+
const baseByteLength = randomBase ? modulusByteLength : 1;
|
|
24
|
+
const base = randomBase ? randomBigInt(modulus, baseByteLength) : 2n;
|
|
23
25
|
const phi = (p - 1n) * (q - 1n);
|
|
24
|
-
const base = randomBigInt(modulus - 2n, modulusByteLength) + 2n;
|
|
25
26
|
const exponent = modExp(2n, t, phi);
|
|
26
27
|
const solution = modExp(base, exponent, modulus);
|
|
27
|
-
return {
|
|
28
|
+
return {
|
|
29
|
+
puzzle: { modulusByteLength, baseByteLength, modulus, base, time: t },
|
|
30
|
+
solution,
|
|
31
|
+
};
|
|
28
32
|
}
|
|
29
33
|
export function solve({ modulus, base, time }) {
|
|
30
34
|
for (let i = 0n; i < time; i++) {
|
package/dist/core/types.d.ts
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
export interface Cipher {
|
|
2
|
+
v: 1 | 2;
|
|
2
3
|
salt: Uint8Array<ArrayBuffer>;
|
|
3
4
|
iv: Uint8Array<ArrayBuffer>;
|
|
4
5
|
ciphertext: Uint8Array<ArrayBuffer>;
|
|
5
6
|
}
|
|
7
|
+
export interface CipherV2 extends Cipher {
|
|
8
|
+
v: 2;
|
|
9
|
+
}
|
|
6
10
|
export interface Puzzle {
|
|
7
11
|
modulusByteLength: number;
|
|
12
|
+
baseByteLength: number;
|
|
8
13
|
modulus: bigint;
|
|
9
14
|
base: bigint;
|
|
10
15
|
time: bigint;
|
|
11
16
|
}
|
|
12
17
|
export interface Envelope extends Puzzle, Cipher {
|
|
13
|
-
|
|
18
|
+
}
|
|
19
|
+
export interface EnvelopeV2 extends Puzzle, CipherV2 {
|
|
14
20
|
}
|
|
15
21
|
/**
|
|
16
22
|
* Optional configuration options for {@link seal}.
|
|
@@ -26,6 +32,12 @@ export interface SealOptions {
|
|
|
26
32
|
* @default 2048
|
|
27
33
|
*/
|
|
28
34
|
modulusLength?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Whether to use a random base instead of base 2 for the time-lock puzzle.
|
|
37
|
+
* @default false
|
|
38
|
+
* @since 2.0.0
|
|
39
|
+
*/
|
|
40
|
+
randomBase?: boolean;
|
|
29
41
|
}
|
|
30
42
|
export interface PuzzleParams extends Required<SealOptions> {
|
|
31
43
|
}
|
package/dist/node/cli.js
CHANGED
|
@@ -13,7 +13,8 @@ Commands:
|
|
|
13
13
|
Options for seal:
|
|
14
14
|
-t, --time <squarings> Number of sequential squarings required to solve
|
|
15
15
|
the puzzle (default: ${SEAL_DEFAULTS.time})
|
|
16
|
-
-m, --modulus-length <bits> Desired bit-length of the modulus (default: ${SEAL_DEFAULTS.modulusLength})
|
|
16
|
+
-m, --modulus-length <bits> Desired bit-length of the modulus (default: ${SEAL_DEFAULTS.modulusLength})
|
|
17
|
+
--random-base Use a random base instead of 2 (default: ${SEAL_DEFAULTS.randomBase})
|
|
17
18
|
|
|
18
19
|
Global options:
|
|
19
20
|
-h, --help Display this help message
|
|
@@ -32,6 +33,10 @@ const PARSE_ARGS_CONFIG = {
|
|
|
32
33
|
short: 'm',
|
|
33
34
|
default: `${SEAL_DEFAULTS.modulusLength}`,
|
|
34
35
|
},
|
|
36
|
+
'random-base': {
|
|
37
|
+
type: 'boolean',
|
|
38
|
+
default: SEAL_DEFAULTS.randomBase,
|
|
39
|
+
},
|
|
35
40
|
help: {
|
|
36
41
|
type: 'boolean',
|
|
37
42
|
short: 'h',
|
|
@@ -66,7 +71,11 @@ async function runSeal(plaintext, options) {
|
|
|
66
71
|
process.exitCode = 2;
|
|
67
72
|
return;
|
|
68
73
|
}
|
|
69
|
-
const envelope = await seal(plaintext, {
|
|
74
|
+
const envelope = await seal(plaintext, {
|
|
75
|
+
time,
|
|
76
|
+
modulusLength,
|
|
77
|
+
randomBase: options['random-base'],
|
|
78
|
+
});
|
|
70
79
|
process.stdout.write(`${envelope}\n`);
|
|
71
80
|
}
|
|
72
81
|
async function runUnseal(envelope) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t){return new Promise((n,r)=>{if(t?.signal?.aborted)return r(t.signal.reason);t?.signal?.addEventListener(`abort`,s);let i=URL.createObjectURL(new Blob(["(function(){let
|
|
1
|
+
function e(e,t){return new Promise((n,r)=>{if(t?.signal?.aborted)return r(t.signal.reason);t?.signal?.addEventListener(`abort`,s);let i=URL.createObjectURL(new Blob(["(function(){async function e(e,t,n){let r=new TextEncoder().encode(`treadwheel-v${n}`),i=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:r},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function t(t,n){let r=await e(n,t.salt,t.v);return new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:t.iv},r,t.ciphertext))}let n=new Uint8Array([183,15,255]);var r=class{constructor(e){this.offset=0,this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}},i=class extends r{readUint8(){return this.view.getUint8(this.offset++)}readUint16(){let e=this.view.getUint16(this.offset);return this.offset+=2,e}readUint32(){let e=this.view.getUint32(this.offset);return this.offset+=4,e}readBigUInt64(){let e=this.view.getBigUint64(this.offset);return this.offset+=8,e}readBytes(e){let t=this.offset+e;if(t>this.bytes.byteLength)throw Error(`Malformed envelope: unexpected end of data`);let n=this.bytes.subarray(this.offset,t);return this.offset=t,n}};function a(e){let t=0n;for(let n=0;n<e.length;n++)t=t<<8n|BigInt(e[n]);return t}function o(e,t){let n=new Uint8Array(t);for(let r=0;r<t;r++){let i=BigInt((t-1-r)*8);n[r]=Number(e>>i&255n)}return n}function s(e){let t=new i(e);if(!t.readBytes(n.byteLength).every((e,t)=>e===n[t]))throw Error(`Invalid envelope: magic bytes mismatch`);let r=t.readUint8();if(r!==1&&r!==2)throw Error(`Unsupported envelope version ${r}`);let o=t.readUint16(),s=r===1?o:t.readUint16(),c=t.readUint32(),l=t.readBigUInt64();return{v:r,modulusByteLength:o,baseByteLength:s,modulus:a(t.readBytes(o)),base:a(t.readBytes(s)),time:l,salt:t.readBytes(32),iv:t.readBytes(12),ciphertext:t.readBytes(c)}}function c({modulus:e,base:t,time:n}){for(let r=0n;r<n;r++)t=t*t%e;return t}new TextEncoder;let l=new TextDecoder;async function u(e){let n=s(e),r=o(c(n),n.modulusByteLength),i;try{i=await t(n,r)}finally{r.fill(0)}return l.decode(i)}function d(e){if(`fromBase64`in Uint8Array&&typeof Uint8Array.fromBase64==`function`)return Uint8Array.fromBase64(e,{alphabet:`base64url`});let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+=`==`.slice((t.length+2)%4),Uint8Array.from(atob(t),e=>e.charCodeAt(0))}async function f(e){if(!globalThis.crypto?.subtle)throw Error(`Web Crypto API is not available`);return await u(d(e))}self.onmessage=async e=>{try{let t=await f(e.data);self.postMessage({success:!0,plaintext:t})}catch(e){self.postMessage({success:!1,error:e instanceof Error?e:Error(String(e))})}}})();"],{type:`application/javascript`})),a=new Worker(i);URL.revokeObjectURL(i);let o=()=>{a.terminate(),t?.signal?.removeEventListener(`abort`,s)};a.onmessage=e=>{e.data.success?n(e.data.plaintext):r(e.data.error),o()},a.onerror=e=>{e.preventDefault(),r(e.error??Error(e.message)),o()};function s(e){r(e.target.reason),o()}a.postMessage(e)})}const t=String.raw,n=document.createElement(`template`);n.innerHTML=t`<style>#base,:host{display:contents}#widget{all:initial;display:block;box-sizing:border-box;width:300px;max-width:100%;color-scheme:inherit;color:#111;color:light-dark(#111,#eee);background:#fff;background:light-dark(#fff,#111);border:1px solid #0002;border-color:light-dark(#0002,#fff3);border-radius:10px;box-shadow:0 1px 2px #0001;box-shadow:0 1px 2px light-dark(#0001,#0006);font-size:16px;line-height:1.25;font-family:Inter,Roboto,"Helvetica Neue","Arial Nova","Nimbus Sans",Arial,sans-serif;-webkit-user-select:none;user-select:none}:host([layout=floating]) #base{display:inline-block;position:relative}:host([layout=floating]) #widget{display:none;position:absolute;z-index:1000000;opacity:0;transition:opacity .2s ease-in .8s}:host([layout=floating][status]) #widget{display:block}:host([layout=floating][status=error]) #widget,:host([layout=floating][status=processing]) #widget{opacity:1;transition:opacity .1s ease-out}:host([layout=floating][status=success]) #base{position:absolute;pointer-events:none}:host([layout=floating][status=success]) #trigger{visibility:hidden}@supports (position-area:block-end span-inline-end){:host([layout=floating]) #base{position:static;anchor-name:--base}:host([layout=floating]) #widget{position:fixed;position-anchor:--base;position-area:block-end span-inline-end;position-try-fallbacks:flip-inline}}button{all:unset;width:100%;cursor:pointer}button:focus-visible{outline:revert}:host([status]) #status,button{position:relative;box-sizing:border-box;min-height:46px;padding:16px 16px 10px 52px;border-radius:6px}:host([status]) button{display:none}:host([status=processing]) #status{cursor:wait}:host([status]) #status::before,button::before{content:'';position:absolute;left:14px;top:50%;width:24px;height:24px;margin-top:-10px;border:1px solid #aaa;border-color:light-dark(#aaa,#777);border-radius:6px}:host([status=processing]) #status::before{border-radius:50%;border-color:currentColor currentColor transparent transparent;animation:spin 1s linear infinite}:host([status=success]) #status::before{border-color:#285;background-color:#285;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==")}:host([status=error]) #status::before{border-color:#d34;background-color:#d34;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE3IDcgNyAxN003IDdsMTAgMTAiLz48L3N2Zz4=")}footer{text-align:right;font-size:12px;color:#666;color:light-dark(#666,#999);padding:2px 9px 7px 9px}footer a{color:inherit;text-decoration:none}footer a:hover{text-decoration:underline}@keyframes spin{to{transform:rotate(360deg)}}</style><div id="base"><slot id="trigger"></slot><article id="widget" lang="en"><button type="button">I'm not a robot</button><div id="status" role="status"></div><footer>Protected by <a href="https://github.com/jo-phil/treadwheel" target="_blank" rel="noopener noreferrer" translate="no">Treadwheel</a></footer></article></div>`;var r=class extends HTMLElement{constructor(){super(),this._shadow=this.attachShadow({mode:`open`}),this._handleClick=async t=>{if(!t.target?.closest(`button`))return;let n=this.getAttribute(`envelope`);if(!n)return;this.setAttribute(`status`,`processing`),this.querySelectorAll(`button`).forEach(e=>{e.disabled=!0});let r=this._shadow.getElementById(`status`);r&&(r.textContent=`Verifying…`);try{let t=await e(n,{signal:this._abortController?.signal});this._shadow.removeEventListener(`click`,this._handleClick),this.setAttribute(`status`,`success`),r&&(r.textContent=`Verified`);let i=document.createElement(`div`);i.slot=`_output`,i.style.display=`contents`,this.getAttribute(`output`)===`html`?i.innerHTML=t:i.textContent=t,this.append(i);let a=document.createElement(`style`);a.textContent=`:host{display:contents}`;let o=document.createElement(`slot`);o.name=`_output`;let s=()=>{this._shadow.replaceChildren(a,o),[...this.childNodes].forEach(e=>{e!==i&&e.remove()})},c=this._shadow.getElementById(`widget`);c&&this.getAttribute(`layout`)===`floating`?(this._shadow.append(o),c.addEventListener(`transitionend`,s,{once:!0})):s()}catch(e){e instanceof DOMException&&e.name===`AbortError`?(this.removeAttribute(`status`),r&&(r.textContent=``),this.querySelectorAll(`button`).forEach(e=>{e.disabled=!1})):(this.setAttribute(`status`,`error`),r&&(r.textContent=`Verification failed`))}},this._shadow.appendChild(n.content.cloneNode(!0)),this._shadow.addEventListener(`click`,this._handleClick),this._shadow.getElementById(`trigger`)?.addEventListener(`slotchange`,()=>{this.hasAttribute(`layout`)||this.querySelector(`button`)&&this.setAttribute(`layout`,`floating`)},{once:!0})}connectedCallback(){this._abortController=new AbortController}disconnectedCallback(){this._abortController?.abort()}};customElements.define(`treadwheel-widget`,r);
|
|
2
2
|
//# sourceMappingURL=treadwheel-widget.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"treadwheel-widget.min.js","names":["unsealInWorker","envelope","options","resolve","reject","handleAbort","url","worker","cleanup","event","errorEvent","html","template","TreadwheelWidget","e","button","status","plaintext","output","style","slot","purge","node","widget","error"],"sources":["../src/browser/index.ts","../src/browser/widget.ts"],"sourcesContent":["import { SEAL_DEFAULTS } from '../core/defaults.js';\nimport { sealFromPrimes, unsealFromBytes } from '../core/index.js';\nimport { bytesToBigInt } from '../core/io.js';\nimport type { SealOptions, UnsealInWorkerOptions } from '../core/types.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './codec.js';\n\nexport type { SealOptions, UnsealInWorkerOptions };\n\n/**\n * Seal plaintext using a time-lock puzzle.\n *\n * @param plaintext - The plaintext to seal.\n * @param options - Optional configuration options.\n * @returns A Base64URL-encoded envelope.\n */\nexport async function seal(\n plaintext: string,\n options?: SealOptions,\n): Promise<string> {\n const config = { ...SEAL_DEFAULTS, ...options };\n\n const keyPair = await globalThis.crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: config.modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256',\n },\n true,\n ['decrypt'],\n );\n const jwk = await globalThis.crypto.subtle.exportKey(\n 'jwk',\n keyPair.privateKey,\n );\n\n if (!jwk.p || !jwk.q) throw new Error('RSA JWK is missing primes p or q');\n const p = bytesToBigInt(base64UrlToBytes(jwk.p));\n const q = bytesToBigInt(base64UrlToBytes(jwk.q));\n\n return bytesToBase64Url(await sealFromPrimes(plaintext, p, q, config));\n}\n\n/**\n * Unseal an envelope by solving its time-lock puzzle.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @returns The decrypted plaintext.\n */\nexport async function unseal(envelope: string): Promise<string> {\n if (!globalThis.crypto?.subtle)\n throw new Error('Web Crypto API is not available');\n\n return await unsealFromBytes(base64UrlToBytes(envelope));\n}\n\n/**\n * Unseal an envelope in a web worker.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @param options - Optional configuration options.\n * @returns The decrypted plaintext.\n */\nexport function unsealInWorker(\n envelope: string,\n options?: UnsealInWorkerOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n if (options?.signal?.aborted) return reject(options.signal.reason);\n options?.signal?.addEventListener('abort', handleAbort);\n\n const worker = new Worker(new URL('./worker.js', import.meta.url), {\n type: 'module',\n });\n\n const cleanup = () => {\n worker.terminate();\n options?.signal?.removeEventListener('abort', handleAbort);\n };\n\n worker.onmessage = (event) => {\n if (event.data.success) resolve(event.data.plaintext);\n else reject(event.data.error);\n cleanup();\n };\n\n worker.onerror = (errorEvent) => {\n errorEvent.preventDefault();\n reject(errorEvent.error ?? new Error(errorEvent.message));\n cleanup();\n };\n\n function handleAbort(event: Event) {\n reject((event.target as AbortSignal).reason);\n cleanup();\n }\n\n worker.postMessage(envelope);\n });\n}\n","import { unsealInWorker } from './index.js';\n\nconst html = String.raw;\n\nconst template = document.createElement('template');\ntemplate.innerHTML = html`\n <style>\n :host, #base {\n display: contents;\n }\n\n #widget {\n all: initial;\n display: block;\n box-sizing: border-box;\n width: 300px;\n max-width: 100%;\n\n color-scheme: inherit;\n color: #111;\n color: light-dark(#111, #eee);\n background: #fff;\n background: light-dark(#fff, #111);\n\n border: 1px solid #0002;\n border-color: light-dark(#0002, #fff3);\n border-radius: 10px;\n box-shadow: 0 1px 2px #0001;\n box-shadow: 0 1px 2px light-dark(#0001, #0006);\n\n font-size: 16px;\n line-height: 1.25;\n font-family:\n Inter, Roboto, \"Helvetica Neue\", \"Arial Nova\", \"Nimbus Sans\", Arial,\n sans-serif;\n\n -webkit-user-select: none;\n user-select: none;\n }\n\n :host([layout=\"floating\"]) #base {\n display: inline-block;\n position: relative;\n }\n\n :host([layout=\"floating\"]) #widget {\n display: none;\n position: absolute;\n z-index: 1000000;\n opacity: 0;\n transition: opacity .2s ease-in .8s;\n }\n\n :host([layout=\"floating\"][status]) #widget {\n display: block;\n }\n\n :host([layout=\"floating\"][status=\"processing\"]) #widget,\n :host([layout=\"floating\"][status=\"error\"]) #widget {\n opacity: 1;\n transition: opacity .1s ease-out;\n }\n\n :host([layout=\"floating\"][status=\"success\"]) #base {\n position: absolute;\n pointer-events: none;\n }\n\n :host([layout=\"floating\"][status=\"success\"]) #trigger {\n visibility: hidden;\n }\n\n @supports (position-area: block-end span-inline-end) {\n :host([layout=\"floating\"]) #base {\n position: static;\n anchor-name: --base;\n }\n\n :host([layout=\"floating\"]) #widget {\n position: fixed;\n position-anchor: --base;\n position-area: block-end span-inline-end;\n position-try-fallbacks: flip-inline;\n }\n }\n\n button {\n all: unset;\n width: 100%;\n cursor: pointer;\n }\n\n button:focus-visible {\n outline: revert;\n }\n\n button, :host([status]) #status {\n position: relative;\n box-sizing: border-box;\n min-height: 46px;\n padding: 16px 16px 10px 52px;\n border-radius: 6px;\n }\n\n :host([status]) button {\n display: none;\n }\n\n :host([status=\"processing\"]) #status {\n cursor: wait;\n }\n\n button::before, :host([status]) #status::before {\n content: '';\n position: absolute;\n left: 14px;\n top: 50%;\n width: 24px;\n height: 24px;\n margin-top: -10px;\n\n border: 1px solid #aaa;\n border-color: light-dark(#aaa, #777);\n border-radius: 6px;\n }\n\n :host([status=\"processing\"]) #status::before {\n border-radius: 50%;\n border-color: currentColor currentColor transparent transparent;\n animation: spin 1s linear infinite;\n }\n\n :host([status=\"success\"]) #status::before {\n border-color: #285;\n background-color: #285;\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==\");\n }\n\n :host([status=\"error\"]) #status::before {\n border-color: #d34;\n background-color: #d34;\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE3IDcgNyAxN003IDdsMTAgMTAiLz48L3N2Zz4=\");\n }\n\n footer {\n text-align: right;\n font-size: 12px;\n color: #666;\n color: light-dark(#666, #999);\n padding: 2px 9px 7px 9px;\n }\n\n footer a {\n color: inherit;\n text-decoration: none;\n }\n\n footer a:hover {\n text-decoration: underline;\n }\n\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n <div id=\"base\">\n <slot id=\"trigger\"></slot>\n <article id=\"widget\" lang=\"en\">\n <button type=\"button\">I'm not a robot</button>\n <div id=\"status\" role=\"status\"></div>\n <footer>\n Protected by\n <a\n href=\"https://github.com/jo-phil/treadwheel\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n translate=\"no\"\n >\n Treadwheel\n </a>\n </footer>\n </article>\n </div>\n`;\n\nclass TreadwheelWidget extends HTMLElement {\n private _shadow = this.attachShadow({ mode: 'open' });\n private _abortController?: AbortController;\n\n constructor() {\n super();\n\n this._shadow.appendChild(template.content.cloneNode(true));\n this._shadow.addEventListener('click', this._handleClick);\n this._shadow.getElementById('trigger')?.addEventListener(\n 'slotchange',\n () => {\n if (this.hasAttribute('layout')) return;\n if (this.querySelector('button')) {\n this.setAttribute('layout', 'floating');\n }\n },\n { once: true },\n );\n }\n\n connectedCallback() {\n this._abortController = new AbortController();\n }\n\n disconnectedCallback() {\n this._abortController?.abort();\n }\n\n private _handleClick = async (e: Event) => {\n const target = e.target as HTMLElement | null;\n if (!target?.closest('button')) return;\n\n const envelope = this.getAttribute('envelope');\n if (!envelope) return;\n\n this.setAttribute('status', 'processing');\n this.querySelectorAll('button').forEach((button) => {\n button.disabled = true;\n });\n\n const status = this._shadow.getElementById('status');\n if (status) status.textContent = 'Verifying…';\n\n try {\n const plaintext = await unsealInWorker(envelope, {\n signal: this._abortController?.signal,\n });\n\n this._shadow.removeEventListener('click', this._handleClick);\n this.setAttribute('status', 'success');\n if (status) status.textContent = 'Verified';\n\n const output = document.createElement('div');\n output.slot = '_output';\n output.style.display = 'contents';\n\n if (this.getAttribute('output') === 'html') output.innerHTML = plaintext;\n else output.textContent = plaintext;\n this.append(output);\n\n const style = document.createElement('style');\n style.textContent = ':host{display:contents}';\n\n const slot = document.createElement('slot');\n slot.name = '_output';\n\n const purge = () => {\n this._shadow.replaceChildren(style, slot);\n [...this.childNodes].forEach((node) => {\n if (node !== output) node.remove();\n });\n };\n\n const widget = this._shadow.getElementById('widget');\n if (widget && this.getAttribute('layout') === 'floating') {\n this._shadow.append(slot);\n widget.addEventListener('transitionend', purge, { once: true });\n } else {\n purge();\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n this.removeAttribute('status');\n if (status) status.textContent = '';\n this.querySelectorAll('button').forEach((button) => {\n button.disabled = false;\n });\n } else {\n this.setAttribute('status', 'error');\n if (status) status.textContent = 'Verification failed';\n }\n }\n };\n}\n\ncustomElements.define('treadwheel-widget', TreadwheelWidget);\n"],"mappings":"AA+DA,SAAgBA,EACdC,EACAC,EACiB,CACjB,OAAO,IAAI,SAASC,EAASC,IAAW,CACtC,GAAIF,GAAS,QAAQ,QAAS,OAAOE,EAAOF,EAAQ,OAAO,MAAM,EACjEA,GAAS,QAAQ,iBAAiB,QAASG,CAAW,EAEtD,IAAAC,EAAA,IAAA,gBAAA,IAAA,KAAA,CAAA,s9EAAA,EAAA,CAAA,KAAA,wBAAA,CAAA,CAAA,EAAAC,EAAA,IAAA,OAAAD,CAAA,EAAA,IAAA,gBAAAA,CAAA,EAIA,IAAME,MAAgB,CACpBD,EAAO,UAAU,EACjBL,GAAS,QAAQ,oBAAoB,QAASG,CAAW,CAC3D,EAEAE,EAAO,UAAaE,GAAU,CACxBA,EAAM,KAAK,QAASN,EAAQM,EAAM,KAAK,SAAS,EAC/CL,EAAOK,EAAM,KAAK,KAAK,EAC5BD,EAAQ,CACV,EAEAD,EAAO,QAAWG,GAAe,CAC/BA,EAAW,eAAe,EAC1BN,EAAOM,EAAW,OAAa,MAAMA,EAAW,OAAO,CAAC,EACxDF,EAAQ,CACV,EAEA,SAASH,EAAYI,EAAc,CACjCL,EAAQK,EAAM,OAAuB,MAAM,EAC3CD,EAAQ,CACV,CAEAD,EAAO,YAAYN,CAAQ,CAC7B,CAAC,CACH,CCjGA,MAAMU,EAAO,OAAO,IAEdC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,UAAYD,CAAI,itGAkLzB,IA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BAAiB,gBAAiBF,EAAO,CAAE,KAAM,EAAK,CAAC,GAE9DA,EAAM,CAEV,OAASG,EAAO,CACVA,aAAiB,cAAgBA,EAAM,OAAS,cAClD,KAAK,gBAAgB,QAAQ,EACzBR,IAAQA,EAAO,YAAc,IACjC,KAAK,iBAAiB,QAAQ,CAAC,CAAC,QAASD,GAAW,CAClDA,EAAO,SAAW,EACpB,CAAC,IAED,KAAK,aAAa,SAAU,OAAO,EAC/BC,IAAQA,EAAO,YAAc,uBAErC,CACF,EAtFE,KAAK,QAAQ,YAAYJ,EAAS,QAAQ,UAAU,EAAI,CAAC,EACzD,KAAK,QAAQ,iBAAiB,QAAS,KAAK,YAAY,EACxD,KAAK,QAAQ,eAAe,SAAS,CAAC,EAAE,iBACtC,iBACM,CACA,KAAK,aAAa,QAAQ,GAC1B,KAAK,cAAc,QAAQ,GAC7B,KAAK,aAAa,SAAU,UAAU,CAE1C,EACA,CAAE,KAAM,EAAK,CACf,CACF,CAEA,mBAAoB,CAClB,KAAK,iBAAmB,IAAI,eAC9B,CAEA,sBAAuB,CACrB,KAAK,kBAAkB,MAAM,CAC/B,CAmEF,EAEA,eAAe,OAAO,oBAAqBC,CAAgB"}
|
|
1
|
+
{"version":3,"file":"treadwheel-widget.min.js","names":["unsealInWorker","envelope","options","resolve","reject","handleAbort","url","worker","cleanup","event","errorEvent","html","template","TreadwheelWidget","e","button","status","plaintext","output","style","slot","purge","node","widget","error"],"sources":["../src/browser/index.ts","../src/browser/widget.ts"],"sourcesContent":["import { SEAL_DEFAULTS } from '../core/defaults.js';\nimport { sealFromPrimes, unsealFromBytes } from '../core/index.js';\nimport { bytesToBigInt } from '../core/io.js';\nimport type { SealOptions, UnsealInWorkerOptions } from '../core/types.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './codec.js';\n\nexport type { SealOptions, UnsealInWorkerOptions };\n\n/**\n * Seal plaintext using a time-lock puzzle.\n *\n * @param plaintext - The plaintext to seal.\n * @param options - Optional configuration options.\n * @returns A Base64URL-encoded envelope.\n */\nexport async function seal(\n plaintext: string,\n options?: SealOptions,\n): Promise<string> {\n const config = { ...SEAL_DEFAULTS, ...options };\n\n const keyPair = await globalThis.crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: config.modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256',\n },\n true,\n ['decrypt'],\n );\n const jwk = await globalThis.crypto.subtle.exportKey(\n 'jwk',\n keyPair.privateKey,\n );\n\n if (!jwk.p || !jwk.q) throw new Error('RSA JWK is missing primes p or q');\n const p = bytesToBigInt(base64UrlToBytes(jwk.p));\n const q = bytesToBigInt(base64UrlToBytes(jwk.q));\n\n return bytesToBase64Url(await sealFromPrimes(plaintext, p, q, config));\n}\n\n/**\n * Unseal an envelope by solving its time-lock puzzle.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @returns The decrypted plaintext.\n */\nexport async function unseal(envelope: string): Promise<string> {\n if (!globalThis.crypto?.subtle)\n throw new Error('Web Crypto API is not available');\n\n return await unsealFromBytes(base64UrlToBytes(envelope));\n}\n\n/**\n * Unseal an envelope in a web worker.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @param options - Optional configuration options.\n * @returns The decrypted plaintext.\n */\nexport function unsealInWorker(\n envelope: string,\n options?: UnsealInWorkerOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n if (options?.signal?.aborted) return reject(options.signal.reason);\n options?.signal?.addEventListener('abort', handleAbort);\n\n const worker = new Worker(new URL('./worker.js', import.meta.url), {\n type: 'module',\n });\n\n const cleanup = () => {\n worker.terminate();\n options?.signal?.removeEventListener('abort', handleAbort);\n };\n\n worker.onmessage = (event) => {\n if (event.data.success) resolve(event.data.plaintext);\n else reject(event.data.error);\n cleanup();\n };\n\n worker.onerror = (errorEvent) => {\n errorEvent.preventDefault();\n reject(errorEvent.error ?? new Error(errorEvent.message));\n cleanup();\n };\n\n function handleAbort(event: Event) {\n reject((event.target as AbortSignal).reason);\n cleanup();\n }\n\n worker.postMessage(envelope);\n });\n}\n","import { unsealInWorker } from './index.js';\n\nconst html = String.raw;\n\nconst template = document.createElement('template');\ntemplate.innerHTML = html`\n <style>\n :host, #base {\n display: contents;\n }\n\n #widget {\n all: initial;\n display: block;\n box-sizing: border-box;\n width: 300px;\n max-width: 100%;\n\n color-scheme: inherit;\n color: #111;\n color: light-dark(#111, #eee);\n background: #fff;\n background: light-dark(#fff, #111);\n\n border: 1px solid #0002;\n border-color: light-dark(#0002, #fff3);\n border-radius: 10px;\n box-shadow: 0 1px 2px #0001;\n box-shadow: 0 1px 2px light-dark(#0001, #0006);\n\n font-size: 16px;\n line-height: 1.25;\n font-family:\n Inter, Roboto, \"Helvetica Neue\", \"Arial Nova\", \"Nimbus Sans\", Arial,\n sans-serif;\n\n -webkit-user-select: none;\n user-select: none;\n }\n\n :host([layout=\"floating\"]) #base {\n display: inline-block;\n position: relative;\n }\n\n :host([layout=\"floating\"]) #widget {\n display: none;\n position: absolute;\n z-index: 1000000;\n opacity: 0;\n transition: opacity .2s ease-in .8s;\n }\n\n :host([layout=\"floating\"][status]) #widget {\n display: block;\n }\n\n :host([layout=\"floating\"][status=\"processing\"]) #widget,\n :host([layout=\"floating\"][status=\"error\"]) #widget {\n opacity: 1;\n transition: opacity .1s ease-out;\n }\n\n :host([layout=\"floating\"][status=\"success\"]) #base {\n position: absolute;\n pointer-events: none;\n }\n\n :host([layout=\"floating\"][status=\"success\"]) #trigger {\n visibility: hidden;\n }\n\n @supports (position-area: block-end span-inline-end) {\n :host([layout=\"floating\"]) #base {\n position: static;\n anchor-name: --base;\n }\n\n :host([layout=\"floating\"]) #widget {\n position: fixed;\n position-anchor: --base;\n position-area: block-end span-inline-end;\n position-try-fallbacks: flip-inline;\n }\n }\n\n button {\n all: unset;\n width: 100%;\n cursor: pointer;\n }\n\n button:focus-visible {\n outline: revert;\n }\n\n button, :host([status]) #status {\n position: relative;\n box-sizing: border-box;\n min-height: 46px;\n padding: 16px 16px 10px 52px;\n border-radius: 6px;\n }\n\n :host([status]) button {\n display: none;\n }\n\n :host([status=\"processing\"]) #status {\n cursor: wait;\n }\n\n button::before, :host([status]) #status::before {\n content: '';\n position: absolute;\n left: 14px;\n top: 50%;\n width: 24px;\n height: 24px;\n margin-top: -10px;\n\n border: 1px solid #aaa;\n border-color: light-dark(#aaa, #777);\n border-radius: 6px;\n }\n\n :host([status=\"processing\"]) #status::before {\n border-radius: 50%;\n border-color: currentColor currentColor transparent transparent;\n animation: spin 1s linear infinite;\n }\n\n :host([status=\"success\"]) #status::before {\n border-color: #285;\n background-color: #285;\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==\");\n }\n\n :host([status=\"error\"]) #status::before {\n border-color: #d34;\n background-color: #d34;\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE3IDcgNyAxN003IDdsMTAgMTAiLz48L3N2Zz4=\");\n }\n\n footer {\n text-align: right;\n font-size: 12px;\n color: #666;\n color: light-dark(#666, #999);\n padding: 2px 9px 7px 9px;\n }\n\n footer a {\n color: inherit;\n text-decoration: none;\n }\n\n footer a:hover {\n text-decoration: underline;\n }\n\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n <div id=\"base\">\n <slot id=\"trigger\"></slot>\n <article id=\"widget\" lang=\"en\">\n <button type=\"button\">I'm not a robot</button>\n <div id=\"status\" role=\"status\"></div>\n <footer>\n Protected by\n <a\n href=\"https://github.com/jo-phil/treadwheel\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n translate=\"no\"\n >\n Treadwheel\n </a>\n </footer>\n </article>\n </div>\n`;\n\nclass TreadwheelWidget extends HTMLElement {\n private _shadow = this.attachShadow({ mode: 'open' });\n private _abortController?: AbortController;\n\n constructor() {\n super();\n\n this._shadow.appendChild(template.content.cloneNode(true));\n this._shadow.addEventListener('click', this._handleClick);\n this._shadow.getElementById('trigger')?.addEventListener(\n 'slotchange',\n () => {\n if (this.hasAttribute('layout')) return;\n if (this.querySelector('button')) {\n this.setAttribute('layout', 'floating');\n }\n },\n { once: true },\n );\n }\n\n connectedCallback() {\n this._abortController = new AbortController();\n }\n\n disconnectedCallback() {\n this._abortController?.abort();\n }\n\n private _handleClick = async (e: Event) => {\n const target = e.target as HTMLElement | null;\n if (!target?.closest('button')) return;\n\n const envelope = this.getAttribute('envelope');\n if (!envelope) return;\n\n this.setAttribute('status', 'processing');\n this.querySelectorAll('button').forEach((button) => {\n button.disabled = true;\n });\n\n const status = this._shadow.getElementById('status');\n if (status) status.textContent = 'Verifying…';\n\n try {\n const plaintext = await unsealInWorker(envelope, {\n signal: this._abortController?.signal,\n });\n\n this._shadow.removeEventListener('click', this._handleClick);\n this.setAttribute('status', 'success');\n if (status) status.textContent = 'Verified';\n\n const output = document.createElement('div');\n output.slot = '_output';\n output.style.display = 'contents';\n\n if (this.getAttribute('output') === 'html') output.innerHTML = plaintext;\n else output.textContent = plaintext;\n this.append(output);\n\n const style = document.createElement('style');\n style.textContent = ':host{display:contents}';\n\n const slot = document.createElement('slot');\n slot.name = '_output';\n\n const purge = () => {\n this._shadow.replaceChildren(style, slot);\n [...this.childNodes].forEach((node) => {\n if (node !== output) node.remove();\n });\n };\n\n const widget = this._shadow.getElementById('widget');\n if (widget && this.getAttribute('layout') === 'floating') {\n this._shadow.append(slot);\n widget.addEventListener('transitionend', purge, { once: true });\n } else {\n purge();\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n this.removeAttribute('status');\n if (status) status.textContent = '';\n this.querySelectorAll('button').forEach((button) => {\n button.disabled = false;\n });\n } else {\n this.setAttribute('status', 'error');\n if (status) status.textContent = 'Verification failed';\n }\n }\n };\n}\n\ncustomElements.define('treadwheel-widget', TreadwheelWidget);\n"],"mappings":"AA+DA,SAAgBA,EACdC,EACAC,EACiB,CACjB,OAAO,IAAI,SAASC,EAASC,IAAW,CACtC,GAAIF,GAAS,QAAQ,QAAS,OAAOE,EAAOF,EAAQ,OAAO,MAAM,EACjEA,GAAS,QAAQ,iBAAiB,QAASG,CAAW,EAEtD,IAAAC,EAAA,IAAA,gBAAA,IAAA,KAAA,CAAA,ghFAAA,EAAA,CAAA,KAAA,wBAAA,CAAA,CAAA,EAAAC,EAAA,IAAA,OAAAD,CAAA,EAAA,IAAA,gBAAAA,CAAA,EAIA,IAAME,MAAgB,CACpBD,EAAO,UAAU,EACjBL,GAAS,QAAQ,oBAAoB,QAASG,CAAW,CAC3D,EAEAE,EAAO,UAAaE,GAAU,CACxBA,EAAM,KAAK,QAASN,EAAQM,EAAM,KAAK,SAAS,EAC/CL,EAAOK,EAAM,KAAK,KAAK,EAC5BD,EAAQ,CACV,EAEAD,EAAO,QAAWG,GAAe,CAC/BA,EAAW,eAAe,EAC1BN,EAAOM,EAAW,OAAa,MAAMA,EAAW,OAAO,CAAC,EACxDF,EAAQ,CACV,EAEA,SAASH,EAAYI,EAAc,CACjCL,EAAQK,EAAM,OAAuB,MAAM,EAC3CD,EAAQ,CACV,CAEAD,EAAO,YAAYN,CAAQ,CAC7B,CAAC,CACH,CCjGA,MAAMU,EAAO,OAAO,IAEdC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,UAAYD,CAAI,itGAkLzB,IAAME,EAAN,cAA+B,WAAY,CAIzC,aAAc,CACZ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,CAAC,GAE9DA,EAAM,CAEV,OAASG,EAAO,CACVA,aAAiB,cAAgBA,EAAM,OAAS,cAClD,KAAK,gBAAgB,QAAQ,EACzBR,IAAQA,EAAO,YAAc,IACjC,KAAK,iBAAiB,QAAQ,CAAC,CAAC,QAASD,GAAW,CAClDA,EAAO,SAAW,EACpB,CAAC,IAED,KAAK,aAAa,SAAU,OAAO,EAC/BC,IAAQA,EAAO,YAAc,uBAErC,CACF,EAtFE,KAAK,QAAQ,YAAYJ,EAAS,QAAQ,UAAU,EAAI,CAAC,EACzD,KAAK,QAAQ,iBAAiB,QAAS,KAAK,YAAY,EACxD,KAAK,QAAQ,eAAe,SAAS,CAAC,EAAE,iBACtC,iBACM,CACA,KAAK,aAAa,QAAQ,GAC1B,KAAK,cAAc,QAAQ,GAC7B,KAAK,aAAa,SAAU,UAAU,CAE1C,EACA,CAAE,KAAM,EAAK,CACf,CACF,CAEA,mBAAoB,CAClB,KAAK,iBAAmB,IAAI,eAC9B,CAEA,sBAAuB,CACrB,KAAK,kBAAkB,MAAM,CAC/B,CAmEF,EAEA,eAAe,OAAO,oBAAqBC,CAAgB"}
|
package/dist/treadwheel.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={time:25e4,modulusLength:2048},t=new TextEncoder().encode(`treadwheel-
|
|
1
|
+
const e={time:25e4,modulusLength:2048,randomBase:!1};async function t(e,t,n){let r=new TextEncoder().encode(`treadwheel-v${n}`),i=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:r},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function n(e,n){let r=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)),i=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),a=await t(n,r,2);return{v:2,salt:r,iv:i,ciphertext:new Uint8Array(await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:i},a,e))}}async function r(e,n){let r=await t(n,e.salt,e.v);return new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:e.iv},r,e.ciphertext))}const i=new Uint8Array([183,15,255]);var a=class{constructor(e){this.offset=0,this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}},o=class extends a{readUint8(){return this.view.getUint8(this.offset++)}readUint16(){let e=this.view.getUint16(this.offset);return this.offset+=2,e}readUint32(){let e=this.view.getUint32(this.offset);return this.offset+=4,e}readBigUInt64(){let e=this.view.getBigUint64(this.offset);return this.offset+=8,e}readBytes(e){let t=this.offset+e;if(t>this.bytes.byteLength)throw Error(`Malformed envelope: unexpected end of data`);let n=this.bytes.subarray(this.offset,t);return this.offset=t,n}},s=class extends a{writeUint8(e){this.view.setUint8(this.offset++,e)}writeUint16(e){this.view.setUint16(this.offset,e),this.offset+=2}writeUint32(e){this.view.setUint32(this.offset,e),this.offset+=4}writeBigUInt64(e){this.view.setBigUint64(this.offset,BigInt(e)),this.offset+=8}writeBytes(e){this.bytes.set(e,this.offset),this.offset+=e.byteLength}};function c(e){let t=0n;for(let n=0;n<e.length;n++)t=t<<8n|BigInt(e[n]);return t}function l(e,t){let n=new Uint8Array(t);for(let r=0;r<t;r++){let i=BigInt((t-1-r)*8);n[r]=Number(e>>i&255n)}return n}function u({v:e,modulusByteLength:t,baseByteLength:n,time:r,modulus:a,base:o,salt:c,iv:u,ciphertext:d}){let f=i.byteLength+17+t+n+c.byteLength+u.byteLength+d.byteLength,p=new Uint8Array(f),m=new s(p);return m.writeBytes(i),m.writeUint8(e),m.writeUint16(t),m.writeUint16(n),m.writeUint32(d.byteLength),m.writeBigUInt64(r),m.writeBytes(l(a,t)),m.writeBytes(l(o,n)),m.writeBytes(c),m.writeBytes(u),m.writeBytes(d),p}function d(e){let t=new o(e);if(!t.readBytes(i.byteLength).every((e,t)=>e===i[t]))throw Error(`Invalid envelope: magic bytes mismatch`);let n=t.readUint8();if(n!==1&&n!==2)throw Error(`Unsupported envelope version ${n}`);let r=t.readUint16(),a=n===1?r:t.readUint16(),s=t.readUint32(),l=t.readBigUInt64();return{v:n,modulusByteLength:r,baseByteLength:a,modulus:c(t.readBytes(r)),base:c(t.readBytes(a)),time:l,salt:t.readBytes(32),iv:t.readBytes(12),ciphertext:t.readBytes(s)}}function f(e,t,n){let r=1n;for(;t>0n;t>>=1n)t&1n&&(r=r*e%n),e=e*e%n;return r}function p(e,t){let n=new Uint8Array(t+16);return globalThis.crypto.getRandomValues(n),c(n)%e}function m(e,t,{time:n,modulusLength:r,randomBase:i}){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`Option 'time' must be a non-negative safe integer`);let a=BigInt(n),o=Math.ceil(r/8),s=e*t,c=i?o:1,l=i?p(s,c):2n,u=f(l,f(2n,a,(e-1n)*(t-1n)),s);return{puzzle:{modulusByteLength:o,baseByteLength:c,modulus:s,base:l,time:a},solution:u}}function h({modulus:e,base:t,time:n}){for(let r=0n;r<n;r++)t=t*t%e;return t}const g=new TextEncoder,_=new TextDecoder;async function v(e,t,r,i){let a=g.encode(e),{puzzle:o,solution:s}=m(t,r,i),c=l(s,o.modulusByteLength),d;try{d=await n(a,c)}finally{c.fill(0)}return u({...o,...d})}async function y(e){let t=d(e),n=l(h(t),t.modulusByteLength),i;try{i=await r(t,n)}finally{n.fill(0)}return _.decode(i)}function b(e){if(`toBase64`in e&&typeof e.toBase64==`function`)return e.toBase64({alphabet:`base64url`,omitPadding:!0});let t=16384,n=``;for(let r=0;r<e.length;r+=t){let i=e.subarray(r,r+t);n+=String.fromCharCode(...i)}return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function x(e){if(`fromBase64`in Uint8Array&&typeof Uint8Array.fromBase64==`function`)return Uint8Array.fromBase64(e,{alphabet:`base64url`});let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+=`==`.slice((t.length+2)%4),Uint8Array.from(atob(t),e=>e.charCodeAt(0))}async function S(t,n){let r={...e,...n},i=await globalThis.crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:r.modulusLength,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`decrypt`]),a=await globalThis.crypto.subtle.exportKey(`jwk`,i.privateKey);if(!a.p||!a.q)throw Error(`RSA JWK is missing primes p or q`);return b(await v(t,c(x(a.p)),c(x(a.q)),r))}async function C(e){if(!globalThis.crypto?.subtle)throw Error(`Web Crypto API is not available`);return await y(x(e))}function w(e,t){return new Promise((n,r)=>{if(t?.signal?.aborted)return r(t.signal.reason);t?.signal?.addEventListener(`abort`,s);let i=URL.createObjectURL(new Blob(["(function(){async function e(e,t,n){let r=new TextEncoder().encode(`treadwheel-v${n}`),i=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:r},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function t(t,n){let r=await e(n,t.salt,t.v);return new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:t.iv},r,t.ciphertext))}let n=new Uint8Array([183,15,255]);var r=class{constructor(e){this.offset=0,this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}},i=class extends r{readUint8(){return this.view.getUint8(this.offset++)}readUint16(){let e=this.view.getUint16(this.offset);return this.offset+=2,e}readUint32(){let e=this.view.getUint32(this.offset);return this.offset+=4,e}readBigUInt64(){let e=this.view.getBigUint64(this.offset);return this.offset+=8,e}readBytes(e){let t=this.offset+e;if(t>this.bytes.byteLength)throw Error(`Malformed envelope: unexpected end of data`);let n=this.bytes.subarray(this.offset,t);return this.offset=t,n}};function a(e){let t=0n;for(let n=0;n<e.length;n++)t=t<<8n|BigInt(e[n]);return t}function o(e,t){let n=new Uint8Array(t);for(let r=0;r<t;r++){let i=BigInt((t-1-r)*8);n[r]=Number(e>>i&255n)}return n}function s(e){let t=new i(e);if(!t.readBytes(n.byteLength).every((e,t)=>e===n[t]))throw Error(`Invalid envelope: magic bytes mismatch`);let r=t.readUint8();if(r!==1&&r!==2)throw Error(`Unsupported envelope version ${r}`);let o=t.readUint16(),s=r===1?o:t.readUint16(),c=t.readUint32(),l=t.readBigUInt64();return{v:r,modulusByteLength:o,baseByteLength:s,modulus:a(t.readBytes(o)),base:a(t.readBytes(s)),time:l,salt:t.readBytes(32),iv:t.readBytes(12),ciphertext:t.readBytes(c)}}function c({modulus:e,base:t,time:n}){for(let r=0n;r<n;r++)t=t*t%e;return t}new TextEncoder;let l=new TextDecoder;async function u(e){let n=s(e),r=o(c(n),n.modulusByteLength),i;try{i=await t(n,r)}finally{r.fill(0)}return l.decode(i)}function d(e){if(`fromBase64`in Uint8Array&&typeof Uint8Array.fromBase64==`function`)return Uint8Array.fromBase64(e,{alphabet:`base64url`});let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+=`==`.slice((t.length+2)%4),Uint8Array.from(atob(t),e=>e.charCodeAt(0))}async function f(e){if(!globalThis.crypto?.subtle)throw Error(`Web Crypto API is not available`);return await u(d(e))}self.onmessage=async e=>{try{let t=await f(e.data);self.postMessage({success:!0,plaintext:t})}catch(e){self.postMessage({success:!1,error:e instanceof Error?e:Error(String(e))})}}})();"],{type:`application/javascript`})),a=new Worker(i);URL.revokeObjectURL(i);let o=()=>{a.terminate(),t?.signal?.removeEventListener(`abort`,s)};a.onmessage=e=>{e.data.success?n(e.data.plaintext):r(e.data.error),o()},a.onerror=e=>{e.preventDefault(),r(e.error??Error(e.message)),o()};function s(e){r(e.target.reason),o()}a.postMessage(e)})}export{S as seal,C as unseal,w as unsealInWorker};
|
|
2
2
|
//# sourceMappingURL=treadwheel.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"treadwheel.min.js","names":["SEAL_DEFAULTS","INFO_BYTES","deriveKey","keyData","salt","baseKey","encrypt","payload","iv","derivedKey","decrypt","cipher","MAGIC_BYTES","BinaryCursor","bytes","BinaryReader","value","length","until","BinaryWriter","buffer","bytesToBigInt","result","i","bigIntToBytes","bigint","byteLength","shift","envelopeToBytes","v","modulusByteLength","time","modulus","base","ciphertext","totalSize","writer","bytesToEnvelope","reader","b","ciphertextLength","modExp","exponent","randomBigInt","strictUpperBound","randomBytes","mint","p","q","modulusLength","t","phi","solution","solve","encoder","decoder","sealFromPrimes","plaintext","puzzleParams","puzzle","unsealFromBytes","envelope","bytesToBase64Url","CHUNK_SIZE","binaryString","chunk","base64UrlToBytes","base64Url","base64","char","seal","options","config","keyPair","jwk","unseal","unsealInWorker","resolve","reject","handleAbort","url","worker","cleanup","event","errorEvent"],"sources":["../src/core/defaults.ts","../src/core/cipher.ts","../src/core/io.ts","../src/core/puzzle.ts","../src/core/index.ts","../src/browser/codec.ts","../src/browser/index.ts"],"sourcesContent":["import type { SealOptions } from './types.js';\n\nexport const SEAL_DEFAULTS: Required<SealOptions> = {\n time: 250_000,\n modulusLength: 2048,\n};\n","import type { Cipher } from './types.js';\n\nconst INFO_BYTES = new TextEncoder().encode('treadwheel-v1');\n\nasync function deriveKey(\n keyData: BufferSource,\n salt: BufferSource,\n): Promise<CryptoKey> {\n const baseKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n keyData,\n 'HKDF',\n false,\n ['deriveKey'],\n );\n\n return await globalThis.crypto.subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt: salt, info: INFO_BYTES },\n baseKey,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nexport async function encrypt(\n payload: Uint8Array<ArrayBuffer>,\n keyData: BufferSource,\n): Promise<Cipher> {\n const salt = globalThis.crypto.getRandomValues(new Uint8Array(32));\n const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));\n\n const derivedKey = await deriveKey(keyData, salt);\n const ciphertext = new Uint8Array(\n await globalThis.crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n derivedKey,\n payload,\n ),\n );\n\n return { salt, iv, ciphertext };\n}\n\nexport async function decrypt(\n cipher: Cipher,\n keyData: BufferSource,\n): Promise<Uint8Array<ArrayBuffer>> {\n const derivedKey = await deriveKey(keyData, cipher.salt);\n return new Uint8Array(\n await globalThis.crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: cipher.iv },\n derivedKey,\n cipher.ciphertext,\n ),\n );\n}\n","import type { Envelope } from './types.js';\n\nconst MAGIC_BYTES = new Uint8Array([0xb7, 0x0f, 0xff]);\n\nclass BinaryCursor {\n protected view: DataView;\n protected bytes: Uint8Array<ArrayBuffer>;\n protected offset: number = 0;\n\n constructor(bytes: Uint8Array<ArrayBuffer>) {\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n}\n\nclass BinaryReader extends BinaryCursor {\n public readUint8(): number {\n return this.view.getUint8(this.offset++);\n }\n\n public readUint16(): number {\n const value = this.view.getUint16(this.offset);\n this.offset += 2;\n return value;\n }\n\n public readUint32(): number {\n const value = this.view.getUint32(this.offset);\n this.offset += 4;\n return value;\n }\n\n public readBigUInt64(): bigint {\n const value = this.view.getBigUint64(this.offset);\n this.offset += 8;\n return value;\n }\n\n public readBytes(length: number): Uint8Array<ArrayBuffer> {\n const until = this.offset + length;\n if (until > this.bytes.byteLength)\n throw new Error('Malformed envelope: unexpected end of data');\n\n const bytes = this.bytes.subarray(this.offset, until);\n this.offset = until;\n return bytes;\n }\n}\n\nclass BinaryWriter extends BinaryCursor {\n public writeUint8(value: number): void {\n this.view.setUint8(this.offset++, value);\n }\n\n public writeUint16(value: number): void {\n this.view.setUint16(this.offset, value);\n this.offset += 2;\n }\n\n public writeUint32(value: number): void {\n this.view.setUint32(this.offset, value);\n this.offset += 4;\n }\n\n public writeBigUInt64(value: bigint): void {\n this.view.setBigUint64(this.offset, BigInt(value));\n this.offset += 8;\n }\n\n public writeBytes(buffer: Uint8Array): void {\n this.bytes.set(buffer, this.offset);\n this.offset += buffer.byteLength;\n }\n}\n\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n let result = 0n;\n for (let i = 0; i < bytes.length; i++) {\n result = (result << 8n) | BigInt(bytes[i] as number);\n }\n return result;\n}\n\nexport function bigIntToBytes(\n bigint: bigint,\n byteLength: number,\n): Uint8Array<ArrayBuffer> {\n const buffer = new Uint8Array(byteLength);\n for (let i = 0; i < byteLength; i++) {\n const shift = BigInt((byteLength - 1 - i) * 8);\n buffer[i] = Number((bigint >> shift) & 0xffn);\n }\n return buffer;\n}\n\nexport function envelopeToBytes({\n v,\n modulusByteLength,\n time,\n modulus,\n base,\n salt,\n iv,\n ciphertext,\n}: Envelope): Uint8Array<ArrayBuffer> {\n // header: some magic bytes, 1 version, 8 for t, 2 mod length, 4 ct length\n const headerSize = MAGIC_BYTES.byteLength + 15;\n const totalSize =\n headerSize +\n 2 * modulusByteLength +\n salt.byteLength +\n iv.byteLength +\n ciphertext.byteLength;\n\n const bytes = new Uint8Array(totalSize);\n const writer = new BinaryWriter(bytes);\n\n writer.writeBytes(MAGIC_BYTES);\n writer.writeUint8(v);\n\n writer.writeUint16(modulusByteLength);\n writer.writeUint32(ciphertext.byteLength);\n\n writer.writeBigUInt64(time);\n writer.writeBytes(bigIntToBytes(modulus, modulusByteLength));\n writer.writeBytes(bigIntToBytes(base, modulusByteLength));\n\n writer.writeBytes(salt);\n writer.writeBytes(iv);\n writer.writeBytes(ciphertext);\n\n return bytes;\n}\n\nexport function bytesToEnvelope(bytes: Uint8Array<ArrayBuffer>): Envelope {\n const reader = new BinaryReader(bytes);\n\n const magicBytes = reader.readBytes(MAGIC_BYTES.byteLength);\n if (!magicBytes.every((b, i) => b === MAGIC_BYTES[i]))\n throw new Error('Invalid envelope: magic bytes mismatch');\n\n const v = reader.readUint8();\n if (v !== 1) throw new Error(`Unsupported envelope version ${v}`);\n\n const modulusByteLength = reader.readUint16();\n const ciphertextLength = reader.readUint32();\n\n const time = reader.readBigUInt64();\n const modulus = bytesToBigInt(reader.readBytes(modulusByteLength));\n const base = bytesToBigInt(reader.readBytes(modulusByteLength));\n\n const salt = reader.readBytes(32);\n const iv = reader.readBytes(12);\n const ciphertext = reader.readBytes(ciphertextLength);\n\n return { v, modulusByteLength, time, modulus, base, salt, iv, ciphertext };\n}\n","import { bytesToBigInt } from './io.js';\nimport type { Puzzle, PuzzleParams } from './types.js';\n\nfunction modExp(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n for (; exponent > 0n; exponent >>= 1n) {\n if (exponent & 1n) result = (result * base) % modulus;\n base = (base * base) % modulus;\n }\n return result;\n}\n\nfunction randomBigInt(strictUpperBound: bigint, byteLength: number): bigint {\n // Oversample by 16 bytes to reduce modulo bias\n const randomBytes = new Uint8Array(byteLength + 16);\n globalThis.crypto.getRandomValues(randomBytes);\n return bytesToBigInt(randomBytes) % strictUpperBound;\n}\n\nexport function mint(\n p: bigint,\n q: bigint,\n { time, modulusLength }: PuzzleParams,\n): { puzzle: Puzzle; solution: bigint } {\n if (!Number.isSafeInteger(time) || time < 0)\n throw new RangeError(\"Option 'time' must be a non-negative safe integer\");\n\n const t = BigInt(time);\n const modulusByteLength = Math.ceil(modulusLength / 8);\n\n const modulus = p * q;\n const phi = (p - 1n) * (q - 1n);\n const base = randomBigInt(modulus - 2n, modulusByteLength) + 2n;\n const exponent = modExp(2n, t, phi);\n const solution = modExp(base, exponent, modulus);\n\n return { puzzle: { modulusByteLength, modulus, base, time: t }, solution };\n}\n\nexport function solve({ modulus, base, time }: Puzzle): bigint {\n for (let i = 0n; i < time; i++) {\n base = (base * base) % modulus;\n }\n return base;\n}\n","import { decrypt, encrypt } from './cipher.js';\nimport { bigIntToBytes, bytesToEnvelope, envelopeToBytes } from './io.js';\nimport { mint, solve } from './puzzle.js';\nimport type { Cipher, PuzzleParams } from './types.js';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nexport async function sealFromPrimes(\n plaintext: string,\n p: bigint,\n q: bigint,\n puzzleParams: PuzzleParams,\n): Promise<Uint8Array<ArrayBuffer>> {\n const payload = encoder.encode(plaintext);\n const { puzzle, solution } = mint(p, q, puzzleParams);\n const keyData = bigIntToBytes(solution, puzzle.modulusByteLength);\n\n let cipher: Cipher;\n try {\n cipher = await encrypt(payload, keyData);\n } finally {\n keyData.fill(0);\n }\n\n return envelopeToBytes({ v: 1, ...puzzle, ...cipher });\n}\n\nexport async function unsealFromBytes(\n bytes: Uint8Array<ArrayBuffer>,\n): Promise<string> {\n const envelope = bytesToEnvelope(bytes);\n const solution = solve(envelope);\n const keyData = bigIntToBytes(solution, envelope.modulusByteLength);\n\n let payload: Uint8Array<ArrayBuffer>;\n try {\n payload = await decrypt(envelope, keyData);\n } finally {\n keyData.fill(0);\n }\n\n return decoder.decode(payload);\n}\n","export function bytesToBase64Url(bytes: Uint8Array): string {\n if ('toBase64' in bytes && typeof bytes.toBase64 === 'function') {\n return bytes.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n\n const CHUNK_SIZE = 0x4000;\n let binaryString = '';\n for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {\n const chunk = bytes.subarray(i, i + CHUNK_SIZE);\n binaryString += String.fromCharCode(...chunk);\n }\n\n const base64 = btoa(binaryString);\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function base64UrlToBytes(base64Url: string): Uint8Array<ArrayBuffer> {\n if (\n 'fromBase64' in Uint8Array &&\n typeof Uint8Array.fromBase64 === 'function'\n ) {\n return Uint8Array.fromBase64(base64Url, { alphabet: 'base64url' });\n }\n\n let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n base64 += '=='.slice((base64.length + 2) % 4);\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n","import { SEAL_DEFAULTS } from '../core/defaults.js';\nimport { sealFromPrimes, unsealFromBytes } from '../core/index.js';\nimport { bytesToBigInt } from '../core/io.js';\nimport type { SealOptions, UnsealInWorkerOptions } from '../core/types.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './codec.js';\n\nexport type { SealOptions, UnsealInWorkerOptions };\n\n/**\n * Seal plaintext using a time-lock puzzle.\n *\n * @param plaintext - The plaintext to seal.\n * @param options - Optional configuration options.\n * @returns A Base64URL-encoded envelope.\n */\nexport async function seal(\n plaintext: string,\n options?: SealOptions,\n): Promise<string> {\n const config = { ...SEAL_DEFAULTS, ...options };\n\n const keyPair = await globalThis.crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: config.modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256',\n },\n true,\n ['decrypt'],\n );\n const jwk = await globalThis.crypto.subtle.exportKey(\n 'jwk',\n keyPair.privateKey,\n );\n\n if (!jwk.p || !jwk.q) throw new Error('RSA JWK is missing primes p or q');\n const p = bytesToBigInt(base64UrlToBytes(jwk.p));\n const q = bytesToBigInt(base64UrlToBytes(jwk.q));\n\n return bytesToBase64Url(await sealFromPrimes(plaintext, p, q, config));\n}\n\n/**\n * Unseal an envelope by solving its time-lock puzzle.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @returns The decrypted plaintext.\n */\nexport async function unseal(envelope: string): Promise<string> {\n if (!globalThis.crypto?.subtle)\n throw new Error('Web Crypto API is not available');\n\n return await unsealFromBytes(base64UrlToBytes(envelope));\n}\n\n/**\n * Unseal an envelope in a web worker.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @param options - Optional configuration options.\n * @returns The decrypted plaintext.\n */\nexport function unsealInWorker(\n envelope: string,\n options?: UnsealInWorkerOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n if (options?.signal?.aborted) return reject(options.signal.reason);\n options?.signal?.addEventListener('abort', handleAbort);\n\n const worker = new Worker(new URL('./worker.js', import.meta.url), {\n type: 'module',\n });\n\n const cleanup = () => {\n worker.terminate();\n options?.signal?.removeEventListener('abort', handleAbort);\n };\n\n worker.onmessage = (event) => {\n if (event.data.success) resolve(event.data.plaintext);\n else reject(event.data.error);\n cleanup();\n };\n\n worker.onerror = (errorEvent) => {\n errorEvent.preventDefault();\n reject(errorEvent.error ?? new Error(errorEvent.message));\n cleanup();\n };\n\n function handleAbort(event: Event) {\n reject((event.target as AbortSignal).reason);\n cleanup();\n }\n\n worker.postMessage(envelope);\n });\n}\n"],"mappings":"AAEA,MAAaA,EAAuC,CAClD,KAAM,KACN,cAAe,IACjB,ECHMC,EAAa,IAAI,YAAY,CAAC,CAAC,OAAO,eAAe,EAE3D,eAAeC,EACbC,EACAC,EACoB,CACpB,IAAMC,EAAU,MAAM,WAAW,OAAO,OAAO,UAC7C,MACAF,EACA,OACA,GACA,CAAC,WAAW,CACd,EAEA,OAAO,MAAM,WAAW,OAAO,OAAO,UACpC,CAAE,KAAM,OAAQ,KAAM,UAAiBC,OAAM,KAAMH,CAAW,EAC9DI,EACA,CAAE,KAAM,UAAW,OAAQ,GAAI,EAC/B,GACA,CAAC,UAAW,SAAS,CACvB,CACF,CAEA,eAAsBC,EACpBC,EACAJ,EACiB,CACjB,IAAMC,EAAO,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,EAC3DI,EAAK,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,EAEzDC,EAAa,MAAMP,EAAUC,EAASC,CAAI,EAShD,MAAO,CAAEA,OAAMI,KAAI,WAAA,IARI,WACrB,MAAM,WAAW,OAAO,OAAO,QAC7B,CAAE,KAAM,UAAWA,IAAG,EACtBC,EACAF,CACF,CAG0B,CAAE,CAChC,CAEA,eAAsBG,EACpBC,EACAR,EACkC,CAClC,IAAMM,EAAa,MAAMP,EAAUC,EAASQ,EAAO,IAAI,EACvD,OAAO,IAAI,WACT,MAAM,WAAW,OAAO,OAAO,QAC7B,CAAE,KAAM,UAAW,GAAIA,EAAO,EAAG,EACjCF,EACAE,EAAO,UACT,CACF,CACF,CCtDA,MAAMC,EAAc,IAAI,WAAW,CAAC,IAAM,GAAM,GAAI,CAAC,EAErD,IA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OP,EAAQ,OAAO,MAAM,EACjEA,GAAS,QAAQ,iBAAiB,QAASQ,CAAW,EAEtD,IAAAC,EAAA,IAAA,gBAAA,IAAA,KAAA,CAAA,s9EAAA,EAAA,CAAA,KAAA,wBAAA,CAAA,CAAA,EAAAC,EAAA,IAAA,OAAAD,CAAA,EAAA,IAAA,gBAAAA,CAAA,EAIA,IAAME,MAAgB,CACpBD,EAAO,UAAU,EACjBV,GAAS,QAAQ,oBAAoB,QAASQ,CAAW,CAC3D,EAEAE,EAAO,UAAaE,GAAU,CACxBA,EAAM,KAAK,QAASN,EAAQM,EAAM,KAAK,SAAS,EAC/CL,EAAOK,EAAM,KAAK,KAAK,EAC5BD,EAAQ,CACV,EAEAD,EAAO,QAAWG,GAAe,CAC/BA,EAAW,eAAe,EAC1BN,EAAOM,EAAW,OAAa,MAAMA,EAAW,OAAO,CAAC,EACxDF,EAAQ,CACV,EAEA,SAASH,EAAYI,EAAc,CACjCL,EAAQK,EAAM,OAAuB,MAAM,EAC3CD,EAAQ,CACV,CAEAD,EAAO,YAAYpB,CAAQ,CAC7B,CAAC,CACH,C"}
|
|
1
|
+
{"version":3,"file":"treadwheel.min.js","names":["SEAL_DEFAULTS","deriveKey","keyData","salt","version","info","baseKey","encrypt","payload","iv","derivedKey","decrypt","cipher","MAGIC_BYTES","BinaryCursor","bytes","BinaryReader","value","length","until","BinaryWriter","buffer","bytesToBigInt","result","i","bigIntToBytes","bigint","byteLength","shift","envelopeToBytes","v","modulusByteLength","baseByteLength","time","modulus","base","ciphertext","totalSize","writer","bytesToEnvelope","reader","b","ciphertextLength","modExp","exponent","randomBigInt","strictUpperBound","randomBytes","mint","p","q","modulusLength","randomBase","t","solution","solve","encoder","decoder","sealFromPrimes","plaintext","puzzleParams","puzzle","unsealFromBytes","envelope","bytesToBase64Url","CHUNK_SIZE","binaryString","chunk","base64UrlToBytes","base64Url","base64","char","seal","options","config","keyPair","jwk","unseal","unsealInWorker","resolve","reject","handleAbort","url","worker","cleanup","event","errorEvent"],"sources":["../src/core/defaults.ts","../src/core/cipher.ts","../src/core/io.ts","../src/core/puzzle.ts","../src/core/index.ts","../src/browser/codec.ts","../src/browser/index.ts"],"sourcesContent":["import type { SealOptions } from './types.js';\n\nexport const SEAL_DEFAULTS: Required<SealOptions> = {\n time: 250_000,\n modulusLength: 2048,\n randomBase: false,\n};\n","import type { Cipher, CipherV2 } from './types.js';\n\nasync function deriveKey(\n keyData: BufferSource,\n salt: BufferSource,\n version: number,\n): Promise<CryptoKey> {\n const info = new TextEncoder().encode(`treadwheel-v${version}`);\n const baseKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n keyData,\n 'HKDF',\n false,\n ['deriveKey'],\n );\n\n return await globalThis.crypto.subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n baseKey,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nexport async function encrypt(\n payload: Uint8Array<ArrayBuffer>,\n keyData: BufferSource,\n): Promise<CipherV2> {\n const v = 2;\n const salt = globalThis.crypto.getRandomValues(new Uint8Array(32));\n const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));\n\n const derivedKey = await deriveKey(keyData, salt, v);\n const ciphertext = new Uint8Array(\n await globalThis.crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n derivedKey,\n payload,\n ),\n );\n\n return { v, salt, iv, ciphertext };\n}\n\nexport async function decrypt(\n cipher: Cipher,\n keyData: BufferSource,\n): Promise<Uint8Array<ArrayBuffer>> {\n const derivedKey = await deriveKey(keyData, cipher.salt, cipher.v);\n return new Uint8Array(\n await globalThis.crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: cipher.iv },\n derivedKey,\n cipher.ciphertext,\n ),\n );\n}\n","import type { Envelope, EnvelopeV2 } from './types.js';\n\nconst MAGIC_BYTES = new Uint8Array([0xb7, 0x0f, 0xff]);\n\nclass BinaryCursor {\n protected view: DataView;\n protected bytes: Uint8Array<ArrayBuffer>;\n protected offset: number = 0;\n\n constructor(bytes: Uint8Array<ArrayBuffer>) {\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n}\n\nclass BinaryReader extends BinaryCursor {\n public readUint8(): number {\n return this.view.getUint8(this.offset++);\n }\n\n public readUint16(): number {\n const value = this.view.getUint16(this.offset);\n this.offset += 2;\n return value;\n }\n\n public readUint32(): number {\n const value = this.view.getUint32(this.offset);\n this.offset += 4;\n return value;\n }\n\n public readBigUInt64(): bigint {\n const value = this.view.getBigUint64(this.offset);\n this.offset += 8;\n return value;\n }\n\n public readBytes(length: number): Uint8Array<ArrayBuffer> {\n const until = this.offset + length;\n if (until > this.bytes.byteLength)\n throw new Error('Malformed envelope: unexpected end of data');\n\n const bytes = this.bytes.subarray(this.offset, until);\n this.offset = until;\n return bytes;\n }\n}\n\nclass BinaryWriter extends BinaryCursor {\n public writeUint8(value: number): void {\n this.view.setUint8(this.offset++, value);\n }\n\n public writeUint16(value: number): void {\n this.view.setUint16(this.offset, value);\n this.offset += 2;\n }\n\n public writeUint32(value: number): void {\n this.view.setUint32(this.offset, value);\n this.offset += 4;\n }\n\n public writeBigUInt64(value: bigint): void {\n this.view.setBigUint64(this.offset, BigInt(value));\n this.offset += 8;\n }\n\n public writeBytes(buffer: Uint8Array): void {\n this.bytes.set(buffer, this.offset);\n this.offset += buffer.byteLength;\n }\n}\n\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n let result = 0n;\n for (let i = 0; i < bytes.length; i++) {\n result = (result << 8n) | BigInt(bytes[i] as number);\n }\n return result;\n}\n\nexport function bigIntToBytes(\n bigint: bigint,\n byteLength: number,\n): Uint8Array<ArrayBuffer> {\n const buffer = new Uint8Array(byteLength);\n for (let i = 0; i < byteLength; i++) {\n const shift = BigInt((byteLength - 1 - i) * 8);\n buffer[i] = Number((bigint >> shift) & 0xffn);\n }\n return buffer;\n}\n\nexport function envelopeToBytes({\n v,\n modulusByteLength,\n baseByteLength,\n time,\n modulus,\n base,\n salt,\n iv,\n ciphertext,\n}: EnvelopeV2): Uint8Array<ArrayBuffer> {\n // magic bytes, 1 version, 8 for t, 2 mod length, 2 base length, 4 ct length\n const headerSize = MAGIC_BYTES.byteLength + 17;\n const totalSize =\n headerSize +\n modulusByteLength +\n baseByteLength +\n salt.byteLength +\n iv.byteLength +\n ciphertext.byteLength;\n\n const bytes = new Uint8Array(totalSize);\n const writer = new BinaryWriter(bytes);\n\n writer.writeBytes(MAGIC_BYTES);\n writer.writeUint8(v);\n\n writer.writeUint16(modulusByteLength);\n writer.writeUint16(baseByteLength);\n writer.writeUint32(ciphertext.byteLength);\n\n writer.writeBigUInt64(time);\n writer.writeBytes(bigIntToBytes(modulus, modulusByteLength));\n writer.writeBytes(bigIntToBytes(base, baseByteLength));\n\n writer.writeBytes(salt);\n writer.writeBytes(iv);\n writer.writeBytes(ciphertext);\n\n return bytes;\n}\n\nexport function bytesToEnvelope(bytes: Uint8Array<ArrayBuffer>): Envelope {\n const reader = new BinaryReader(bytes);\n\n const magicBytes = reader.readBytes(MAGIC_BYTES.byteLength);\n if (!magicBytes.every((b, i) => b === MAGIC_BYTES[i]))\n throw new Error('Invalid envelope: magic bytes mismatch');\n\n const v = reader.readUint8();\n if (v !== 1 && v !== 2) throw new Error(`Unsupported envelope version ${v}`);\n\n const modulusByteLength = reader.readUint16();\n const baseByteLength = v === 1 ? modulusByteLength : reader.readUint16();\n const ciphertextLength = reader.readUint32();\n\n const time = reader.readBigUInt64();\n const modulus = bytesToBigInt(reader.readBytes(modulusByteLength));\n const base = bytesToBigInt(reader.readBytes(baseByteLength));\n\n const salt = reader.readBytes(32);\n const iv = reader.readBytes(12);\n const ciphertext = reader.readBytes(ciphertextLength);\n\n return {\n v,\n modulusByteLength,\n baseByteLength,\n modulus,\n base,\n time,\n salt,\n iv,\n ciphertext,\n };\n}\n","import { bytesToBigInt } from './io.js';\nimport type { Puzzle, PuzzleParams } from './types.js';\n\nfunction modExp(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n for (; exponent > 0n; exponent >>= 1n) {\n if (exponent & 1n) result = (result * base) % modulus;\n base = (base * base) % modulus;\n }\n return result;\n}\n\nfunction randomBigInt(strictUpperBound: bigint, byteLength: number): bigint {\n // Oversample by 16 bytes to reduce modulo bias\n const randomBytes = new Uint8Array(byteLength + 16);\n globalThis.crypto.getRandomValues(randomBytes);\n return bytesToBigInt(randomBytes) % strictUpperBound;\n}\n\nexport function mint(\n p: bigint,\n q: bigint,\n { time, modulusLength, randomBase }: PuzzleParams,\n): { puzzle: Puzzle; solution: bigint } {\n if (!Number.isSafeInteger(time) || time < 0)\n throw new RangeError(\"Option 'time' must be a non-negative safe integer\");\n\n const t = BigInt(time);\n\n const modulusByteLength = Math.ceil(modulusLength / 8);\n const modulus = p * q;\n\n const baseByteLength = randomBase ? modulusByteLength : 1;\n const base = randomBase ? randomBigInt(modulus, baseByteLength) : 2n;\n\n const phi = (p - 1n) * (q - 1n);\n const exponent = modExp(2n, t, phi);\n const solution = modExp(base, exponent, modulus);\n\n return {\n puzzle: { modulusByteLength, baseByteLength, modulus, base, time: t },\n solution,\n };\n}\n\nexport function solve({ modulus, base, time }: Puzzle): bigint {\n for (let i = 0n; i < time; i++) {\n base = (base * base) % modulus;\n }\n return base;\n}\n","import { decrypt, encrypt } from './cipher.js';\nimport { bigIntToBytes, bytesToEnvelope, envelopeToBytes } from './io.js';\nimport { mint, solve } from './puzzle.js';\nimport type { CipherV2, PuzzleParams } from './types.js';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nexport async function sealFromPrimes(\n plaintext: string,\n p: bigint,\n q: bigint,\n puzzleParams: PuzzleParams,\n): Promise<Uint8Array<ArrayBuffer>> {\n const payload = encoder.encode(plaintext);\n const { puzzle, solution } = mint(p, q, puzzleParams);\n const keyData = bigIntToBytes(solution, puzzle.modulusByteLength);\n\n let cipher: CipherV2;\n try {\n cipher = await encrypt(payload, keyData);\n } finally {\n keyData.fill(0);\n }\n\n return envelopeToBytes({ ...puzzle, ...cipher });\n}\n\nexport async function unsealFromBytes(\n bytes: Uint8Array<ArrayBuffer>,\n): Promise<string> {\n const envelope = bytesToEnvelope(bytes);\n const solution = solve(envelope);\n const keyData = bigIntToBytes(solution, envelope.modulusByteLength);\n\n let payload: Uint8Array<ArrayBuffer>;\n try {\n payload = await decrypt(envelope, keyData);\n } finally {\n keyData.fill(0);\n }\n\n return decoder.decode(payload);\n}\n","export function bytesToBase64Url(bytes: Uint8Array): string {\n if ('toBase64' in bytes && typeof bytes.toBase64 === 'function') {\n return bytes.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n\n const CHUNK_SIZE = 0x4000;\n let binaryString = '';\n for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {\n const chunk = bytes.subarray(i, i + CHUNK_SIZE);\n binaryString += String.fromCharCode(...chunk);\n }\n\n const base64 = btoa(binaryString);\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function base64UrlToBytes(base64Url: string): Uint8Array<ArrayBuffer> {\n if (\n 'fromBase64' in Uint8Array &&\n typeof Uint8Array.fromBase64 === 'function'\n ) {\n return Uint8Array.fromBase64(base64Url, { alphabet: 'base64url' });\n }\n\n let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n base64 += '=='.slice((base64.length + 2) % 4);\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n","import { SEAL_DEFAULTS } from '../core/defaults.js';\nimport { sealFromPrimes, unsealFromBytes } from '../core/index.js';\nimport { bytesToBigInt } from '../core/io.js';\nimport type { SealOptions, UnsealInWorkerOptions } from '../core/types.js';\nimport { base64UrlToBytes, bytesToBase64Url } from './codec.js';\n\nexport type { SealOptions, UnsealInWorkerOptions };\n\n/**\n * Seal plaintext using a time-lock puzzle.\n *\n * @param plaintext - The plaintext to seal.\n * @param options - Optional configuration options.\n * @returns A Base64URL-encoded envelope.\n */\nexport async function seal(\n plaintext: string,\n options?: SealOptions,\n): Promise<string> {\n const config = { ...SEAL_DEFAULTS, ...options };\n\n const keyPair = await globalThis.crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: config.modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256',\n },\n true,\n ['decrypt'],\n );\n const jwk = await globalThis.crypto.subtle.exportKey(\n 'jwk',\n keyPair.privateKey,\n );\n\n if (!jwk.p || !jwk.q) throw new Error('RSA JWK is missing primes p or q');\n const p = bytesToBigInt(base64UrlToBytes(jwk.p));\n const q = bytesToBigInt(base64UrlToBytes(jwk.q));\n\n return bytesToBase64Url(await sealFromPrimes(plaintext, p, q, config));\n}\n\n/**\n * Unseal an envelope by solving its time-lock puzzle.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @returns The decrypted plaintext.\n */\nexport async function unseal(envelope: string): Promise<string> {\n if (!globalThis.crypto?.subtle)\n throw new Error('Web Crypto API is not available');\n\n return await unsealFromBytes(base64UrlToBytes(envelope));\n}\n\n/**\n * Unseal an envelope in a web worker.\n *\n * @param envelope - A Base64URL-encoded envelope.\n * @param options - Optional configuration options.\n * @returns The decrypted plaintext.\n */\nexport function unsealInWorker(\n envelope: string,\n options?: UnsealInWorkerOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n if (options?.signal?.aborted) return reject(options.signal.reason);\n options?.signal?.addEventListener('abort', handleAbort);\n\n const worker = new Worker(new URL('./worker.js', import.meta.url), {\n type: 'module',\n });\n\n const cleanup = () => {\n worker.terminate();\n options?.signal?.removeEventListener('abort', handleAbort);\n };\n\n worker.onmessage = (event) => {\n if (event.data.success) resolve(event.data.plaintext);\n else reject(event.data.error);\n cleanup();\n };\n\n worker.onerror = (errorEvent) => {\n errorEvent.preventDefault();\n reject(errorEvent.error ?? new Error(errorEvent.message));\n cleanup();\n };\n\n function handleAbort(event: Event) {\n reject((event.target as AbortSignal).reason);\n cleanup();\n }\n\n worker.postMessage(envelope);\n });\n}\n"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AAW,EAEtD,IAAAC,EAAA,IAAA,gBAAA,IAAA,KAAA,CAAA,ghFAAA,EAAA,CAAA,KAAA,wBAAA,CAAA,CAAA,EAAAC,EAAA,IAAA,OAAAD,CAAA,EAAA,IAAA,gBAAAA,CAAA,EAIA,IAAME,MAAgB,CACpBD,EAAO,UAAU,EACjBV,GAAS,QAAQ,oBAAoB,QAASQ,CAAW,CAC3D,EAEAE,EAAO,UAAaE,GAAU,CACxBA,EAAM,KAAK,QAASN,EAAQM,EAAM,KAAK,SAAS,EAC/CL,EAAOK,EAAM,KAAK,KAAK,EAC5BD,EAAQ,CACV,EAEAD,EAAO,QAAWG,GAAe,CAC/BA,EAAW,eAAe,EAC1BN,EAAOM,EAAW,OAAa,MAAMA,EAAW,OAAO,CAAC,EACxDF,EAAQ,CACV,EAEA,SAASH,EAAYI,EAAc,CACjCL,EAAQK,EAAM,OAAuB,MAAM,EAC3CD,EAAQ,CACV,CAEAD,EAAO,YAAYpB,CAAQ,CAC7B,CAAC,CACH,C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "treadwheel",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Time-release encryption to protect sensitive information from bots",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"anti-scraping",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"dist"
|
|
51
51
|
],
|
|
52
52
|
"scripts": {
|
|
53
|
-
"build": "pnpm clean && tsc && tsdown",
|
|
54
|
-
"check": "tsc
|
|
53
|
+
"build": "pnpm clean && tsc -p tsconfig.build.json && tsdown",
|
|
54
|
+
"check": "tsc",
|
|
55
55
|
"clean": "rimraf dist",
|
|
56
56
|
"format": "biome format --write",
|
|
57
57
|
"lint": "biome check",
|
|
@@ -65,11 +65,11 @@
|
|
|
65
65
|
"docs:preview": "vitepress preview docs"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
|
-
"@biomejs/biome": "2.
|
|
68
|
+
"@biomejs/biome": "2.6.9",
|
|
69
69
|
"@lit-labs/rollup-plugin-minify-html-literals": "^0.2.0",
|
|
70
|
-
"@types/node": "^26.6.
|
|
71
|
-
"@vitest/browser-playwright": "^5.1.
|
|
72
|
-
"@vitest/coverage-istanbul": "^5.1.
|
|
70
|
+
"@types/node": "^26.6.11",
|
|
71
|
+
"@vitest/browser-playwright": "^5.1.2",
|
|
72
|
+
"@vitest/coverage-istanbul": "^5.1.2",
|
|
73
73
|
"execa": "^10.2.1",
|
|
74
74
|
"magic-string": "^1.4.5",
|
|
75
75
|
"nyc": "^18.0.0",
|
|
@@ -79,11 +79,11 @@
|
|
|
79
79
|
"tsx": "^4.23.15",
|
|
80
80
|
"typedoc": "^0.28.20",
|
|
81
81
|
"typedoc-plugin-markdown": "^4.14.1",
|
|
82
|
-
"typescript": "^
|
|
82
|
+
"typescript": "^6.0.3",
|
|
83
83
|
"vitepress": "^1.6.4",
|
|
84
|
-
"vitest": "^5.1.
|
|
84
|
+
"vitest": "^5.1.2"
|
|
85
85
|
},
|
|
86
|
-
"packageManager": "pnpm@12.
|
|
86
|
+
"packageManager": "pnpm@12.25.1",
|
|
87
87
|
"engines": {
|
|
88
88
|
"node": ">=22.0.0"
|
|
89
89
|
}
|