treadwheel 1.0.5 → 1.1.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.
@@ -13,16 +13,26 @@ template.innerHTML = html `
13
13
  box-sizing: border-box;
14
14
  width: 300px;
15
15
  max-width: 100%;
16
- border: 1px solid rgba(0, 0, 0, 0.12);
17
- border-radius: 10px;
16
+
17
+ color-scheme: inherit;
18
18
  color: #111;
19
+ color: light-dark(#111, #eee);
19
20
  background: #fff;
20
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
21
+ background: light-dark(#fff, #111);
22
+
23
+ border: 1px solid #0002;
24
+ border-color: light-dark(#0002, #fff3);
25
+ border-radius: 10px;
26
+ box-shadow: 0 1px 2px #0001;
27
+ box-shadow: 0 1px 2px light-dark(#0001, #0006);
28
+
29
+ font-size: 16px;
30
+ line-height: 1.25;
21
31
  font-family:
22
32
  Inter, Roboto, "Helvetica Neue", "Arial Nova", "Nimbus Sans", Arial,
23
33
  sans-serif;
24
- font-size: 16px;
25
- line-height: 1.25;
34
+
35
+ -webkit-user-select: none;
26
36
  user-select: none;
27
37
  }
28
38
 
@@ -106,25 +116,27 @@ template.innerHTML = html `
106
116
  width: 24px;
107
117
  height: 24px;
108
118
  margin-top: -10px;
109
- border: 1px solid #bbb;
119
+
120
+ border: 1px solid #aaa;
121
+ border-color: light-dark(#aaa, #777);
110
122
  border-radius: 6px;
111
123
  }
112
124
 
113
125
  :host([status="processing"]) #status::before {
114
126
  border-radius: 50%;
115
- border-color: transparent transparent #111 #111;
127
+ border-color: currentColor currentColor transparent transparent;
116
128
  animation: spin 1s linear infinite;
117
129
  }
118
130
 
119
131
  :host([status="success"]) #status::before {
120
- border-color: #16a34a;
121
- background-color: #16a34a;
132
+ border-color: #285;
133
+ background-color: #285;
122
134
  background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==");
123
135
  }
124
136
 
125
137
  :host([status="error"]) #status::before {
126
- border-color: #dc2626;
127
- background-color: #dc2626;
138
+ border-color: #d34;
139
+ background-color: #d34;
128
140
  background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE3IDcgNyAxN003IDdsMTAgMTAiLz48L3N2Zz4=");
129
141
  }
130
142
 
