@sesamy/sesamy-js 1.111.0 → 1.113.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.
@@ -1 +1 @@
1
- var capsulePlugin=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){let t=e.length%4,n=(t?e+`=`.repeat(4-t):e).replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}function n(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}var r=new Uint8Array([1,0,1]),i=`dca-keys`,a=`keypair`,o=`default`,s=class e{fetchFn;unlockFn;periodKeyCache;clientBound;rsaKeySize;keyDbName;keyPairPromise=null;constructor(e={}){this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.unlockFn=e.unlockFn,this.periodKeyCache=e.periodKeyCache,this.clientBound=e.clientBound??!1,this.rsaKeySize=e.rsaKeySize??2048,this.keyDbName=e.keyDbName??i}parsePage(e){let t=e??document,n=t.querySelector(`script.dca-data`);if(!n)throw Error(`DCA: <script class="dca-data"> not found`);let r=JSON.parse(n.textContent??``),i=t.querySelector(`template.dca-sealed-content`),a={};if(i&&i instanceof HTMLTemplateElement){let e=i.content.querySelectorAll(`[data-dca-content-name]`);for(let t of Array.from(e)){let e=t.getAttribute(`data-dca-content-name`);e&&(a[e]=t.textContent?.trim()??``)}}return{dcaData:r,sealedContent:a}}parseJsonResponse(e){let{sealedContent:t,...n}=e;return{dcaData:n,sealedContent:t}}static hasDcaContent(e){return(e??document).querySelector(`script.dca-data`)!==null}async unlock(e,t,n){let r=e.dcaData.issuerData[t];if(!r)throw Error(`DCA: issuer "${t}" not found in issuerData`);let i={resourceJWT:e.dcaData.resourceJWT,contentKeys:r.contentKeys,...e.dcaData.contentKeyMap?{contentKeyMap:e.dcaData.contentKeyMap}:{},...n};if(this.clientBound&&(i.clientPublicKey=await this.getPublicKey()),this.unlockFn)return this.unlockFn(r.unlockUrl,i);let a=await this.fetchFn(r.unlockUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);return a.json()}async unlockWithShareToken(e,t,n,r){return this.unlock(e,t,{...r,shareToken:n})}static getShareTokenFromUrl(e=`share`){if(typeof window>`u`||typeof URL>`u`)return null;try{return new URL(window.location.href).searchParams.get(e)}catch{return null}}async decrypt(e,n,r){let i=e.dcaData.contentSealData[n];if(!i)throw Error(`DCA: contentSealData not found for "${n}"`);let a=e.sealedContent[n];if(!a)throw Error(`DCA: sealed content not found for "${n}"`);let o=r.keys[n];if(!o)throw Error(`DCA: no key provided for "${n}"`);let s=r.transport===`client-bound`,c;if(o.contentKey){if(c=s?await this.rsaUnwrapKey(o.contentKey):t(o.contentKey),o.periodKeys&&this.periodKeyCache){let t=s?await this.unwrapPeriodKeyMap(o.periodKeys):o.periodKeys,r=e.dcaData.contentKeyMap?.[n]??n;await this.cachePeriodKeys(r,t)}}else if(o.periodKeys){let t=s?await this.unwrapPeriodKeyMap(o.periodKeys):o.periodKeys;if(c=await this.unwrapWithPeriodKeys(e.dcaData.sealedContentKeys[n]??[],t),this.periodKeyCache){let r=e.dcaData.contentKeyMap?.[n]??n;await this.cachePeriodKeys(r,t)}}else{let t=e.dcaData.contentKeyMap?.[n]??n,r=await this.getCachedPeriodKeys(t,e.dcaData.sealedContentKeys[n]??[]);if(r)c=await this.unwrapWithPeriodKeys(e.dcaData.sealedContentKeys[n]??[],r);else throw Error(`DCA: no contentKey or periodKeys available for "${n}"`)}let l=t(a),u=t(i.nonce),d=new TextEncoder().encode(i.aad),f=await crypto.subtle.importKey(`raw`,c,{name:`AES-GCM`},!1,[`decrypt`]),p=await crypto.subtle.decrypt({name:`AES-GCM`,iv:u,additionalData:d,tagLength:128},f,l);return new TextDecoder().decode(p)}async decryptAll(e,t){let n={};for(let r of Object.keys(t.keys))n[r]=await this.decrypt(e,r,t);return n}async processPage(t={}){let n=this.parsePage(t.root),r=t.issuerName??Object.keys(n.dcaData.issuerData)[0];if(!r)throw Error(`DCA: no issuers found in issuerData`);let i=t.shareToken===void 0?e.getShareTokenFromUrl(t.shareTokenParam):t.shareToken,a=i?await this.unlockWithShareToken(n,r,i,t.additionalBody):await this.unlock(n,r,t.additionalBody);return this.decryptAll(n,a)}renderToPage(e,t){let n=t??document,r=new Set;for(let[t,i]of Object.entries(e)){let e=n.querySelector(`[data-dca-content-name="${CSS.escape(t)}"]`);e&&(e.innerHTML=i,r.add(t))}return r}async unwrapWithPeriodKeys(e,n){for(let r of e){let e=n[r.t];if(!e)continue;let i=t(e),a=t(r.nonce),o=t(r.key),s=await crypto.subtle.importKey(`raw`,i,{name:`AES-GCM`},!1,[`decrypt`]);try{let e=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a,tagLength:128},s,o);return new Uint8Array(e)}catch{continue}}throw Error(`DCA: could not unwrap contentKey — no matching periodKey`)}async cachePeriodKeys(e,t){if(this.periodKeyCache)for(let[n,r]of Object.entries(t))await this.periodKeyCache.set(`dca:pk:${e}:${n}`,r)}async getCachedPeriodKeys(e,t){if(!this.periodKeyCache)return null;let n={},r=!1;for(let i of t){let t=await this.periodKeyCache.get(`dca:pk:${e}:${i.t}`);t&&(n[i.t]=t,r=!0)}return r?n:null}async getPublicKey(){let e=await this.ensureKeyPair(),t=await crypto.subtle.exportKey(`spki`,e.publicKey);return n(new Uint8Array(t))}async hasKeyPair(){try{let e=await this.openKeyDb();return await this.idbGet(e,o)!==void 0}catch{return!1}}ensureKeyPair(){return this.keyPairPromise||=this.loadOrCreateKeyPair(),this.keyPairPromise}async loadOrCreateKeyPair(){try{let e=await this.openKeyDb(),t=await this.idbGet(e,o);if(t?.publicKey&&t?.privateKey)return{publicKey:t.publicKey,privateKey:t.privateKey}}catch{}let e=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:this.rsaKeySize,publicExponent:r,hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await crypto.subtle.exportKey(`jwk`,e.privateKey),n=await crypto.subtle.importKey(`jwk`,t,{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]),i={publicKey:e.publicKey,privateKey:n};try{let t=await this.openKeyDb();await this.idbPut(t,o,{id:o,publicKey:e.publicKey,privateKey:n,createdAt:Date.now(),keySize:this.rsaKeySize})}catch{}return i}async rsaUnwrapKey(e){let n=await this.ensureKeyPair(),r=t(e),i=await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,r);return new Uint8Array(i)}async unwrapPeriodKeyMap(e){let t={};for(let[r,i]of Object.entries(e))t[r]=n(await this.rsaUnwrapKey(i));return t}keyDbPromise=null;openKeyDb(){return this.keyDbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.keyDbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(a)||e.createObjectStore(a,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this.keyDbPromise}idbGet(e,t){return new Promise((n,r)=>{let i=e.transaction(a,`readonly`).objectStore(a).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error)})}idbPut(e,t,n){return new Promise((t,r)=>{let i=e.transaction(a,`readwrite`).objectStore(a).put(n);i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}};function c(e){return s.hasDcaContent(e)}var l=function(e){return e.AUTH_INITIALIZED=`sesamyJsAuthInitialized`,e.READY=`sesamyJsReady`,e.AUTHENTICATED=`sesamyJsAuthenticated`,e.LOGOUT=`sesamyJsLogout`,e.CLEAR_CACHE=`sesamyJsClearCache`,e.USER_ATTRIBUTE_CHANGED=`sesamyUserAttributeChanged`,e.PURCHASE=`sesamyJsPurchase`,e.CONSENT_CHANGED=`sesamyJsConsentChanged`,e}({}),u=3600*1e3;function d(){let e=null;return{init(t,n){let r=async(e,t)=>{let r=await n.getToken(!1),i=new Headers(t?.headers);return r&&i.set(`Authorization`,`Bearer ${r}`),globalThis.fetch(e,{...t,headers:i,credentials:t?.credentials??`same-origin`})};window.addEventListener(l.LOGOUT,()=>{try{let e=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n?.startsWith(`dca:unlock:`)&&e.push(n)}e.forEach(e=>sessionStorage.removeItem(e))}catch{}}),e=new s({fetch:r,clientBound:t.clientBound??!1,rsaKeySize:t.rsaKeySize??2048,unlockFn:async(e,t)=>{let n=JSON.stringify(t),i=`dca:unlock:${e}:${n}`;try{let e=sessionStorage.getItem(i);if(e){let{ts:t,data:n}=JSON.parse(e);if(Date.now()-t<u)return n;sessionStorage.removeItem(i)}}catch{}let a=await r(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:n});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);let o=await a.json();try{sessionStorage.setItem(i,JSON.stringify({ts:Date.now(),data:o}))}catch{}return o}})},getDcaClient(){return e},async processPage(){if(!e||!c())return null;let t=await e.processPage();return e.renderToPage(t),t}}}return e.createCapsulePlugin=d,e})({});
1
+ var capsulePlugin=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){let t=e.length%4,n=(t?e+`=`.repeat(4-t):e).replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}function n(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}var r=new Uint8Array([1,0,1]),i=`dca-keys`,a=`keypair`,o=`default`,s=class e{fetchFn;unlockFn;periodKeyCache;clientBound;rsaKeySize;keyDbName;keyPairPromise=null;accessCheck;paywallFn;constructor(e={}){this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.unlockFn=e.unlockFn,this.periodKeyCache=e.periodKeyCache,this.clientBound=e.clientBound??!1,this.rsaKeySize=e.rsaKeySize??2048,this.keyDbName=e.keyDbName??i,this.accessCheck=e.accessCheck,this.paywallFn=e.paywallFn}parsePage(e){let t=e??document,n=t.querySelector(`script.dca-data`);if(!n)throw Error(`DCA: <script class="dca-data"> not found`);let r=JSON.parse(n.textContent??``),i=t.querySelector(`template.dca-sealed-content`),a={};if(i&&i instanceof HTMLTemplateElement){let e=i.content.querySelectorAll(`[data-dca-content-name]`);for(let t of Array.from(e)){let e=t.getAttribute(`data-dca-content-name`);e&&(a[e]=t.textContent?.trim()??``)}}return{dcaData:r,sealedContent:a}}parseJsonResponse(e){let{sealedContent:t,...n}=e;return{dcaData:n,sealedContent:t}}static hasDcaContent(e){return(e??document).querySelector(`script.dca-data`)!==null}async unlock(e,t,n){let r=e.dcaData.issuerData[t];if(!r)throw Error(`DCA: issuer "${t}" not found in issuerData`);let i={resourceJWT:e.dcaData.resourceJWT,contentEncryptionKeys:r.contentEncryptionKeys,...n};if(this.clientBound&&(i.clientPublicKey=await this.getPublicKey()),this.unlockFn)return this.unlockFn(r.unlockUrl,i);let a=await this.fetchFn(r.unlockUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);return a.json()}async unlockWithShareToken(e,t,n,r){return this.unlock(e,t,{...r,shareToken:n})}static getShareTokenFromUrl(e=`share`){if(typeof window>`u`||typeof URL>`u`)return null;try{return new URL(window.location.href).searchParams.get(e)}catch{return null}}async decrypt(e,n,r,i){let a=e.dcaData.contentSealData[n];if(!a)throw Error(`DCA: contentSealData not found for "${n}"`);let o=e.sealedContent[n];if(!o)throw Error(`DCA: sealed content not found for "${n}"`);let s=i??r.contentEncryptionKeys.find(e=>(e.contentName??`default`)===n);if(!s)throw Error(`DCA: no key provided for "${n}"`);let c=r.transport===`client-bound`,l=s.periodKeys?Object.fromEntries(s.periodKeys.map(e=>[e.bucket,e.key])):void 0,u;if(s.contentKey){if(u=c?await this.rsaUnwrapKey(s.contentKey):t(s.contentKey),l&&this.periodKeyCache){let e=c?await this.unwrapPeriodKeyMap(l):l,t=s.keyName??n;await this.cachePeriodKeys(t,e)}}else if(l){let t=c?await this.unwrapPeriodKeyMap(l):l;if(u=await this.unwrapWithPeriodKeys(e.dcaData.sealedContentKeys[n]??[],t),this.periodKeyCache){let e=s.keyName??n;await this.cachePeriodKeys(e,t)}}else{let t=Object.values(e.dcaData.issuerData).flatMap(e=>e.contentEncryptionKeys).find(e=>(e.contentName??`default`)===n)?.keyName??n,r=await this.getCachedPeriodKeys(t,e.dcaData.sealedContentKeys[n]??[]);if(r)u=await this.unwrapWithPeriodKeys(e.dcaData.sealedContentKeys[n]??[],r);else throw Error(`DCA: no contentKey or periodKeys available for "${n}"`)}let d=t(o),f=t(a.nonce),p=new TextEncoder().encode(a.aad),m=await crypto.subtle.importKey(`raw`,u,{name:`AES-GCM`},!1,[`decrypt`]),h=await crypto.subtle.decrypt({name:`AES-GCM`,iv:f,additionalData:p,tagLength:128},m,d);return new TextDecoder().decode(h)}async decryptAll(e,t){let n={},r=new Map(t.contentEncryptionKeys.map(e=>[e.contentName??`default`,e]));for(let[i,a]of r)n[i]=await this.decrypt(e,i,t,a);return n}async processPage(t={}){let n=t.root??document;if(this.accessCheck){let t=e.getPublisherContentId(n);if(!t)return console.warn(`DCA: accessCheck is configured but no publisher-content-id attribute was found on the page. Treating as denied.`),this.paywallFn&&this.paywallFn(t,n),{};let r=await this.accessCheck(t);if(!r||!r.hasAccess)return this.paywallFn&&this.paywallFn(t,n),{}}let r=this.parsePage(n),i=t.issuerName??Object.keys(r.dcaData.issuerData)[0];if(!i)throw Error(`DCA: no issuers found in issuerData`);let a=t.shareToken===void 0?e.getShareTokenFromUrl(t.shareTokenParam):t.shareToken,o=a?await this.unlockWithShareToken(r,i,a,t.additionalBody):await this.unlock(r,i,t.additionalBody);return this.decryptAll(r,o)}renderToPage(e,t){let n=t??document,r=new Set;for(let[t,i]of Object.entries(e)){let e=n.querySelector(`[data-dca-content-name="${CSS.escape(t)}"]`);e&&(e.innerHTML=i,r.add(t))}return r}static getPublisherContentId(e){let t=e??document;if(t instanceof Element){let e=t.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}let n=t.querySelector(`script.dca-data`);if(n){let e=n.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}return null}observe(e,t){let n=e??document.body,r=new MutationObserver(e=>{for(let n of e)for(let e of Array.from(n.addedNodes)){if(!(e instanceof HTMLElement))continue;let n=[];if(e.matches(`script.dca-data`)){let t=e.parentElement??e;n.includes(t)||n.push(t)}let r=e.querySelectorAll(`script.dca-data`);for(let t of Array.from(r)){let r=t.parentElement??e;n.includes(r)||n.push(r)}for(let e of n)this.processPage({...t,root:e}).then(t=>{Object.keys(t).length>0&&this.renderToPage(t,e)}).catch(e=>console.error(`DCA auto-process failed:`,e))}});return r.observe(n,{childList:!0,subtree:!0}),r}async unwrapWithPeriodKeys(e,n){for(let r of e){let e=n[r.t];if(!e)continue;let i=t(e),a=t(r.nonce),o=t(r.key),s=await crypto.subtle.importKey(`raw`,i,{name:`AES-GCM`},!1,[`decrypt`]);try{let e=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a,tagLength:128},s,o);return new Uint8Array(e)}catch{continue}}throw Error(`DCA: could not unwrap contentKey — no matching periodKey`)}async cachePeriodKeys(e,t){if(this.periodKeyCache)for(let[n,r]of Object.entries(t))await this.periodKeyCache.set(`dca:pk:${e}:${n}`,r)}async getCachedPeriodKeys(e,t){if(!this.periodKeyCache)return null;let n={},r=!1;for(let i of t){let t=await this.periodKeyCache.get(`dca:pk:${e}:${i.t}`);t&&(n[i.t]=t,r=!0)}return r?n:null}async getPublicKey(){let e=await this.ensureKeyPair(),t=await crypto.subtle.exportKey(`spki`,e.publicKey);return n(new Uint8Array(t))}async hasKeyPair(){try{let e=await this.openKeyDb();return await this.idbGet(e,o)!==void 0}catch{return!1}}ensureKeyPair(){return this.keyPairPromise||=this.loadOrCreateKeyPair(),this.keyPairPromise}async loadOrCreateKeyPair(){try{let e=await this.openKeyDb(),t=await this.idbGet(e,o);if(t?.publicKey&&t?.privateKey)return{publicKey:t.publicKey,privateKey:t.privateKey}}catch{}let e=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:this.rsaKeySize,publicExponent:r,hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await crypto.subtle.exportKey(`jwk`,e.privateKey),n=await crypto.subtle.importKey(`jwk`,t,{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]),i={publicKey:e.publicKey,privateKey:n};try{let t=await this.openKeyDb();await this.idbPut(t,o,{id:o,publicKey:e.publicKey,privateKey:n,createdAt:Date.now(),keySize:this.rsaKeySize})}catch{}return i}async rsaUnwrapKey(e){let n=await this.ensureKeyPair(),r=t(e),i=await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,r);return new Uint8Array(i)}async unwrapPeriodKeyMap(e){let t={};for(let[r,i]of Object.entries(e))t[r]=n(await this.rsaUnwrapKey(i));return t}keyDbPromise=null;openKeyDb(){return this.keyDbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.keyDbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(a)||e.createObjectStore(a,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this.keyDbPromise}idbGet(e,t){return new Promise((n,r)=>{let i=e.transaction(a,`readonly`).objectStore(a).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error)})}idbPut(e,t,n){return new Promise((t,r)=>{let i=e.transaction(a,`readwrite`).objectStore(a).put(n);i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}};function c(e){return s.hasDcaContent(e)}var l=function(e){return e.AUTH_INITIALIZED=`sesamyJsAuthInitialized`,e.READY=`sesamyJsReady`,e.AUTHENTICATED=`sesamyJsAuthenticated`,e.LOGOUT=`sesamyJsLogout`,e.CLEAR_CACHE=`sesamyJsClearCache`,e.USER_ATTRIBUTE_CHANGED=`sesamyUserAttributeChanged`,e.PURCHASE=`sesamyJsPurchase`,e.CONSENT_CHANGED=`sesamyJsConsentChanged`,e}({}),u=3600*1e3;function d(){let e=null;return{init(t,n){let r=async(e,t)=>{let r=await n.getToken(!1),i=new Headers(t?.headers);return r&&i.set(`Authorization`,`Bearer ${r}`),globalThis.fetch(e,{...t,headers:i,credentials:t?.credentials??`same-origin`})};window.addEventListener(l.LOGOUT,()=>{try{let e=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n?.startsWith(`dca:unlock:`)&&e.push(n)}e.forEach(e=>sessionStorage.removeItem(e))}catch{}}),e=new s({fetch:r,clientBound:t.clientBound??!1,rsaKeySize:t.rsaKeySize??2048,unlockFn:async(e,t)=>{let n=JSON.stringify(t),i=`dca:unlock:${e}:${n}`;try{let e=sessionStorage.getItem(i);if(e){let{ts:t,data:n}=JSON.parse(e);if(Date.now()-t<u)return n;sessionStorage.removeItem(i)}}catch{}let a=await r(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:n});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);let o=await a.json();try{sessionStorage.setItem(i,JSON.stringify({ts:Date.now(),data:o}))}catch{}return o}})},getDcaClient(){return e},async processPage(){if(!e||!c())return null;let t=await e.processPage();return e.renderToPage(t),t}}}return e.createCapsulePlugin=d,e})({});
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/@sesamy+capsule@0.8.0/node_modules/@sesamy/capsule/dist/index.mjs
1
+ //#region ../../node_modules/.pnpm/@sesamy+capsule@0.11.0/node_modules/@sesamy/capsule/dist/index.mjs
2
2
  function e(e) {
3
3
  let t = e.length % 4, n = (t ? e + "=".repeat(4 - t) : e).replace(/-/g, "+").replace(/_/g, "/"), r = atob(n), i = new Uint8Array(r.length);
4
4
  for (let e = 0; e < r.length; e++) i[e] = r.charCodeAt(e);
@@ -21,8 +21,10 @@ var n = new Uint8Array([
21
21
  rsaKeySize;
22
22
  keyDbName;
23
23
  keyPairPromise = null;
24
+ accessCheck;
25
+ paywallFn;
24
26
  constructor(e = {}) {
25
- this.fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this.unlockFn = e.unlockFn, this.periodKeyCache = e.periodKeyCache, this.clientBound = e.clientBound ?? !1, this.rsaKeySize = e.rsaKeySize ?? 2048, this.keyDbName = e.keyDbName ?? r;
27
+ this.fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this.unlockFn = e.unlockFn, this.periodKeyCache = e.periodKeyCache, this.clientBound = e.clientBound ?? !1, this.rsaKeySize = e.rsaKeySize ?? 2048, this.keyDbName = e.keyDbName ?? r, this.accessCheck = e.accessCheck, this.paywallFn = e.paywallFn;
26
28
  }
27
29
  parsePage(e) {
28
30
  let t = e ?? document, n = t.querySelector("script.dca-data");
@@ -55,8 +57,7 @@ var n = new Uint8Array([
55
57
  if (!r) throw Error(`DCA: issuer "${t}" not found in issuerData`);
56
58
  let i = {
57
59
  resourceJWT: e.dcaData.resourceJWT,
58
- contentKeys: r.contentKeys,
59
- ...e.dcaData.contentKeyMap ? { contentKeyMap: e.dcaData.contentKeyMap } : {},
60
+ contentEncryptionKeys: r.contentEncryptionKeys,
60
61
  ...n
61
62
  };
62
63
  if (this.clientBound && (i.clientPublicKey = await this.getPublicKey()), this.unlockFn) return this.unlockFn(r.unlockUrl, i);
@@ -82,48 +83,55 @@ var n = new Uint8Array([
82
83
  return null;
83
84
  }
84
85
  }
85
- async decrypt(t, n, r) {
86
- let i = t.dcaData.contentSealData[n];
87
- if (!i) throw Error(`DCA: contentSealData not found for "${n}"`);
88
- let a = t.sealedContent[n];
89
- if (!a) throw Error(`DCA: sealed content not found for "${n}"`);
90
- let o = r.keys[n];
91
- if (!o) throw Error(`DCA: no key provided for "${n}"`);
92
- let s = r.transport === "client-bound", c;
93
- if (o.contentKey) {
94
- if (c = s ? await this.rsaUnwrapKey(o.contentKey) : e(o.contentKey), o.periodKeys && this.periodKeyCache) {
95
- let e = s ? await this.unwrapPeriodKeyMap(o.periodKeys) : o.periodKeys, r = t.dcaData.contentKeyMap?.[n] ?? n;
96
- await this.cachePeriodKeys(r, e);
86
+ async decrypt(t, n, r, i) {
87
+ let a = t.dcaData.contentSealData[n];
88
+ if (!a) throw Error(`DCA: contentSealData not found for "${n}"`);
89
+ let o = t.sealedContent[n];
90
+ if (!o) throw Error(`DCA: sealed content not found for "${n}"`);
91
+ let s = i ?? r.contentEncryptionKeys.find((e) => (e.contentName ?? "default") === n);
92
+ if (!s) throw Error(`DCA: no key provided for "${n}"`);
93
+ let c = r.transport === "client-bound", l = s.periodKeys ? Object.fromEntries(s.periodKeys.map((e) => [e.bucket, e.key])) : void 0, u;
94
+ if (s.contentKey) {
95
+ if (u = c ? await this.rsaUnwrapKey(s.contentKey) : e(s.contentKey), l && this.periodKeyCache) {
96
+ let e = c ? await this.unwrapPeriodKeyMap(l) : l, t = s.keyName ?? n;
97
+ await this.cachePeriodKeys(t, e);
97
98
  }
98
- } else if (o.periodKeys) {
99
- let e = s ? await this.unwrapPeriodKeyMap(o.periodKeys) : o.periodKeys;
100
- if (c = await this.unwrapWithPeriodKeys(t.dcaData.sealedContentKeys[n] ?? [], e), this.periodKeyCache) {
101
- let r = t.dcaData.contentKeyMap?.[n] ?? n;
102
- await this.cachePeriodKeys(r, e);
99
+ } else if (l) {
100
+ let e = c ? await this.unwrapPeriodKeyMap(l) : l;
101
+ if (u = await this.unwrapWithPeriodKeys(t.dcaData.sealedContentKeys[n] ?? [], e), this.periodKeyCache) {
102
+ let t = s.keyName ?? n;
103
+ await this.cachePeriodKeys(t, e);
103
104
  }
104
105
  } else {
105
- let e = t.dcaData.contentKeyMap?.[n] ?? n, r = await this.getCachedPeriodKeys(e, t.dcaData.sealedContentKeys[n] ?? []);
106
- if (r) c = await this.unwrapWithPeriodKeys(t.dcaData.sealedContentKeys[n] ?? [], r);
106
+ let e = Object.values(t.dcaData.issuerData).flatMap((e) => e.contentEncryptionKeys).find((e) => (e.contentName ?? "default") === n)?.keyName ?? n, r = await this.getCachedPeriodKeys(e, t.dcaData.sealedContentKeys[n] ?? []);
107
+ if (r) u = await this.unwrapWithPeriodKeys(t.dcaData.sealedContentKeys[n] ?? [], r);
107
108
  else throw Error(`DCA: no contentKey or periodKeys available for "${n}"`);
108
109
  }
109
- let l = e(a), u = e(i.nonce), d = new TextEncoder().encode(i.aad), f = await crypto.subtle.importKey("raw", c, { name: "AES-GCM" }, !1, ["decrypt"]), p = await crypto.subtle.decrypt({
110
+ let d = e(o), f = e(a.nonce), p = new TextEncoder().encode(a.aad), m = await crypto.subtle.importKey("raw", u, { name: "AES-GCM" }, !1, ["decrypt"]), h = await crypto.subtle.decrypt({
110
111
  name: "AES-GCM",
111
- iv: u,
112
- additionalData: d,
112
+ iv: f,
113
+ additionalData: p,
113
114
  tagLength: 128
114
- }, f, l);
115
- return new TextDecoder().decode(p);
115
+ }, m, d);
116
+ return new TextDecoder().decode(h);
116
117
  }
117
118
  async decryptAll(e, t) {
118
- let n = {};
119
- for (let r of Object.keys(t.keys)) n[r] = await this.decrypt(e, r, t);
119
+ let n = {}, r = new Map(t.contentEncryptionKeys.map((e) => [e.contentName ?? "default", e]));
120
+ for (let [i, a] of r) n[i] = await this.decrypt(e, i, t, a);
120
121
  return n;
121
122
  }
122
123
  async processPage(e = {}) {
123
- let t = this.parsePage(e.root), n = e.issuerName ?? Object.keys(t.dcaData.issuerData)[0];
124
- if (!n) throw Error("DCA: no issuers found in issuerData");
125
- let r = e.shareToken === void 0 ? o.getShareTokenFromUrl(e.shareTokenParam) : e.shareToken, i = r ? await this.unlockWithShareToken(t, n, r, e.additionalBody) : await this.unlock(t, n, e.additionalBody);
126
- return this.decryptAll(t, i);
124
+ let t = e.root ?? document;
125
+ if (this.accessCheck) {
126
+ let e = o.getPublisherContentId(t);
127
+ if (!e) return console.warn("DCA: accessCheck is configured but no publisher-content-id attribute was found on the page. Treating as denied."), this.paywallFn && this.paywallFn(e, t), {};
128
+ let n = await this.accessCheck(e);
129
+ if (!n || !n.hasAccess) return this.paywallFn && this.paywallFn(e, t), {};
130
+ }
131
+ let n = this.parsePage(t), r = e.issuerName ?? Object.keys(n.dcaData.issuerData)[0];
132
+ if (!r) throw Error("DCA: no issuers found in issuerData");
133
+ let i = e.shareToken === void 0 ? o.getShareTokenFromUrl(e.shareTokenParam) : e.shareToken, a = i ? await this.unlockWithShareToken(n, r, i, e.additionalBody) : await this.unlock(n, r, e.additionalBody);
134
+ return this.decryptAll(n, a);
127
135
  }
128
136
  renderToPage(e, t) {
129
137
  let n = t ?? document, r = /* @__PURE__ */ new Set();
@@ -133,6 +141,46 @@ var n = new Uint8Array([
133
141
  }
134
142
  return r;
135
143
  }
144
+ static getPublisherContentId(e) {
145
+ let t = e ?? document;
146
+ if (t instanceof Element) {
147
+ let e = t.closest("[publisher-content-id]");
148
+ if (e) return e.getAttribute("publisher-content-id");
149
+ }
150
+ let n = t.querySelector("script.dca-data");
151
+ if (n) {
152
+ let e = n.closest("[publisher-content-id]");
153
+ if (e) return e.getAttribute("publisher-content-id");
154
+ }
155
+ return null;
156
+ }
157
+ observe(e, t) {
158
+ let n = e ?? document.body, r = new MutationObserver((e) => {
159
+ for (let n of e) for (let e of Array.from(n.addedNodes)) {
160
+ if (!(e instanceof HTMLElement)) continue;
161
+ let n = [];
162
+ if (e.matches("script.dca-data")) {
163
+ let t = e.parentElement ?? e;
164
+ n.includes(t) || n.push(t);
165
+ }
166
+ let r = e.querySelectorAll("script.dca-data");
167
+ for (let t of Array.from(r)) {
168
+ let r = t.parentElement ?? e;
169
+ n.includes(r) || n.push(r);
170
+ }
171
+ for (let e of n) this.processPage({
172
+ ...t,
173
+ root: e
174
+ }).then((t) => {
175
+ Object.keys(t).length > 0 && this.renderToPage(t, e);
176
+ }).catch((e) => console.error("DCA auto-process failed:", e));
177
+ }
178
+ });
179
+ return r.observe(n, {
180
+ childList: !0,
181
+ subtree: !0
182
+ }), r;
183
+ }
136
184
  async unwrapWithPeriodKeys(t, n) {
137
185
  for (let r of t) {
138
186
  let t = n[r.t];