webRemoteControlRelayAuthProvider.ts 972 B

12345678910111213141516171819202122232425262728293031323334
  1. import type { WebRemoteControlRelayRole } from "@zcode/shared";
  2. function base64UrlNoPadding(bytes: Uint8Array): string {
  3. const base64 = btoa(String.fromCharCode(...bytes));
  4. return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
  5. }
  6. export async function calculateBrowserWebRemoteControlProof(
  7. passHash: string,
  8. nonce: string,
  9. role: WebRemoteControlRelayRole,
  10. deviceSid: string,
  11. ): Promise<string> {
  12. const encoder = new TextEncoder();
  13. const key = await globalThis.crypto.subtle.importKey(
  14. "raw",
  15. encoder.encode(passHash),
  16. { name: "HMAC", hash: "SHA-256" },
  17. false,
  18. ["sign"],
  19. );
  20. const signature = await globalThis.crypto.subtle.sign(
  21. "HMAC",
  22. key,
  23. encoder.encode(`${nonce}|${role}|${deviceSid}`),
  24. );
  25. return base64UrlNoPadding(new Uint8Array(signature));
  26. }
  27. export function createBrowserWebRemoteControlRelayAuthProvider() {
  28. return {
  29. calculateProof: calculateBrowserWebRemoteControlProof,
  30. };
  31. }