openrtc 2.0.0-rc.8 → 2.0.0-rc.9
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-23XC6TGK.js +2 -0
- package/dist/{chunk-BY3EPIAB.js → chunk-KWXAZUAZ.js} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/native.d.ts +2 -2
- package/dist/native.js +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/{types-ZdRrnIRw.d.ts → types-byWIP-WI.d.ts} +7 -0
- package/package.json +1 -1
- package/dist/chunk-IAEGDK4P.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var T=new Map;function P(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 V(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return P(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function q(){return P(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function O(){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 W(a){let e=await O().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 B(a,e){let t=await O().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 z(a){T.delete(a);let e=await O().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 Z(a){let e=await W(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await B(a,t),t}var J={async getOrCreate(a){let e=await Z(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await V(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=q(),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:P(s),nonce:r,issuedAt:o}}}},delete:z};var N={"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":287514e-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 R={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},j=1440*6e4,f=class extends Error{constructor(t,i){super(t);this.status=i;this.name="OpenRTCV2HttpError";}};function k(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function A(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function X(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 U(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 F(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+j||!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(U(r[0]))),s=v(a.token);}catch{return null}if(o.alg!=="EdDSA"||a.signingPublicJwk.kid&&o.kid!==a.signingPublicJwk.kid)return null;try{let u=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},u,U(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),d=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(d)||l>=d||d*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function Q(a,e,t,i){try{let n=globalThis.localStorage?.getItem(k(a,e,t));if(!n)return null;let r=JSON.parse(n),o=await F(r,a,t,i,e);return o?{token:o.token,expiresAtMs:o.expiresAtMs,principalId:e,signingPublicJwk:o.signingPublicJwk}:null}catch{return null}}async function Y(a,e,t,i){try{let n=globalThis.localStorage?.getItem(A(a,t));return n?await F(JSON.parse(n),e,t,i):null}catch{return null}}function ee(a,e,t,i){try{globalThis.localStorage?.setItem(k(a,e,t),JSON.stringify(i));}catch{}}function te(a,e,t){try{globalThis.localStorage?.setItem(A(a,e),JSON.stringify({token:t.token,expiresAtMs:t.expiresAtMs,principalId:t.principalId,signingPublicJwk:t.signingPublicJwk}));}catch{}}function $(a,e,t,i){try{globalThis.localStorage?.removeItem(k(a,e,t)),i&&globalThis.localStorage?.removeItem(A(i,t));}catch{}}function ie(a){return `${a}_${crypto.randomUUID()}`}async function ne(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 v(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 C=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=ie("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}).`;try{let d=await s.json();typeof d.error=="string"&&(c=d.error.slice(0,256));}catch{}let l=new f(c,s.status);if(r=l,o===0&&[502,503,504].includes(s.status))continue;throw l}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 ne(this.apiKey,t):t,s=await(await this.key()).proof((u,p)=>["openrtc:v2:capability",this.apiKey,e,r,u,p].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 d={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return d.renew=()=>this.capability(e,t,i,n),d}async deviceCertificate(e,t,i){let n=this.authEpoch(e),r=n.devices.get(t)??{};if(n.devices.set(t,r),r.current&&r.current.expiresAtMs>Date.now()+j)return this.deviceCertificateResult(e,t,i,{...r.current,enrolled:false});if(!r.inFlight){let s=n.generation;r.inFlight=this.resolveAuthenticatedDevice(e,t,n).then(c=>{if(n.generation!==s)throw new Error("The OpenRTC authentication identity changed during enrollment.");return r.current=c,c}).finally(()=>{r.inFlight=void 0;});}let o=await r.inFlight;return this.deviceCertificateResult(e,t,i,o)}async resolveAuthenticatedDevice(e,t,i){let n=await this.key();if(e.getSessionKey){let r=await e.getSessionKey();if(!r)throw new Error("The OpenRTC auth provider has no active principal.");let o=await X(this.appTag,n.thumbprint,r);i.sessionKeyHash=o;let s=await Y(o,this.appTag,t,n.thumbprint);if(s)return s}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash)}deviceCertificateResult(e,t,i,n){let r={type:"device-certificate",token:n.token,avenue:i??{kind:"user",id:n.principalId},expiresAtMs:n.expiresAtMs};return r.renew=async()=>(await this.deviceCertificate(e,t,i)).source,{principalId:n.principalId,source:r,enrolled:n.enrolled}}async enrollAuthenticatedDevice(e,t,i){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let n=async p=>{let h=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:p,deviceId:t});if(!h)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:h,...e.providerId?{providerId:e.providerId}:{}})},r;try{r=await n(!1);}catch(p){if(!(p instanceof f)||p.status!==401)throw p;r=await n(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let o=await this.key(),s=await Q(this.appTag,r.principalId,t,o.thumbprint);if(s)return {...s,principalId:r.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let c=await o.proof((p,h)=>["openrtc:v2:device-enroll",this.appTag,r.principalId,t,p,h].join(":")),l=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${r.principalId}:${t}:${c.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:t,deviceProof:c,...l?{attestation:l}:{}});this.record("device.enroll"),l&&this.record("security.attestation.verify");let u={principalId:r.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,signingPublicJwk:d.signingPublicJwk,enrolled:true};return ee(this.appTag,r.principalId,t,{token:u.token,expiresAtMs:u.expiresAtMs,signingPublicJwk:u.signingPublicJwk}),i&&te(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);$(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);$(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){if(e.type!=="device-certificate")throw new Error("Device management requires an authenticated device certificate.");let o=v(e.token),s=String(o.jti??""),l=await(await this.key()).proof((p,h)=>["openrtc:v2:device-management",s,i,n??"",r?"except-current":"include-current",p,h].join(":")),d=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;d&&this.before(d);let u=await this.post("/v2/devices/manage",{action:i,deviceCertificate:e.token,currentDeviceId:t,...n?{targetDeviceId:n}:{},...r?{exceptCurrent:true}:{},deviceProof:l});return d&&this.record(d),u}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=v(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=v(n.token),d=String(l.jti??""),p=await(await this.key()).proof((y,b)=>["openrtc:v2:gateway-grant",d,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,y,b].join(":")),h=await this.post("/v2/gateway/grants",{credentialType:n.type,credential:n.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:p,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{}});return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),s&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),h})();i=o;try{return await o}finally{i===o&&(i=null);}}}};var I=new WeakMap;function ye(a){let e=I.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function re(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 g(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}function ae(a){let e=a?.trim();if(e){if(new TextEncoder().encode(e).byteLength>4*1024)throw new Error("[OpenRTC] Device profile metadata must not exceed 4 KiB.");return e}}var G=/^[A-Za-z0-9_.:@-]{1,160}$/,se=/^[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 L(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return se.test(t)?t:e}function oe(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return L(i?.deviceId)}catch{return null}}function ce(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&oe(i,a)||L(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 H(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function S(a){let e=v(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 x=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);}},D=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:(N[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"}));}},m=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;I.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{I.delete(this),this.onClosed();}}}},E=class extends m{constructor(t,i,n){super("devices",t,i,n);this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=()=>this.client.devices.list();this.listWithStatus=()=>this.client.devices.listWithStatus();this.watch=this.client.devices.watch;this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;}},K=class extends m{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},w=class extends m{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();}},M=class extends m{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},_=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new x;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={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.");return this.controlPlane.listEnrolledDevices(t,await this.deviceId())},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=H(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(o=>o.retireDeviceIfPresent(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();await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${g(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:${g(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:${g(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=re(e.apiKey),this.usage=new D(e.usage),this.controlPlane=new C(this.apiKey,t.endpoints??R,t.deviceKeyProvider??J,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):ce(this.controlPlane.appTag);return H(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,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??R).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,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName}),[s,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared-TKAQLONA.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(),n=await this.controlPlane.deviceCertificate(t,i),r=await this.activate({kind:"devices",id:n.principalId,source:n.source,principalId:n.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:e.profile?.name,deviceMetadata:ae(e.profile?.metadata)}),o;return o=new E(n.principalId,r,()=>{this.channels.detach(r),this.onClosed(o);}),this.handles.add(o),o}async joinSpace(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),s;return s=new K(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=g(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 d=t.auth??this.options.auth;if(!d)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let u=await this.deviceId(),p=await this.controlPlane.deviceCertificate(d,u,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"join");let h;try{h=await this.activate({kind:"room",id:i,source:p.source,principalId:p.principalId,deviceId:u,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(b){throw n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"leave").catch(()=>{}),b}let y;return y=new w(i,h,()=>{this.channels.detach(h),this.onClosed(y);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(p.source,i,"leave");}:void 0),this.handles.add(y),y}let o=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),s=String(v(o.token).principalId),c=await this.activate({kind:"room",id:i,source:o,principalId:s,deviceId:S(o),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new w(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),s;return s=new M(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 ge(a,e){return new _(a,e)}
|
|
2
|
+
export{V as a,ye as b,ge as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-23XC6TGK.js';function s(){let t=crypto.getRandomValues(new Uint8Array(24)),e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(t){if(!t||typeof t!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=t;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(t){return {async delete(e){await t.invoke("openrtc_v2_delete_device_key",{appTag:e});},async getOrCreate(e){let n=d(await t.invoke("openrtc_v2_device_public_key",{appTag:e})),a$1=await a(n);return {publicKeyJwk:n,thumbprint:a$1,async proof(p){let r=s(),o=Math.floor(Date.now()/1e3),i=await t.invoke("openrtc_v2_sign_device_proof",{appTag:e,challenge:p(r,o)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(i))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:n,signature:i,nonce:r,issuedAt:o}}}}}}
|
|
2
2
|
export{v as a};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
|
|
2
|
-
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-
|
|
3
|
-
export { c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, f as OpenRTCCapabilityHandle, h as OpenRTCDevicesHandle, i as OpenRTCDevicesStartOptions, l as OpenRTCRoomHandle, m as OpenRTCRoomJoinOptions, n as OpenRTCSpaceHandle, o as OpenRTCSpaceJoinOptions, p as OpenRTCTicketHandle, q as OpenRTCTicketIssueOptions, r as OpenRTCTransportPreferences, t as OpenRTCUsageUpdate, u as OpenRTCUsageWarning } from './types-
|
|
2
|
+
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-byWIP-WI.js';
|
|
3
|
+
export { c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, f as OpenRTCCapabilityHandle, h as OpenRTCDevicesHandle, i as OpenRTCDevicesStartOptions, l as OpenRTCRoomHandle, m as OpenRTCRoomJoinOptions, n as OpenRTCSpaceHandle, o as OpenRTCSpaceJoinOptions, p as OpenRTCTicketHandle, q as OpenRTCTicketIssueOptions, r as OpenRTCTransportPreferences, t as OpenRTCUsageUpdate, u as OpenRTCUsageWarning } from './types-byWIP-WI.js';
|
|
4
4
|
import './OpenRTCShared-BswnbjpG.js';
|
|
5
5
|
import './types-BHePJWbM.js';
|
|
6
6
|
import './IEngineBridge-BbsT8hof.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-KWXAZUAZ.js';import {c}from'./chunk-23XC6TGK.js';export{a as OPENRTC_ERROR_CODES,b as OpenRtcError,e as classifyOpenRtcFailure,d as openRtcError,c as projectOpenRtcErrorFields}from'./chunk-NT5YHZQH.js';import {d}from'./chunk-K37WVIZL.js';function i(p){return c(p,{platform:"web",runtimeFactory:async e=>{let{createWasmClient:t}=await import('./factories-TLUZAXUG.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:a}=await import('./ipcFactory-QOAZVE56.js');return a(t,e)}})};export{i as OpenRTC};
|
package/dist/native.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
|
|
2
2
|
export { c as classifyNativeIpcFailure, i as isNativeIpcCommandUnavailable } from './ipc-CflAVodw.js';
|
|
3
|
-
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-
|
|
4
|
-
export { b as OpenRTCAccessMode, c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, e as OpenRTCBotVerificationProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannelCatalog, h as OpenRTCDevicesHandle, i as OpenRTCDevicesStartOptions, j as OpenRTCEnrolledDevice, k as OpenRTCLatestStateMode, l as OpenRTCRoomHandle, m as OpenRTCRoomJoinOptions, n as OpenRTCSpaceHandle, o as OpenRTCSpaceJoinOptions, p as OpenRTCTicketHandle, q as OpenRTCTicketIssueOptions, r as OpenRTCTransportPreferences, s as OpenRTCUsageNamespace, t as OpenRTCUsageUpdate, u as OpenRTCUsageWarning } from './types-
|
|
3
|
+
import { O as OpenRTCOptions, a as OpenRTCClient } from './types-byWIP-WI.js';
|
|
4
|
+
export { b as OpenRTCAccessMode, c as OpenRTCAttestationProvider, d as OpenRTCAuthProvider, e as OpenRTCBotVerificationProvider, f as OpenRTCCapabilityHandle, g as OpenRTCChannelCatalog, h as OpenRTCDevicesHandle, i as OpenRTCDevicesStartOptions, j as OpenRTCEnrolledDevice, k as OpenRTCLatestStateMode, l as OpenRTCRoomHandle, m as OpenRTCRoomJoinOptions, n as OpenRTCSpaceHandle, o as OpenRTCSpaceJoinOptions, p as OpenRTCTicketHandle, q as OpenRTCTicketIssueOptions, r as OpenRTCTransportPreferences, s as OpenRTCUsageNamespace, t as OpenRTCUsageUpdate, u as OpenRTCUsageWarning } from './types-byWIP-WI.js';
|
|
5
5
|
import './OpenRTCShared-BswnbjpG.js';
|
|
6
6
|
import './types-BHePJWbM.js';
|
|
7
7
|
import './IEngineBridge-BbsT8hof.js';
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-KWXAZUAZ.js';import {c}from'./chunk-23XC6TGK.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'./chunk-K37WVIZL.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-QOAZVE56.js');return o(t,e)}})}export{m as createNativeOpenRTC};
|
package/dist/openrtc_bg.wasm
CHANGED
|
Binary file
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { d as OpenRTCClient, P as PeerReconciliationStats } from '../OpenRTCShared-BswnbjpG.js';
|
|
2
2
|
export { e as OPENRTC_RUNTIME_POLICY, R as RuntimeClient, f as RuntimePolicySnapshot, D as ScopedConnectionActorError, g as ScopedConnectionActorErrorKind, h as ScopedConnectionActorHandle, i as ScopedConnectionActorHandleOptions, j as ScopedConnectionActorRegistry, k as ScopedConnectionActorState, l as ScopedConnectionClose, m as ScopedConnectionDial, n as ScopedConnectionKey, o as ScopedLogicalChannelHandle, p as ScopedPreferredTransport, q as getRuntimePolicy, r as scopedConnectionKey, s as scopedConnectionKeyToString } from '../OpenRTCShared-BswnbjpG.js';
|
|
3
|
-
import { f as OpenRTCCapabilityHandle } from '../types-
|
|
3
|
+
import { f as OpenRTCCapabilityHandle } from '../types-byWIP-WI.js';
|
|
4
4
|
import { C as Connection, r as RuntimeConnectionTarget, v as RuntimeRawConnection } from '../types-D0pqNSOf.js';
|
|
5
5
|
export { A as ChannelDescriptor, B as ConnectionEvent, D as ConnectionTarget, E as DeviceProfile, I as IncomingStream, P as PeerConnectOptions, F as PeerReadiness, G as PeerStreamOptions, H as PresenceLoopOptions, J as RawConnection, y as RuntimeApplicationPayloadReadinessOptions, K as RuntimeApplicationPayloadRouteOptions, L as RuntimeAuthContext, g as RuntimeAuthIdentity, M as RuntimeAutoConnectPolicy, R as RuntimeChannelDescriptor, a as RuntimeClientOptions, z as RuntimeConnectionEvent, c as RuntimeConnectionStateSnapshot, j as RuntimeDevice, n as RuntimeDeviceConnectOptions, N as RuntimeDevicePresenceStatus, O as RuntimeDeviceStatus, m as RuntimeDeviceStatusSnapshot, f as RuntimeIncomingStream, p as RuntimeJoinRoomOptions, h as RuntimeLocalDeviceInfo, i as RuntimeLocalDeviceProfile, Q as RuntimeLogicalChannelFraming, l as RuntimeManagedSession, S as RuntimeManagedSessionKind, k as RuntimeManagedSessionOptions, T as RuntimeManagedSessionPlatform, e as RuntimePeerConnectOptions, x as RuntimePeerHealth, U as RuntimePeerLifecycleStatus, d as RuntimePeerReadinessSnapshot, V as RuntimePeerScope, W as RuntimePeerSessionSnapshot, b as RuntimePeerState, u as RuntimePeerStreamOptions, w as RuntimePresenceLoopOptions, X as RuntimePresencePolicy, q as RuntimeRoomMember, s as RuntimeScopedChannelOptions, t as RuntimeScopedLogicalChannel, o as RuntimeSession, Y as RuntimeUiConnectionStatus, Z as ScopedChannelOptions, _ as ScopedLogicalChannel, $ as Session, a0 as SessionOptions } from '../types-D0pqNSOf.js';
|
|
6
6
|
import * as Draft14 from '@moq/net';
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as TauriRuntimeAdapter,a as createTauriIpcBridge}from'../chunk-O3D7S5MD.js';export{b as runtimeFromCapability}from'../chunk-
|
|
1
|
+
export{b as TauriRuntimeAdapter,a as createTauriIpcBridge}from'../chunk-O3D7S5MD.js';export{b as runtimeFromCapability}from'../chunk-23XC6TGK.js';export{b as Connection,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-NCL672QJ.js';export{f as IpcRuntimeAdapter}from'../chunk-A7AMB23L.js';import'../chunk-C6PAXO3N.js';import'../chunk-7Z6N46RB.js';export{q as BROWSER_WASM_RUNTIME_CAPABILITIES,r as NATIVE_IPC_RUNTIME_CAPABILITIES,o as OPENRTC_RUNTIME_POLICY,s as cloneRuntimeCapabilities,p as getRuntimePolicy,g as logOpenRtcTeardownTrace,t as runtimeCapabilitiesForBrowserHost,u as runtimeCapabilitiesFromNativeStatus,v as runtimeCapabilityProfile}from'../chunk-JIVVHBCB.js';export{b as openRtcDebug,a as openRtcDebugEnabled,c as openRtcDebugInfo,d as openRtcDebugLog}from'../chunk-VK6KX433.js';import'../chunk-NT5YHZQH.js';export{a as classifyNativeIpcFailure,b as isNativeIpcCommandUnavailable}from'../chunk-K37WVIZL.js';import'../chunk-BXFXPIXO.js';import {b}from'../chunk-N26S7V4N.js';import'../chunk-NB4H5TP3.js';import'../chunk-RD3JEGGF.js';import'../chunk-C7YN5MSV.js';export{a as isRuntimeDeviceActive,c as isRuntimeDeviceConnectable,b as isRuntimeDeviceRoutable}from'../chunk-CK6WQV7J.js';var j="https://api.openrtc.app";function c(e){if(typeof globalThis.crypto?.randomUUID!="function")throw new Error(`Secure request identity is unavailable for ${e}.`);return `${e}:${globalThis.crypto.randomUUID()}`}async function z(e,t,n){let o=e.replace(/\/$/,""),r=await fetch(`${o}/v1/spaces/${encodeURIComponent(n)}/scoped-auth`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":c("enable-space-auth")},body:"{}"}),a=await r.json().catch(()=>({}));if(!r.ok){let s=typeof a?.error=="string"?a.error:`enableSpaceAuth failed (${r.status})`;throw new Error(s)}return a}async function q(e,t,n){let o=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":c("mint-space-token")},body:JSON.stringify(n)}),r=await o.json().catch(()=>({}));if(!o.ok){let a=typeof r?.error=="string"?r.error:`mintSpaceToken failed (${o.status})`;throw new Error(a)}if(typeof r?.token!="string"||!r.token.trim())throw new Error("mintSpaceToken response missing token");return r}function d(e){let t=e.apiKey.trim(),n=(e.spaceKey??e.space??"").trim(),o=g(e.sandboxAppId),r=(e.endpointUrl??j).replace(/\/$/,""),a=e.memberIdStorageKey??`openrtc:space-member:${n}${o?`:sandbox:${o}`:""}`;return async()=>{if(!t||!n)throw new Error("spaceToken requires apiKey and space");let s=null;typeof sessionStorage<"u"?(s=sessionStorage.getItem(a),s||(s=globalThis.crypto?.randomUUID?.()??`member-${Date.now()}`,sessionStorage.setItem(a,s))):s=`member-${Date.now()}`;let m=await b().getAppCheckToken(),i=await fetch(`${r}/v1SpacePublicTokens`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":c("mint-public-space-token"),...m?{"X-Firebase-AppCheck":m}:{}},body:JSON.stringify({apiKey:t,spaceKey:n,memberId:s,...o?{sandboxAppId:o}:{}})}),{text:u,payload:p}=await B(i);if(!i.ok){let f=typeof p?.error=="string"?p.error:u.trim()?u.trim().slice(0,240):`public space token mint failed (${i.status})`;throw new Error(f)}let l=typeof p?.token=="string"?p.token.trim():"";if(!l)throw new Error("public space token response missing token");return {customToken:l}}}function M(e){if(!e.trim())return {};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return {}}}async function B(e){let t=e.text;if(typeof t=="function"){let o=await t.call(e).catch(()=>"");return {text:o,payload:M(o)}}let n=await e.json().catch(()=>({}));return {text:JSON.stringify(n),payload:n&&typeof n=="object"?n:{}}}function g(e){let t=e?.trim().toLowerCase()??"";if(!t)return "";if(!/^[a-z0-9][a-z0-9-]{0,47}$/.test(t))throw new Error("sandboxAppId must be 1-48 lowercase letters, numbers, or dashes.");return t}function J(e,t){let n=e.trim(),o=g(t);return o?`${n}::sandbox::${o}`:n}var L=d,H=d;
|
|
2
2
|
export{d as createPublicSpaceTokenProvider,H as createSpaceTokenProvider,z as enableSpaceAuth,q as mintSpaceToken,J as sandboxSpaceKey,L as spaceToken};
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { d as OpenRTCClient } from './OpenRTCShared-BswnbjpG.js';
|
|
2
2
|
import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
|
|
3
3
|
import { a as RuntimeClientOptions } from './types-D0pqNSOf.js';
|
|
4
|
-
import { O as OpenRTCOptions, a as OpenRTCClient$1 } from './types-
|
|
4
|
+
import { O as OpenRTCOptions, a as OpenRTCClient$1 } from './types-byWIP-WI.js';
|
|
5
5
|
import './types-BHePJWbM.js';
|
|
6
6
|
import './IEngineBridge-BbsT8hof.js';
|
|
7
7
|
import './capabilities-YSskrE8H.js';
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-KWXAZUAZ.js';import {c}from'./chunk-23XC6TGK.js';import {a}from'./chunk-DZCZLRM5.js';import'./chunk-2QHDEGVX.js';import'./chunk-D45U2NXV.js';import'./chunk-EUNCYGJD.js';import'./chunk-IAIGT5G3.js';import'./chunk-N4SX7C3W.js';import'./chunk-NCL672QJ.js';import'./chunk-A7AMB23L.js';import'./chunk-C6PAXO3N.js';import'./chunk-7Z6N46RB.js';import'./chunk-JIVVHBCB.js';import'./chunk-VK6KX433.js';import'./chunk-NT5YHZQH.js';import'./chunk-K37WVIZL.js';import'./chunk-BXFXPIXO.js';import'./chunk-N26S7V4N.js';import'./chunk-NB4H5TP3.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';function m(e,t,n={}){return c(e,{endpoints:t,testingAllowInsecureLoopback:true,platform:"web",...n.deviceId?{deviceIdProvider:async()=>n.deviceId}:{},...n.irohTestRelayUrl?{irohTestRelayUrl:n.irohTestRelayUrl}:{},runtimeFactory:async i=>{let{createWasmClient:o}=await import('./factories-TLUZAXUG.js');return o(i)}})}function d(e,t,n){return c(e,{endpoints:t,testingAllowInsecureLoopback:true,platform:"native",deviceKeyProvider:a$1(n),deviceIdProvider:async()=>{let i=await n.invoke("get_rtc_local_device_info");return String(i?.deviceId??"")},runtimeFactory:async i=>{let{createIpcClient:o}=await import('./ipcFactory-QOAZVE56.js');return o(i,n)}})}function p(e){let t=e.coordinationGateway;return {...e,...t?{coordinationGateway:{...t,testingAllowInsecureLoopback:true}}:{}}}var C=Object.assign(e=>a(p(e)),{native:(e,t)=>a.native(p(e),t)});export{C as createTestingLegacyOpenRTC,d as createTestingNativeOpenRTC,m as createTestingOpenRTC};
|
|
@@ -18,6 +18,13 @@ interface OpenRTCAuthProvider {
|
|
|
18
18
|
getAssertion(input: {
|
|
19
19
|
audience: 'https://api.openrtc.app/v2/assertions/exchange';
|
|
20
20
|
forceRefresh: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Stable OpenRTC installation ID being enrolled. Consumer backends
|
|
23
|
+
* may bind product admission (for example a paid device allowance) to
|
|
24
|
+
* this value in the signed assertion. It is supplied only for an
|
|
25
|
+
* enrollment/renewal assertion, never for hourly gateway refreshes.
|
|
26
|
+
*/
|
|
27
|
+
deviceId: string;
|
|
21
28
|
}): Promise<string | null>;
|
|
22
29
|
/**
|
|
23
30
|
* Optional identity-epoch observer. Notify only when the signed-in
|
package/package.json
CHANGED
package/dist/chunk-IAEGDK4P.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var T=new Map;function P(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 V(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return P(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function q(){return P(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function O(){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 W(a){let e=await O().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 B(a,e){let t=await O().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 z(a){T.delete(a);let e=await O().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 Z(a){let e=await W(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await B(a,t),t}var J={async getOrCreate(a){let e=await Z(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await V(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=q(),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:P(s),nonce:r,issuedAt:o}}}},delete:z};var N={"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":287514e-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 R={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},j=1440*6e4,f=class extends Error{constructor(t,i){super(t);this.status=i;this.name="OpenRTCV2HttpError";}};function k(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function A(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function X(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 U(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 F(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+j||!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(U(r[0]))),s=v(a.token);}catch{return null}if(o.alg!=="EdDSA"||a.signingPublicJwk.kid&&o.kid!==a.signingPublicJwk.kid)return null;try{let u=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},u,U(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),d=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(d)||l>=d||d*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function Q(a,e,t,i){try{let n=globalThis.localStorage?.getItem(k(a,e,t));if(!n)return null;let r=JSON.parse(n),o=await F(r,a,t,i,e);return o?{token:o.token,expiresAtMs:o.expiresAtMs,principalId:e,signingPublicJwk:o.signingPublicJwk}:null}catch{return null}}async function Y(a,e,t,i){try{let n=globalThis.localStorage?.getItem(A(a,t));return n?await F(JSON.parse(n),e,t,i):null}catch{return null}}function ee(a,e,t,i){try{globalThis.localStorage?.setItem(k(a,e,t),JSON.stringify(i));}catch{}}function te(a,e,t){try{globalThis.localStorage?.setItem(A(a,e),JSON.stringify({token:t.token,expiresAtMs:t.expiresAtMs,principalId:t.principalId,signingPublicJwk:t.signingPublicJwk}));}catch{}}function $(a,e,t,i){try{globalThis.localStorage?.removeItem(k(a,e,t)),i&&globalThis.localStorage?.removeItem(A(i,t));}catch{}}function ie(a){return `${a}_${crypto.randomUUID()}`}async function ne(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 v(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 C=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=ie("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}).`;try{let d=await s.json();typeof d.error=="string"&&(c=d.error.slice(0,256));}catch{}let l=new f(c,s.status);if(r=l,o===0&&[502,503,504].includes(s.status))continue;throw l}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 ne(this.apiKey,t):t,s=await(await this.key()).proof((u,p)=>["openrtc:v2:capability",this.apiKey,e,r,u,p].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 d={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return d.renew=()=>this.capability(e,t,i,n),d}async deviceCertificate(e,t,i){let n=this.authEpoch(e),r=n.devices.get(t)??{};if(n.devices.set(t,r),r.current&&r.current.expiresAtMs>Date.now()+j)return this.deviceCertificateResult(e,t,i,{...r.current,enrolled:false});if(!r.inFlight){let s=n.generation;r.inFlight=this.resolveAuthenticatedDevice(e,t,n).then(c=>{if(n.generation!==s)throw new Error("The OpenRTC authentication identity changed during enrollment.");return r.current=c,c}).finally(()=>{r.inFlight=void 0;});}let o=await r.inFlight;return this.deviceCertificateResult(e,t,i,o)}async resolveAuthenticatedDevice(e,t,i){let n=await this.key();if(e.getSessionKey){let r=await e.getSessionKey();if(!r)throw new Error("The OpenRTC auth provider has no active principal.");let o=await X(this.appTag,n.thumbprint,r);i.sessionKeyHash=o;let s=await Y(o,this.appTag,t,n.thumbprint);if(s)return s}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash)}deviceCertificateResult(e,t,i,n){let r={type:"device-certificate",token:n.token,avenue:i??{kind:"user",id:n.principalId},expiresAtMs:n.expiresAtMs};return r.renew=async()=>(await this.deviceCertificate(e,t,i)).source,{principalId:n.principalId,source:r,enrolled:n.enrolled}}async enrollAuthenticatedDevice(e,t,i){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let n=async p=>{let h=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:p});if(!h)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:h,...e.providerId?{providerId:e.providerId}:{}})},r;try{r=await n(!1);}catch(p){if(!(p instanceof f)||p.status!==401)throw p;r=await n(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let o=await this.key(),s=await Q(this.appTag,r.principalId,t,o.thumbprint);if(s)return {...s,principalId:r.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let c=await o.proof((p,h)=>["openrtc:v2:device-enroll",this.appTag,r.principalId,t,p,h].join(":")),l=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${r.principalId}:${t}:${c.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:t,deviceProof:c,...l?{attestation:l}:{}});this.record("device.enroll"),l&&this.record("security.attestation.verify");let u={principalId:r.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,signingPublicJwk:d.signingPublicJwk,enrolled:true};return ee(this.appTag,r.principalId,t,{token:u.token,expiresAtMs:u.expiresAtMs,signingPublicJwk:u.signingPublicJwk}),i&&te(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);$(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);$(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){if(e.type!=="device-certificate")throw new Error("Device management requires an authenticated device certificate.");let o=v(e.token),s=String(o.jti??""),l=await(await this.key()).proof((p,h)=>["openrtc:v2:device-management",s,i,n??"",r?"except-current":"include-current",p,h].join(":")),d=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;d&&this.before(d);let u=await this.post("/v2/devices/manage",{action:i,deviceCertificate:e.token,currentDeviceId:t,...n?{targetDeviceId:n}:{},...r?{exceptCurrent:true}:{},deviceProof:l});return d&&this.record(d),u}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=v(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=v(n.token),d=String(l.jti??""),p=await(await this.key()).proof((y,b)=>["openrtc:v2:gateway-grant",d,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,y,b].join(":")),h=await this.post("/v2/gateway/grants",{credentialType:n.type,credential:n.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:p,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{}});return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),s&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),h})();i=o;try{return await o}finally{i===o&&(i=null);}}}};var S=new WeakMap;function ye(a){let e=S.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function re(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 g(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}function ae(a){let e=a?.trim();if(e){if(new TextEncoder().encode(e).byteLength>4*1024)throw new Error("[OpenRTC] Device profile metadata must not exceed 4 KiB.");return e}}var G=/^[A-Za-z0-9_.:@-]{1,160}$/,se=/^[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 L(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return se.test(t)?t:e}function oe(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return L(i?.deviceId)}catch{return null}}function ce(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&oe(i,a)||L(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 H(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function I(a){let e=v(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 x=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);}},D=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:(N[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"}));}},m=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;S.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{S.delete(this),this.onClosed();}}}},E=class extends m{constructor(t,i,n){super("devices",t,i,n);this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=()=>this.client.devices.list();this.listWithStatus=()=>this.client.devices.listWithStatus();this.watch=this.client.devices.watch;this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;}},K=class extends m{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},w=class extends m{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();}},M=class extends m{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},_=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new x;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={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.");return this.controlPlane.listEnrolledDevices(t,await this.deviceId())},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=H(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(o=>o.retireDeviceIfPresent(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();await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${g(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:${g(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:${g(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=re(e.apiKey),this.usage=new D(e.usage),this.controlPlane=new C(this.apiKey,t.endpoints??R,t.deviceKeyProvider??J,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):ce(this.controlPlane.appTag);return H(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,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??R).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,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName}),[s,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared-TKAQLONA.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(),n=await this.controlPlane.deviceCertificate(t,i),r=await this.activate({kind:"devices",id:n.principalId,source:n.source,principalId:n.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:e.profile?.name,deviceMetadata:ae(e.profile?.metadata)}),o;return o=new E(n.principalId,r,()=>{this.channels.detach(r),this.onClosed(o);}),this.handles.add(o),o}async joinSpace(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:I(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),s;return s=new K(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=g(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 d=t.auth??this.options.auth;if(!d)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let u=await this.deviceId(),p=await this.controlPlane.deviceCertificate(d,u,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"join");let h;try{h=await this.activate({kind:"room",id:i,source:p.source,principalId:p.principalId,deviceId:u,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(b){throw n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"leave").catch(()=>{}),b}let y;return y=new w(i,h,()=>{this.channels.detach(h),this.onClosed(y);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(p.source,i,"leave");}:void 0),this.handles.add(y),y}let o=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),s=String(v(o.token).principalId),c=await this.activate({kind:"room",id:i,source:o,principalId:s,deviceId:I(o),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new w(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:I(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),s;return s=new M(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 ge(a,e){return new _(a,e)}
|
|
2
|
-
export{V as a,ye as b,ge as c};
|