openrtc 2.0.0-rc.21 → 2.0.0-rc.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-HTAWPIP2.js → chunk-3PE6TWIX.js} +1 -1
- package/dist/chunk-4UAAQLXK.js +2 -0
- package/dist/index.js +1 -1
- package/dist/native.js +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/index.js +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DA3HSI3K.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-4UAAQLXK.js';function p(){let r=crypto.getRandomValues(new Uint8Array(24)),e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function u(r){if(!r||typeof r!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=r;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function v(r){return {async readSecureRecord(e,t){return r.invoke("openrtc_v2_read_secure_record",{appTag:e,key:t})},async writeSecureRecord(e,t,n){await r.invoke("openrtc_v2_write_secure_record",{appTag:e,key:t,value:n});},async deleteSecureRecord(e,t){await r.invoke("openrtc_v2_delete_secure_record",{appTag:e,key:t});},async delete(e){await r.invoke("openrtc_v2_delete_device_key",{appTag:e});},async getOrCreate(e){let t=u(await r.invoke("openrtc_v2_device_public_key",{appTag:e})),n=await a(t);return {publicKeyJwk:t,thumbprint:n,async proof(s){let o=p(),c=Math.floor(Date.now()/1e3),i=await r.invoke("openrtc_v2_sign_device_proof",{appTag:e,challenge:s(o,c)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(i))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:t,signature:i,nonce:o,issuedAt:c}}}}}}
|
|
2
2
|
export{v as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var T=new Map;function k(a){let e=new Uint8Array(a),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return k(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function z(){return k(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function S(){return typeof indexedDB>"u"?null:new Promise((a,e)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>a(t.result),t.onerror=()=>e(t.error);})}async function Z(a){let e=await S().catch(()=>null);if(!e)return T.get(a)??null;try{return await new Promise((t,i)=>{let n=e.transaction("keys","readonly").objectStore("keys").get(a);n.onsuccess=()=>t(n.result??null),n.onerror=()=>i(n.error);})}finally{e.close();}}async function X(a,e){let t=await S().catch(()=>null);if(!t){T.set(a,e);return}try{await new Promise((i,n)=>{let r=t.transaction("keys","readwrite").objectStore("keys").put(e,a);r.onsuccess=()=>i(),r.onerror=()=>n(r.error);});}finally{t.close();}}async function Q(a){T.delete(a);let e=await S().catch(()=>null);if(e)try{await new Promise((t,i)=>{let n=e.transaction("keys","readwrite").objectStore("keys").delete(a);n.onsuccess=()=>t(),n.onerror=()=>i(n.error);});}finally{e.close();}}async function Y(a){let e=await Z(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await X(a,t),t}var U={async getOrCreate(a){let e=await Y(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await B(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=z(),o=Math.floor(Date.now()/1e3),s=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(n(r,o)));return {publicKeyJwk:t,signature:k(s),nonce:r,issuedAt:o}}}},delete:Q};var $={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":299532e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var A={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},H=1440*6e4,b=class extends Error{constructor(t,i,n){super(t);this.status=i;this.reason=n;this.name="OpenRTCV2HttpError";}};function F(a){return !(a instanceof b)||a.status!==403?false:a.reason==="device-certificate-stale"||a.reason==="device-certificate-revoked"?true:!a.reason&&a.message==="Device certificate is revoked or stale."}function I(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function x(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function ee(a,e,t){let i=new TextEncoder().encode(`openrtc:v2:session\0${a}\0${e}\0${t}`),n=new Uint8Array(await crypto.subtle.digest("SHA-256",i)),r="";for(let o of n)r+=String.fromCharCode(o);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function j(a){let e=a.replace(/-/g,"+").replace(/_/g,"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t);return Uint8Array.from(i,n=>n.charCodeAt(0))}async function G(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+H||!a.signingPublicJwk||a.signingPublicJwk.kty!=="OKP"||a.signingPublicJwk.crv!=="Ed25519"||typeof a.signingPublicJwk.x!="string")return null;let r=a.token.split(".");if(r.length!==3)return null;let o,s;try{o=JSON.parse(new TextDecoder().decode(j(r[0]))),s=g(a.token);}catch{return null}if(o.alg!=="EdDSA"||a.signingPublicJwk.kid&&o.kid!==a.signingPublicJwk.kid)return null;try{let d=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},d,j(r[2]),new TextEncoder().encode(`${r[0]}.${r[1]}`)))return null}catch{return null}let c=typeof s.principalId=="string"?s.principalId:"",l=Number(s.iat),p=Number(s.exp);return s.iss!=="openrtc"||s.aud!=="openrtc:v2:gateway-grant"||s.typ!=="device-certificate"||s.appTag!==e||!c||n!==void 0&&c!==n||typeof s.principalKey!="string"||s.principalKey.length===0||s.deviceId!==t||s.deviceKeyThumbprint!==i||typeof s.jti!="string"||s.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(p)||l>=p||p*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function te(a,e,t,i,n){try{let r=I(e,t,i),o=a.readSecureRecord?await a.readSecureRecord(e,r):globalThis.localStorage?.getItem(r);if(!o)return null;let s=JSON.parse(o),c=await G(s,e,i,n,t);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:t,signingPublicJwk:c.signingPublicJwk}:null}catch(r){if(a.readSecureRecord)throw r;return null}}async function ie(a,e,t,i,n){try{let r=x(e,i),o=a.readSecureRecord?await a.readSecureRecord(t,r):globalThis.localStorage?.getItem(r);return o?await G(JSON.parse(o),t,i,n):null}catch(r){if(a.readSecureRecord)throw r;return null}}async function ne(a,e,t,i,n){try{let r=I(e,t,i),o=JSON.stringify(n);a.writeSecureRecord?await a.writeSecureRecord(e,r,o):globalThis.localStorage?.setItem(r,o);}catch(r){if(a.writeSecureRecord)throw r}}async function re(a,e,t,i,n){try{let r=x(t,i),o=JSON.stringify({token:n.token,expiresAtMs:n.expiresAtMs,principalId:n.principalId,signingPublicJwk:n.signingPublicJwk});a.writeSecureRecord?await a.writeSecureRecord(e,r,o):globalThis.localStorage?.setItem(r,o);}catch(r){if(a.writeSecureRecord)throw r}}async function D(a,e,t,i,n){try{let r=I(e,t,i);if(a.deleteSecureRecord?await a.deleteSecureRecord(e,r):globalThis.localStorage?.removeItem(r),n){let o=x(n,i);a.deleteSecureRecord?await a.deleteSecureRecord(e,o):globalThis.localStorage?.removeItem(o);}}catch(r){if(a.deleteSecureRecord)throw r}}function ae(a){return `${a}_${crypto.randomUUID()}`}async function se(a,e){let t=new TextEncoder().encode(`${a}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(n=>n.toString(16).padStart(2,"0")).join("")}function g(a){let e=a.split(".")[1];if(!e)throw new Error("OpenRTC returned a malformed credential.");let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");return JSON.parse(atob(i))}var R=class{constructor(e,t,i,n,r={},o){this.apiKey=e;this.endpoints=t;this.keyProvider=i;this.attestation=n;this.events=r;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let t=this.authEpochs.get(e);if(t)return t;let i={generation:0,devices:new Map};return this.authEpochs.set(e,i),e.subscribe&&(i.unsubscribe=e.subscribe(n=>{n?.type==="principal-changed"&&(i.generation+=1,i.devices.clear(),i.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),i}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(e,t){let i=ae("request"),n=JSON.stringify({apiKey:this.apiKey,...t}),r=null;for(let o=0;o<2;o+=1)try{let s=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":i},body:n,signal:AbortSignal.timeout(15e3)});if(s.ok)return s.json();let c=`OpenRTC request failed (${s.status}).`,l;try{let d=await s.json();typeof d.error=="string"&&(c=d.error.slice(0,256)),typeof d.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(d.reason)&&(l=d.reason);}catch{}let p=new b(c,s.status,l);if(r=p,o===0&&[502,503,504].includes(s.status))continue;throw p}catch(s){if(r=s,o===0&&s instanceof TypeError)continue;throw s}throw r instanceof Error?r:new Error("OpenRTC request failed.")}async capability(e,t,i,n=false){this.before("capability.issue");let r=e==="space"?await se(this.apiKey,t):t,s=await(await this.key()).proof((d,u)=>["openrtc:v2:capability",this.apiKey,e,r,d,u].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,l=await this.post("/v2/capabilities",{avenue:{kind:e,id:r},deviceProof:s,...i?{maxPeers:i}:{},...n?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let p={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return p.renew=()=>this.capability(e,t,i,n),p}async deviceCertificate(e,t,i,n,r){let o=this.authEpoch(e),s=o.devices.get(t)??{};if(o.devices.set(t,s),r&&s.current&&s.current.token!==r.token)return this.deviceCertificateResult(e,t,i,n,{...s.current,enrolled:false});if(!r&&s.current&&s.current.expiresAtMs>Date.now()+H)return this.deviceCertificateResult(e,t,i,n,{...s.current,enrolled:false});if(!s.inFlight){let l=o.generation;r&&(s.current=void 0);let p=r?D(this.keyProvider,this.appTag,r.principalId,t,o.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(e,t,o.sessionKeyHash,n,true)):this.resolveAuthenticatedDevice(e,t,o,n);s.inFlight=p.then(d=>{if(o.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return s.current=d,d}).finally(()=>{s.inFlight=void 0;});}let c=await s.inFlight;return this.deviceCertificateResult(e,t,i,n,c)}async resolveAuthenticatedDevice(e,t,i,n){let r=await this.key();if(e.getSessionKey){let o=await e.getSessionKey();if(!o)throw new Error("The OpenRTC auth provider has no active principal.");let s=await ee(this.appTag,r.thumbprint,o);i.sessionKeyHash=s;let c=await ie(this.keyProvider,s,this.appTag,t,r.thumbprint);if(c)return c}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash,n)}deviceCertificateResult(e,t,i,n,r){let o={type:"device-certificate",token:r.token,avenue:i??{kind:"user",id:r.principalId},expiresAtMs:r.expiresAtMs};return o.renew=async()=>(await this.deviceCertificate(e,t,i,n)).source,o.recoverRejectedCertificate=async()=>(await this.deviceCertificate(e,t,i,n,r)).source,{principalId:r.principalId,source:o,enrolled:r.enrolled}}async enrollAuthenticatedDevice(e,t,i,n,r=false){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let o=async h=>{let y=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:h,deviceId:t});if(!y)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:y,...e.providerId?{providerId:e.providerId}:{}})},s;try{s=await o(!1);}catch(h){if(!(h instanceof b)||h.status!==401)throw h;s=await o(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let c=await this.key(),l=await te(this.keyProvider,this.appTag,s.principalId,t,c.thumbprint);if(l)return {...l,principalId:s.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let p=await c.proof((h,y)=>["openrtc:v2:device-enroll",this.appTag,s.principalId,t,h,y].join(":")),d=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${s.principalId}:${t}:${p.nonce}`,apiKey:this.apiKey})}:void 0,u=await this.post("/v2/devices/enroll",{identitySession:s.identitySession,deviceId:t,deviceProof:p,...n?.name||n?.platform?{deviceProfile:{...n.name?{name:n.name}:{},...n.platform?{platform:n.platform}:{}}}:{},...r?{recoverRevokedEnrollment:true}:{},...d?{attestation:d}:{}});this.record("device.enroll"),d&&this.record("security.attestation.verify");let v={principalId:s.principalId,token:u.deviceCertificate,expiresAtMs:u.expiresAt*1e3,signingPublicJwk:u.signingPublicJwk,enrolled:true};return await ne(this.keyProvider,this.appTag,s.principalId,t,{token:v.token,expiresAtMs:v.expiresAtMs,signingPublicJwk:v.signingPublicJwk}),i&&await re(this.keyProvider,this.appTag,i,t,v),v}async listEnrolledDevices(e,t){let i=await this.deviceCertificate(e,t);return (await this.deviceManagement(i.source,t,"list")).devices??[]}async revokeDevice(e,t,i){let n=await this.deviceCertificate(e,t);if(await this.deviceManagement(n.source,t,"revoke",i),i===t){let r=this.authEpoch(e);await D(this.keyProvider,this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),await this.deleteDeviceKey();}}async revokeAllDevices(e,t,i){let n=await this.deviceCertificate(e,t);await this.deviceManagement(n.source,t,"revoke-all",void 0,i);let r=this.authEpoch(e);await D(this.keyProvider,this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),i?await this.deviceCertificate(e,t):(r.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,t,i,n,r=false){let o=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;o&&this.before(o);let{manageDevice:s}=await import('./deviceManagement-PHY5TIOS.js'),c=await s({source:e,currentDeviceId:t,action:i,targetDeviceId:n,exceptCurrent:r,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:F});return o&&this.record(o),c}async durableRoomMembership(e,t,i){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(i==="join"?"room.join":"room.leave");let n=g(e.token),r=String(n.jti??""),s=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",r,i,t,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:i,roomId:t,deviceCertificate:e.token,deviceProof:s}),this.record(i==="join"?"room.join":"room.leave");}grantProvider(e,t={}){let i=null,n=e;return async r=>{if(i)return i;let o=(async()=>{let s=false;n.expiresAtMs<=Date.now()+5*6e4&&n.renew&&(n=await n.renew(),s=true);let c=r.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),r.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let u=g(d.token),v=String(u.jti??""),y=await(await this.key()).proof((w,q)=>["openrtc:v2:gateway-grant",v,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,w,q].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:y,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{},...d.type==="device-certificate"&&t.deviceProfile?{deviceProfile:t.deviceProfile}:{}})},p;try{p=await l(n);}catch(d){if(!F(d))throw d;let u=await n.recoverRejectedCertificate?.();if(!u)throw d;n=u,s=true,p=await l(n);}return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),s&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),p})();i=o;try{return await o}finally{i===o&&(i=null);}}}};var P=new WeakMap;function fe(a){let e=P.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function oe(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function f(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function V(a){let e=typeof a=="string"?a.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ce.test(t)?t:e}function le(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return V(i?.deviceId)}catch{return null}}function de(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&le(i,a)||V(i?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{i?.setItem(e,n),i?.setItem(t,JSON.stringify({deviceId:n}));}catch{}return n}function L(a){let e=typeof a=="string"?a.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function E(a){let e=g(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var K=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},M=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:($[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}},C=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;P.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}async retireDeviceIfPresent(e){(await this.client.devices.list()).some(i=>i.deviceId===e)&&await this.client.devices.delete(e);}async retireAllOtherDevices(e){let t=await this.client.devices.list();for(let i of t)i.deviceId!==e&&await this.client.devices.delete(i.deviceId);}async close(){if(!this.closed){this.closed=true;try{await this.client.advanced.runtime.shutdown();}finally{P.delete(this),this.onClosed();}}}},m=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let o=i.devices.list,s=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,p=async()=>this.roster.mergeDevices(await o()),d=async()=>this.roster.mergeStatus(await s()),u=y=>c(w=>y(this.roster.mergeDevices(w))),v=y=>l(w=>y(this.roster.mergeStatus(w))),h=Object.create(i);Object.defineProperties(h,{listDevices:{value:p,enumerable:false},listDevicesWithStatus:{value:d,enumerable:false},watchDevices:{value:u,enumerable:false},watchDevicesWithStatus:{value:v,enumerable:false},devices:{value:{...i.devices,list:p,listWithStatus:d,watch:u,watchWithStatus:v},enumerable:true}}),P.set(this,h);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}},_=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},O=class extends C{constructor(t,i,n,r,o){super("room",t,i,n);this.membership=r;this.onLeave=o;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},J=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},N=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new K;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await this.controlPlane.listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof m&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=L(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(o=>o.retireDeviceIfPresent(n)));for(let o of this.handles)o instanceof m&&o.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await this.controlPlane.revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof m&&n.retainCurrentEnrolledDevice(i);await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${f(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${f(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${f(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=oe(e.apiKey),this.usage=new M(e.usage),this.controlPlane=new R(this.apiKey,t.endpoints??A,t.deviceKeyProvider??U,e.trust?.attestation,{beforeLogicalOperation:i=>this.usage.assertCanSpend(i),onLogicalOperation:i=>this.usage.record(i),onAuthEpochChanged:i=>this.retireAuthCapabilities(i)},e.trust?.botVerification);}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let o={fingerprint:t,auth:i},s=n().then(c=>(o.handle=c,c)).catch(c=>{throw this.activations.get(e)===o&&this.activations.delete(e),c});return o.promise=s,this.activations.set(e,o),s}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.controlPlane.appTag):de(this.controlPlane.appTag);return L(e)}runtimeOptions(e){let t=this.options.transports,i=t?.privacy==="relay-only";if(i&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??A).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:i?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:t?.webrtc===true?i?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false},transportPriority:t?.priority}}async activate(e){let t={relay:this.options.transports?.relay===true,moq:this.options.transports?.moq===true,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},i=e.source,n=null,r=()=>({userId:e.principalId,token:i.token,tokenProvider:async()=>i.token,expiresAtMs:i.expiresAtMs}),o=this.runtimeOptions({avenue:e.source.avenue,grantProvider:this.controlPlane.grantProvider(e.source,{maxPeers:e.maxPeers,features:t,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName,devicePlatform:e.devicePlatform}),[s,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared-LDKG5RPN.js')]);n=c(s,this.internals.platform==="native"?"native":"web"),await n.setAuth(r()),this.channels.attach(n,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await n.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(l){throw this.channels.detach(n),await n.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),n}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let i=await this.deviceId(),{resolveDeviceProfile:n}=await import('./deviceProfile-3BEQZLJF.js'),r=n(e.profile,this.internals.platform==="native"?"native":"web"),o=await this.controlPlane.deviceCertificate(t,i,void 0,r),s=await this.activate({kind:"devices",id:o.principalId,source:o.source,principalId:o.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:r.name,devicePlatform:r.platform,deviceMetadata:r.metadata}),c;try{c=await this.controlPlane.listEnrolledDevices(t,i);}catch(d){throw this.channels.detach(s),await s.advanced.runtime.shutdown().catch(()=>{}),d}let{AuthenticatedDeviceRoster:l}=await import('./deviceRoster-GHF6MWXF.js'),p;return p=new m(o.principalId,s,()=>{this.channels.detach(s),this.onClosed(p);},new l(c)),this.handles.add(p),p}async joinSpace(e,t={}){this.assertOpen();let i=f(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(g(n.token).principalId),o=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:E(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),s;return s=new _(i,o,()=>{this.channels.detach(o),this.onClosed(s);},t.payload??"reliable"),this.handles.add(s),s}async joinRoom(e,t={}){this.assertOpen();let i=f(e),n=t.membership??"ephemeral",r=t.access??"capability";if(n==="durable"&&r!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r==="authenticated"){let p=t.auth??this.options.auth;if(!p)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let d=await this.deviceId(),u=await this.controlPlane.deviceCertificate(p,d,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(u.source,i,"join");let v;try{v=await this.activate({kind:"room",id:i,source:u.source,principalId:u.principalId,deviceId:d,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(y){throw n==="durable"&&await this.controlPlane.durableRoomMembership(u.source,i,"leave").catch(()=>{}),y}let h;return h=new O(i,v,()=>{this.channels.detach(v),this.onClosed(h);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(u.source,i,"leave");}:void 0),this.handles.add(h),h}let o=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),s=String(g(o.token).principalId),c=await this.activate({kind:"room",id:i,source:o,principalId:s,deviceId:E(o),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new O(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=f(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(g(n.token).principalId),o=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:E(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),s;return s=new J(i,o,()=>{this.channels.detach(o),this.onClosed(s);},n.token),this.handles.add(s),s}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{this.controlPlane.dispose(),this.activations.clear();}}}};function me(a,e){return new N(a,e)}
|
|
2
|
+
export{B as a,fe as b,me as c};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-3PE6TWIX.js';import {d}from'./chunk-Z2WVSXPW.js';import {c}from'./chunk-4UAAQLXK.js';export{a as OPENRTC_ERROR_CODES,b as OpenRtcError,e as classifyOpenRtcFailure,d as openRtcError,c as projectOpenRtcErrorFields}from'./chunk-NT5YHZQH.js';function i(p){return c(p,{platform:"web",runtimeFactory:async e=>{let{createWasmClient:t}=await import('./factories-SMMQHXUH.js');return t(e)}})}i.native=function(p,e=d()){return c(p,{platform:"native",deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:c}=await import('./ipcFactory-AR3VIBM4.js');return c(t,e)}})};export{i as OpenRTC};
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-3PE6TWIX.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'./chunk-Z2WVSXPW.js';import {c}from'./chunk-4UAAQLXK.js';function m(n,e){return c(n,{platform:"native",deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:o}=await import('./ipcFactory-AR3VIBM4.js');return o(t,e)}})}export{m as createNativeOpenRTC};
|
package/dist/openrtc_bg.wasm
CHANGED
|
Binary file
|
package/dist/runtime/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as Connection,u as IpcRuntimeAdapter,t as RuntimeClient,c as RuntimeConnectionController,g as ScopedConnectionActorError,j as ScopedConnectionActorHandle,k as ScopedConnectionActorRegistry,f as clog,r as concatRuntimeBytes,e as correlationForDriveGrantScope,q as createRuntimeJsonFrameDecoder,m as createRuntimeU32BEFrameDecoder,o as decodeRuntimeJsonPayload,p as encodeRuntimeJsonFrame,n as encodeRuntimeJsonPayload,l as encodeRuntimeU32BEFrame,s as readRuntimeU32BE,d as renderCorrelationFields,h as scopedConnectionKey,i as scopedConnectionKeyToString}from'../chunk-PPZRTJHE.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'../chunk-Z2WVSXPW.js';export{b as runtimeFromCapability}from'../chunk-
|
|
1
|
+
export{b as Connection,u as IpcRuntimeAdapter,t as RuntimeClient,c as RuntimeConnectionController,g as ScopedConnectionActorError,j as ScopedConnectionActorHandle,k as ScopedConnectionActorRegistry,f as clog,r as concatRuntimeBytes,e as correlationForDriveGrantScope,q as createRuntimeJsonFrameDecoder,m as createRuntimeU32BEFrameDecoder,o as decodeRuntimeJsonPayload,p as encodeRuntimeJsonFrame,n as encodeRuntimeJsonPayload,l as encodeRuntimeU32BEFrame,s as readRuntimeU32BE,d as renderCorrelationFields,h as scopedConnectionKey,i as scopedConnectionKeyToString}from'../chunk-PPZRTJHE.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'../chunk-Z2WVSXPW.js';export{b as runtimeFromCapability}from'../chunk-4UAAQLXK.js';export{a as isRuntimeDeviceActive,c as isRuntimeDeviceConnectable,b as isRuntimeDeviceRoutable}from'../chunk-CK6WQV7J.js';import'../chunk-WWC767HK.js';export{s as BROWSER_WASM_RUNTIME_CAPABILITIES,t as NATIVE_IPC_RUNTIME_CAPABILITIES,q as OPENRTC_RUNTIME_POLICY,u as cloneRuntimeCapabilities,r as getRuntimePolicy,i as logOpenRtcTeardownTrace,v as runtimeCapabilitiesForBrowserHost,w as runtimeCapabilitiesFromNativeStatus,x as runtimeCapabilityProfile}from'../chunk-FAPRYEWI.js';import'../chunk-QHSM5NFZ.js';import'../chunk-NT5YHZQH.js';import'../chunk-RRMBD5OL.js';export{b as openRtcDebug,a as openRtcDebugEnabled,c as openRtcDebugInfo,d as openRtcDebugLog}from'../chunk-PQK5SJ47.js';import'../chunk-C7YN5MSV.js';
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-3PE6TWIX.js';import {c}from'./chunk-4UAAQLXK.js';function l(r,n,e={}){return c(r,{endpoints:n,testingAllowInsecureLoopback:true,platform:"web",...e.deviceId?{deviceIdProvider:async()=>e.deviceId}:{},...e.irohTestRelayUrl?{irohTestRelayUrl:e.irohTestRelayUrl}:{},runtimeFactory:async t=>{let{createWasmClient:i}=await import('./factories-SMMQHXUH.js');return i(t)}})}function s(r,n,e){return c(r,{endpoints:n,testingAllowInsecureLoopback:true,platform:"native",deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let{createIpcClient:i}=await import('./ipcFactory-AR3VIBM4.js');return i(t,e)}})}export{s as createTestingNativeOpenRTC,l as createTestingOpenRTC};
|
package/package.json
CHANGED
package/dist/chunk-DA3HSI3K.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var T=new Map;function k(a){let e=new Uint8Array(a),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return k(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function z(){return k(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function S(){return typeof indexedDB>"u"?null:new Promise((a,e)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>a(t.result),t.onerror=()=>e(t.error);})}async function Z(a){let e=await S().catch(()=>null);if(!e)return T.get(a)??null;try{return await new Promise((t,i)=>{let n=e.transaction("keys","readonly").objectStore("keys").get(a);n.onsuccess=()=>t(n.result??null),n.onerror=()=>i(n.error);})}finally{e.close();}}async function X(a,e){let t=await S().catch(()=>null);if(!t){T.set(a,e);return}try{await new Promise((i,n)=>{let r=t.transaction("keys","readwrite").objectStore("keys").put(e,a);r.onsuccess=()=>i(),r.onerror=()=>n(r.error);});}finally{t.close();}}async function Q(a){T.delete(a);let e=await S().catch(()=>null);if(e)try{await new Promise((t,i)=>{let n=e.transaction("keys","readwrite").objectStore("keys").delete(a);n.onsuccess=()=>t(),n.onerror=()=>i(n.error);});}finally{e.close();}}async function Y(a){let e=await Z(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await X(a,t),t}var U={async getOrCreate(a){let e=await Y(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await B(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=z(),s=Math.floor(Date.now()/1e3),o=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(n(r,s)));return {publicKeyJwk:t,signature:k(o),nonce:r,issuedAt:s}}}},delete:Q};var $={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":299532e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var A={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},H=1440*6e4,b=class extends Error{constructor(t,i,n){super(t);this.status=i;this.reason=n;this.name="OpenRTCV2HttpError";}};function F(a){return !(a instanceof b)||a.status!==403?false:a.reason==="device-certificate-stale"?true:!a.reason&&a.message==="Device certificate is revoked or stale."}function I(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function x(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function ee(a,e,t){let i=new TextEncoder().encode(`openrtc:v2:session\0${a}\0${e}\0${t}`),n=new Uint8Array(await crypto.subtle.digest("SHA-256",i)),r="";for(let s of n)r+=String.fromCharCode(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function j(a){let e=a.replace(/-/g,"+").replace(/_/g,"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t);return Uint8Array.from(i,n=>n.charCodeAt(0))}async function G(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+H||!a.signingPublicJwk||a.signingPublicJwk.kty!=="OKP"||a.signingPublicJwk.crv!=="Ed25519"||typeof a.signingPublicJwk.x!="string")return null;let r=a.token.split(".");if(r.length!==3)return null;let s,o;try{s=JSON.parse(new TextDecoder().decode(j(r[0]))),o=y(a.token);}catch{return null}if(s.alg!=="EdDSA"||a.signingPublicJwk.kid&&s.kid!==a.signingPublicJwk.kid)return null;try{let d=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},d,j(r[2]),new TextEncoder().encode(`${r[0]}.${r[1]}`)))return null}catch{return null}let c=typeof o.principalId=="string"?o.principalId:"",l=Number(o.iat),p=Number(o.exp);return o.iss!=="openrtc"||o.aud!=="openrtc:v2:gateway-grant"||o.typ!=="device-certificate"||o.appTag!==e||!c||n!==void 0&&c!==n||typeof o.principalKey!="string"||o.principalKey.length===0||o.deviceId!==t||o.deviceKeyThumbprint!==i||typeof o.jti!="string"||o.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(p)||l>=p||p*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function te(a,e,t,i,n){try{let r=I(e,t,i),s=a.readSecureRecord?await a.readSecureRecord(e,r):globalThis.localStorage?.getItem(r);if(!s)return null;let o=JSON.parse(s),c=await G(o,e,i,n,t);return c?{token:c.token,expiresAtMs:c.expiresAtMs,principalId:t,signingPublicJwk:c.signingPublicJwk}:null}catch(r){if(a.readSecureRecord)throw r;return null}}async function ie(a,e,t,i,n){try{let r=x(e,i),s=a.readSecureRecord?await a.readSecureRecord(t,r):globalThis.localStorage?.getItem(r);return s?await G(JSON.parse(s),t,i,n):null}catch(r){if(a.readSecureRecord)throw r;return null}}async function ne(a,e,t,i,n){try{let r=I(e,t,i),s=JSON.stringify(n);a.writeSecureRecord?await a.writeSecureRecord(e,r,s):globalThis.localStorage?.setItem(r,s);}catch(r){if(a.writeSecureRecord)throw r}}async function re(a,e,t,i,n){try{let r=x(t,i),s=JSON.stringify({token:n.token,expiresAtMs:n.expiresAtMs,principalId:n.principalId,signingPublicJwk:n.signingPublicJwk});a.writeSecureRecord?await a.writeSecureRecord(e,r,s):globalThis.localStorage?.setItem(r,s);}catch(r){if(a.writeSecureRecord)throw r}}async function D(a,e,t,i,n){try{let r=I(e,t,i);if(a.deleteSecureRecord?await a.deleteSecureRecord(e,r):globalThis.localStorage?.removeItem(r),n){let s=x(n,i);a.deleteSecureRecord?await a.deleteSecureRecord(e,s):globalThis.localStorage?.removeItem(s);}}catch(r){if(a.deleteSecureRecord)throw r}}function ae(a){return `${a}_${crypto.randomUUID()}`}async function se(a,e){let t=new TextEncoder().encode(`${a}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(n=>n.toString(16).padStart(2,"0")).join("")}function y(a){let e=a.split(".")[1];if(!e)throw new Error("OpenRTC returned a malformed credential.");let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");return JSON.parse(atob(i))}var R=class{constructor(e,t,i,n,r={},s){this.apiKey=e;this.endpoints=t;this.keyProvider=i;this.attestation=n;this.events=r;this.botVerification=s;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let t=this.authEpochs.get(e);if(t)return t;let i={generation:0,devices:new Map};return this.authEpochs.set(e,i),e.subscribe&&(i.unsubscribe=e.subscribe(n=>{n?.type==="principal-changed"&&(i.generation+=1,i.devices.clear(),i.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),i}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(e,t){let i=ae("request"),n=JSON.stringify({apiKey:this.apiKey,...t}),r=null;for(let s=0;s<2;s+=1)try{let o=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":i},body:n,signal:AbortSignal.timeout(15e3)});if(o.ok)return o.json();let c=`OpenRTC request failed (${o.status}).`,l;try{let d=await o.json();typeof d.error=="string"&&(c=d.error.slice(0,256)),typeof d.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(d.reason)&&(l=d.reason);}catch{}let p=new b(c,o.status,l);if(r=p,s===0&&[502,503,504].includes(o.status))continue;throw p}catch(o){if(r=o,s===0&&o instanceof TypeError)continue;throw o}throw r instanceof Error?r:new Error("OpenRTC request failed.")}async capability(e,t,i,n=false){this.before("capability.issue");let r=e==="space"?await se(this.apiKey,t):t,o=await(await this.key()).proof((d,u)=>["openrtc:v2:capability",this.apiKey,e,r,d,u].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,l=await this.post("/v2/capabilities",{avenue:{kind:e,id:r},deviceProof:o,...i?{maxPeers:i}:{},...n?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let p={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return p.renew=()=>this.capability(e,t,i,n),p}async deviceCertificate(e,t,i,n,r){let s=this.authEpoch(e),o=s.devices.get(t)??{};if(s.devices.set(t,o),r&&o.current&&o.current.token!==r.token)return this.deviceCertificateResult(e,t,i,n,{...o.current,enrolled:false});if(!r&&o.current&&o.current.expiresAtMs>Date.now()+H)return this.deviceCertificateResult(e,t,i,n,{...o.current,enrolled:false});if(!o.inFlight){let l=s.generation;r&&(o.current=void 0);let p=r?D(this.keyProvider,this.appTag,r.principalId,t,s.sessionKeyHash).then(()=>this.enrollAuthenticatedDevice(e,t,s.sessionKeyHash,n)):this.resolveAuthenticatedDevice(e,t,s,n);o.inFlight=p.then(d=>{if(s.generation!==l)throw new Error("The OpenRTC authentication identity changed during enrollment.");return o.current=d,d}).finally(()=>{o.inFlight=void 0;});}let c=await o.inFlight;return this.deviceCertificateResult(e,t,i,n,c)}async resolveAuthenticatedDevice(e,t,i,n){let r=await this.key();if(e.getSessionKey){let s=await e.getSessionKey();if(!s)throw new Error("The OpenRTC auth provider has no active principal.");let o=await ee(this.appTag,r.thumbprint,s);i.sessionKeyHash=o;let c=await ie(this.keyProvider,o,this.appTag,t,r.thumbprint);if(c)return c}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash,n)}deviceCertificateResult(e,t,i,n,r){let s={type:"device-certificate",token:r.token,avenue:i??{kind:"user",id:r.principalId},expiresAtMs:r.expiresAtMs};return s.renew=async()=>(await this.deviceCertificate(e,t,i,n)).source,s.recoverRejectedCertificate=async()=>(await this.deviceCertificate(e,t,i,n,r)).source,{principalId:r.principalId,source:s,enrolled:r.enrolled}}async enrollAuthenticatedDevice(e,t,i,n){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let r=async h=>{let v=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:h,deviceId:t});if(!v)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:v,...e.providerId?{providerId:e.providerId}:{}})},s;try{s=await r(!1);}catch(h){if(!(h instanceof b)||h.status!==401)throw h;s=await r(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let o=await this.key(),c=await te(this.keyProvider,this.appTag,s.principalId,t,o.thumbprint);if(c)return {...c,principalId:s.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let l=await o.proof((h,v)=>["openrtc:v2:device-enroll",this.appTag,s.principalId,t,h,v].join(":")),p=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${s.principalId}:${t}:${l.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:s.identitySession,deviceId:t,deviceProof:l,...n?.name||n?.platform?{deviceProfile:{...n.name?{name:n.name}:{},...n.platform?{platform:n.platform}:{}}}:{},...p?{attestation:p}:{}});this.record("device.enroll"),p&&this.record("security.attestation.verify");let u={principalId:s.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,signingPublicJwk:d.signingPublicJwk,enrolled:true};return await ne(this.keyProvider,this.appTag,s.principalId,t,{token:u.token,expiresAtMs:u.expiresAtMs,signingPublicJwk:u.signingPublicJwk}),i&&await re(this.keyProvider,this.appTag,i,t,u),u}async listEnrolledDevices(e,t){let i=await this.deviceCertificate(e,t);return (await this.deviceManagement(i.source,t,"list")).devices??[]}async revokeDevice(e,t,i){let n=await this.deviceCertificate(e,t);if(await this.deviceManagement(n.source,t,"revoke",i),i===t){let r=this.authEpoch(e);await D(this.keyProvider,this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),await this.deleteDeviceKey();}}async revokeAllDevices(e,t,i){let n=await this.deviceCertificate(e,t);await this.deviceManagement(n.source,t,"revoke-all",void 0,i);let r=this.authEpoch(e);await D(this.keyProvider,this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),i?await this.deviceCertificate(e,t):(r.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,t,i,n,r=false){let s=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;s&&this.before(s);let{manageDevice:o}=await import('./deviceManagement-PHY5TIOS.js'),c=await o({source:e,currentDeviceId:t,action:i,targetDeviceId:n,exceptCurrent:r,key:()=>this.key(),post:l=>this.post("/v2/devices/manage",l),isStale:F});return s&&this.record(s),c}async durableRoomMembership(e,t,i){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(i==="join"?"room.join":"room.leave");let n=y(e.token),r=String(n.jti??""),o=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",r,i,t,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:i,roomId:t,deviceCertificate:e.token,deviceProof:o}),this.record(i==="join"?"room.join":"room.leave");}grantProvider(e,t={}){let i=null,n=e;return async r=>{if(i)return i;let s=(async()=>{let o=false;n.expiresAtMs<=Date.now()+5*6e4&&n.renew&&(n=await n.renew(),o=true);let c=r.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),r.refreshGrant&&this.before("coordination.credential.refresh");let l=async d=>{let u=y(d.token),h=String(u.jti??""),g=await(await this.key()).proof((w,q)=>["openrtc:v2:gateway-grant",h,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,w,q].join(":"));return this.post("/v2/gateway/grants",{credentialType:d.type,credential:d.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:g,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{},...d.type==="device-certificate"&&t.deviceProfile?{deviceProfile:t.deviceProfile}:{}})},p;try{p=await l(n);}catch(d){if(!F(d))throw d;let u=await n.recoverRejectedCertificate?.();if(!u)throw d;n=u,o=true,p=await l(n);}return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),o&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),p})();i=s;try{return await s}finally{i===s&&(i=null);}}}};var P=new WeakMap;function fe(a){let e=P.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function oe(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function f(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function V(a){let e=typeof a=="string"?a.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ce.test(t)?t:e}function le(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return V(i?.deviceId)}catch{return null}}function de(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&le(i,a)||V(i?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{i?.setItem(e,n),i?.setItem(t,JSON.stringify({deviceId:n}));}catch{}return n}function L(a){let e=typeof a=="string"?a.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function E(a){let e=y(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var K=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},M=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:($[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}},C=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;P.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}async retireDeviceIfPresent(e){(await this.client.devices.list()).some(i=>i.deviceId===e)&&await this.client.devices.delete(e);}async retireAllOtherDevices(e){let t=await this.client.devices.list();for(let i of t)i.deviceId!==e&&await this.client.devices.delete(i.deviceId);}async close(){if(!this.closed){this.closed=true;try{await this.client.advanced.runtime.shutdown();}finally{P.delete(this),this.onClosed();}}}},m=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let s=i.devices.list,o=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,p=async()=>this.roster.mergeDevices(await s()),d=async()=>this.roster.mergeStatus(await o()),u=g=>c(w=>g(this.roster.mergeDevices(w))),h=g=>l(w=>g(this.roster.mergeStatus(w))),v=Object.create(i);Object.defineProperties(v,{listDevices:{value:p,enumerable:false},listDevicesWithStatus:{value:d,enumerable:false},watchDevices:{value:u,enumerable:false},watchDevicesWithStatus:{value:h,enumerable:false},devices:{value:{...i.devices,list:p,listWithStatus:d,watch:u,watchWithStatus:h},enumerable:true}}),P.set(this,v);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}},_=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},O=class extends C{constructor(t,i,n,r,s){super("room",t,i,n);this.membership=r;this.onLeave=s;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},J=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},N=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new K;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await this.controlPlane.listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof m&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=L(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(s=>s.retireDeviceIfPresent(n)));for(let s of this.handles)s instanceof m&&s.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await this.controlPlane.revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof m&&n.retainCurrentEnrolledDevice(i);await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${f(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${f(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${f(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=oe(e.apiKey),this.usage=new M(e.usage),this.controlPlane=new R(this.apiKey,t.endpoints??A,t.deviceKeyProvider??U,e.trust?.attestation,{beforeLogicalOperation:i=>this.usage.assertCanSpend(i),onLogicalOperation:i=>this.usage.record(i),onAuthEpochChanged:i=>this.retireAuthCapabilities(i)},e.trust?.botVerification);}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:i},o=n().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=o,this.activations.set(e,s),o}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.controlPlane.appTag):de(this.controlPlane.appTag);return L(e)}runtimeOptions(e){let t=this.options.transports,i=t?.privacy==="relay-only";if(i&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??A).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:i?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:t?.webrtc===true?i?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false},transportPriority:t?.priority}}async activate(e){let t={relay:this.options.transports?.relay===true,moq:this.options.transports?.moq===true,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},i=e.source,n=null,r=()=>({userId:e.principalId,token:i.token,tokenProvider:async()=>i.token,expiresAtMs:i.expiresAtMs}),s=this.runtimeOptions({avenue:e.source.avenue,grantProvider:this.controlPlane.grantProvider(e.source,{maxPeers:e.maxPeers,features:t,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName,devicePlatform:e.devicePlatform}),[o,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(s),import('./OpenRTCShared-LDKG5RPN.js')]);n=c(o,this.internals.platform==="native"?"native":"web"),await n.setAuth(r()),this.channels.attach(n,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await n.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(l){throw this.channels.detach(n),await n.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),n}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let i=await this.deviceId(),{resolveDeviceProfile:n}=await import('./deviceProfile-3BEQZLJF.js'),r=n(e.profile,this.internals.platform==="native"?"native":"web"),s=await this.controlPlane.deviceCertificate(t,i,void 0,r),o=await this.activate({kind:"devices",id:s.principalId,source:s.source,principalId:s.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:r.name,devicePlatform:r.platform,deviceMetadata:r.metadata}),c;try{c=await this.controlPlane.listEnrolledDevices(t,i);}catch(d){throw this.channels.detach(o),await o.advanced.runtime.shutdown().catch(()=>{}),d}let{AuthenticatedDeviceRoster:l}=await import('./deviceRoster-GHF6MWXF.js'),p;return p=new m(s.principalId,o,()=>{this.channels.detach(o),this.onClosed(p);},new l(c)),this.handles.add(p),p}async joinSpace(e,t={}){this.assertOpen();let i=f(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(y(n.token).principalId),s=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:E(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),o;return o=new _(i,s,()=>{this.channels.detach(s),this.onClosed(o);},t.payload??"reliable"),this.handles.add(o),o}async joinRoom(e,t={}){this.assertOpen();let i=f(e),n=t.membership??"ephemeral",r=t.access??"capability";if(n==="durable"&&r!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r==="authenticated"){let p=t.auth??this.options.auth;if(!p)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let d=await this.deviceId(),u=await this.controlPlane.deviceCertificate(p,d,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(u.source,i,"join");let h;try{h=await this.activate({kind:"room",id:i,source:u.source,principalId:u.principalId,deviceId:d,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(g){throw n==="durable"&&await this.controlPlane.durableRoomMembership(u.source,i,"leave").catch(()=>{}),g}let v;return v=new O(i,h,()=>{this.channels.detach(h),this.onClosed(v);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(u.source,i,"leave");}:void 0),this.handles.add(v),v}let s=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),o=String(y(s.token).principalId),c=await this.activate({kind:"room",id:i,source:s,principalId:o,deviceId:E(s),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new O(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=f(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(y(n.token).principalId),s=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:E(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),o;return o=new J(i,s,()=>{this.channels.detach(s),this.onClosed(o);},n.token),this.handles.add(o),o}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{this.controlPlane.dispose(),this.activations.clear();}}}};function me(a,e){return new N(a,e)}
|
|
2
|
-
export{B as a,fe as b,me as c};
|