@@ -132,6 +144,7 @@ template.innerHTML = html `
132
144
  text-align: right;
133
145
  font-size: 12px;
134
146
  color: #666;
147
+ color: light-dark(#666, #999);
135
148
  padding: 2px 9px 7px 9px;
136
149
  }
137
150
 
@@ -205,7 +218,7 @@ class TreadwheelWidget extends HTMLElement {
205
218
  slot.name = '_output';
206
219
  const purge = () => {
207
220
  this._shadow.replaceChildren(style, slot);
208
- this.childNodes.forEach((node) => {
221
+ [...this.childNodes].forEach((node) => {
209
222
  if (node !== output)
210
223
  node.remove();
211
224
  });
@@ -2,15 +2,20 @@ import crypto from 'node:crypto';
2
2
  import { Worker } from 'node:worker_threads';
3
3
  import { SEAL_DEFAULTS } from '../core/defaults.js';
4
4
  import { sealFromPrimes, unsealFromBytes } from '../core/index.js';
5
- function generatePrimeAsync(size) {
5
+ import { bytesToBigInt } from '../core/io.js';
6
+ function generatePrimesAsync(modulusLength) {
6
7
  return new Promise((resolve, reject) => {
7
- const callback = (err, prime) => {
8
+ const callback = (err, _publicKey, privateKey) => {
8
9
  if (err)
9
- reject(err);
10
- else
11
- resolve(prime);
10
+ return reject(err);
11
+ const jwk = privateKey.export({ format: 'jwk' });
12
+ if (!jwk.p || !jwk.q)
13
+ return reject(new Error('RSA JWK is missing primes p or q'));
14
+ const p = bytesToBigInt(Buffer.from(jwk.p, 'base64url'));
15
+ const q = bytesToBigInt(Buffer.from(jwk.q, 'base64url'));
16
+ resolve({ p, q });
12
17
  };
13
- crypto.generatePrime(size, { bigint: true }, callback);
18
+ crypto.generateKeyPair('rsa', { modulusLength }, callback);
14
19
  });
15
20
  }
16
21
  /**
@@ -22,12 +27,7 @@ function generatePrimeAsync(size) {
22
27
  */
23
28
  export async function seal(plaintext, options) {
24
29
  const config = { ...SEAL_DEFAULTS, ...options };
25
- const pLength = Math.ceil(config.modulusLength / 2);
26
- const qLength = config.modulusLength - pLength;
27
- const [p, q] = await Promise.all([
28
- generatePrimeAsync(pLength),
29
- generatePrimeAsync(qLength),
30
- ]);
30
+ const { p, q } = await generatePrimesAsync(config.modulusLength);
31
31
  const envelope = await sealFromPrimes(plaintext, p, q, config);
32
32
  return Buffer.from(envelope).toString('base64url');
33
33
  }
@@ -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 e=new TextEncoder().encode(`treadwheel-v1`);async function t(t,n){let r=await globalThis.crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:n,info:e},r,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function n(e,n){let r=await t(n,e.salt);return new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:e.iv},r,e.ciphertext))}let r=new Uint8Array([183,15,255]);var i=class{constructor(e){this.offset=0,this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}},a=class extends i{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 o(e){let t=0n;for(let n=0;n<e.length;n++)t=t<<8n|BigInt(e[n]);return t}function s(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 c(e){let t=new a(e);if(!t.readBytes(r.byteLength).every((e,t)=>e===r[t]))throw Error(`Invalid envelope: magic bytes mismatch`);let n=t.readUint8();if(n!==1)throw Error(`Unsupported envelope version ${n}`);let i=t.readUint16(),s=t.readUint32();return{v:n,modulusByteLength:i,time:t.readBigUInt64(),modulus:o(t.readBytes(i)),base:o(t.readBytes(i)),salt:t.readBytes(32),iv:t.readBytes(12),ciphertext:t.readBytes(s)}}function l({modulus:e,base:t,time:n}){for(let r=0n;r<n;r++)t=t*t%e;return t}new TextEncoder;let u=new TextDecoder;async function d(e){let t=c(e),r=s(l(t),t.modulusByteLength),i;try{i=await n(t,r)}finally{r.fill(0)}return u.decode(i)}function f(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 p(e){if(!globalThis.crypto?.subtle)throw Error(`Web Crypto API is not available`);return await d(f(e))}self.onmessage=async e=>{try{let t=await p(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%;border:1px solid rgba(0,0,0,.12);border-radius:10px;color:#111;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.06);font-family:Inter,Roboto,"Helvetica Neue","Arial Nova","Nimbus Sans",Arial,sans-serif;font-size:16px;line-height:1.25;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 #bbb;border-radius:6px}:host([status=processing]) #status::before{border-radius:50%;border-color:transparent transparent #111 #111;animation:spin 1s linear infinite}:host([status=success]) #status::before{border-color:#16a34a;background-color:#16a34a;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==")}:host([status=error]) #status::before{border-color:#dc2626;background-color:#dc2626;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE3IDcgNyAxN003IDdsMTAgMTAiLz48L3N2Zz4=")}footer{text-align:right;font-size:12px;color:#666;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);
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 e=new TextEncoder().encode(`treadwheel-v1`);async function t(t,n){let r=await globalThis.crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:n,info:e},r,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function n(e,n){let r=await t(n,e.salt);return new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:e.iv},r,e.ciphertext))}let r=new Uint8Array([183,15,255]);var i=class{constructor(e){this.offset=0,this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}},a=class extends i{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 o(e){let t=0n;for(let n=0;n<e.length;n++)t=t<<8n|BigInt(e[n]);return t}function s(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 c(e){let t=new a(e);if(!t.readBytes(r.byteLength).every((e,t)=>e===r[t]))throw Error(`Invalid envelope: magic bytes mismatch`);let n=t.readUint8();if(n!==1)throw Error(`Unsupported envelope version ${n}`);let i=t.readUint16(),s=t.readUint32();return{v:n,modulusByteLength:i,time:t.readBigUInt64(),modulus:o(t.readBytes(i)),base:o(t.readBytes(i)),salt:t.readBytes(32),iv:t.readBytes(12),ciphertext:t.readBytes(s)}}function l({modulus:e,base:t,time:n}){for(let r=0n;r<n;r++)t=t*t%e;return t}new TextEncoder;let u=new TextDecoder;async function d(e){let t=c(e),r=s(l(t),t.modulusByteLength),i;try{i=await n(t,r)}finally{r.fill(0)}return u.decode(i)}function f(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 p(e){if(!globalThis.crypto?.subtle)throw Error(`Web Crypto API is not available`);return await d(f(e))}self.onmessage=async e=>{try{let t=await p(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","options","reject","handleAbort","url","worker","cleanup","event","resolve","errorEvent","envelope","html","template","TreadwheelWidget","e","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 border: 1px solid rgba(0, 0, 0, 0.12);\n border-radius: 10px;\n color: #111;\n background: #fff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);\n font-family:\n Inter, Roboto, \"Helvetica Neue\", \"Arial Nova\", \"Nimbus Sans\", Arial,\n sans-serif;\n font-size: 16px;\n line-height: 1.25;\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 border: 1px solid #bbb;\n border-radius: 6px;\n }\n\n :host([status=\"processing\"]) #status::before {\n border-radius: 50%;\n border-color: transparent transparent #111 #111;\n animation: spin 1s linear infinite;\n }\n\n :host([status=\"success\"]) #status::before {\n border-color: #16a34a;\n background-color: #16a34a;\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDgtOCA5LTQtNCIvPjwvc3ZnPg==\");\n }\n\n :host([status=\"error\"]) #status::before {\n border-color: #dc2626;\n background-color: #dc2626;\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 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,EACd,EACA,EACiB,CACjB,OA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AAY,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,OA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,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 +1 @@
1
- {"version":3,"file":"treadwheel.min.js","names":["SEAL_DEFAULTS","INFO_BYTES","deriveKey","baseKey","keyData","encrypt","salt","iv","derivedKey","payload","decrypt","cipher","MAGIC_BYTES","BinaryCursor","bytes","BinaryReader","value","until","length","BinaryWriter","buffer","bytesToBigInt","result","i","bigIntToBytes","byteLength","shift","bigint","envelopeToBytes","totalSize","modulusByteLength","ciphertext","writer","v","time","modulus","base","bytesToEnvelope","reader","b","ciphertextLength","modExp","exponent","randomBigInt","randomBytes","strictUpperBound","mint","t","modulusLength","p","q","phi","solution","solve","encoder","decoder","sealFromPrimes","plaintext","puzzleParams","puzzle","unsealFromBytes","envelope","bytesToBase64Url","CHUNK_SIZE","binaryString","chunk","base64UrlToBytes","base64Url","base64","char","seal","config","options","keyPair","jwk","unseal","unsealInWorker","reject","handleAbort","url","worker","cleanup","event","resolve","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,EACb,EACA,EACoB,CACpB,IAAMC,EAAU,MAAM,WAAW,OAAO,OAAO,UAC7C,MACAC,EACA,OACA,GACA,CAAC,WAAW,CACd,EAEA,OAAO,MAAM,WAAW,OAAO,OAAO,UACpC,CAAE,KAAM,OAAQ,KAAM,UAAiB,OAAM,KAAMH,CAAW,EAC9DE,EACA,CAAE,KAAM,UAAW,OAAQ,GAAI,EAC/B,GACA,CAAC,UAAW,SAAS,CACvB,CACF,CAEA,eAAsBE,EACpB,EACA,EACiB,CACjB,IAAMC,EAAO,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,EAC3DC,EAAK,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,EAEzDC,EAAa,MAAMN,EAAUE,EAASE,CAAI,EAShD,MAAO,CAAE,OAAM,KAAI,WAAA,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CAEa,EAAGH,CAAM,CAAC,CACvE,CAQA,eAAsBI,EAAO,EAAmC,CAC9D,GAAI,CAAC,WAAW,QAAQ,OACtB,MAAU,MAAM,iCAAiC,EAEnD,OAAO,MAAMf,EAAgBM,EAAiBL,CAAQ,CAAC,CACzD,CASA,SAAgBe,EACd,EACA,EACiB,CACjB,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,GAAIJ,GAAS,QAAQ,QAAS,OAAOK,EAAOL,EAAQ,OAAO,MAAM,EACjEA,GAAS,QAAQ,iBAAiB,QAASM,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,EACjBR,GAAS,QAAQ,oBAAoB,QAASM,CAAW,CAC3D,EAEA,EAAO,UAAa,GAAU,CACxBI,EAAM,KAAK,QAASC,EAAQD,EAAM,KAAK,SAAS,EAC/CL,EAAOK,EAAM,KAAK,KAAK,EAC5BD,EAAQ,CACV,EAEA,EAAO,QAAW,GAAe,CAC/BG,EAAW,eAAe,EAC1BP,EAAOO,EAAW,OAAa,MAAMA,EAAW,OAAO,CAAC,EACxDH,EAAQ,CACV,EAEA,SAASH,EAAY,EAAc,CACjCD,EAAQK,EAAM,OAAuB,MAAM,EAC3CD,EAAQ,CACV,CAEAD,EAAO,YAAYnB,CAAQ,CAC7B,CAAC,CACH,C"}
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);\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AA,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": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "Time-release encryption to protect sensitive information from bots",
5
5
  "keywords": [
6
6
  "anti-scraping",
@@ -73,7 +73,7 @@
73
73
  "execa": "^10.2.1",
74
74
  "magic-string": "^1.4.5",
75
75
  "nyc": "^18.0.0",
76
- "playwright": "^1.65.0",
76
+ "playwright": "^1.65.1",
77
77
  "rimraf": "^6.1.4",
78
78
  "tsdown": "^0.23.7",
79
79
  "tsx": "^4.23.15",
@@ -83,7 +83,7 @@
83
83
  "vitepress": "^1.6.4",
84
84
  "vitest": "^5.1.0"
85
85
  },
86
- "packageManager": "pnpm@12.16.1",
86
+ "packageManager": "pnpm@12.21.0",
87
87
  "engines": {
88
88
  "node": ">=22.0.0"
89
89
  }