Fix native-safe connection offer decoding
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ConnectionOfferSchema,
|
||||
decodeOfferFragmentPayload,
|
||||
parseConnectionOfferFromUrl,
|
||||
} from "./connection-offer.js";
|
||||
|
||||
function encodeBase64UrlNoPadUtf8(input: string): string {
|
||||
return Buffer.from(input, "utf8")
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/g, "");
|
||||
}
|
||||
|
||||
describe("connection offer", () => {
|
||||
it("decodes base64url JSON payloads", () => {
|
||||
const payload = {
|
||||
v: 2,
|
||||
serverId: "server-123",
|
||||
daemonPublicKeyB64: "pubkey",
|
||||
relay: { endpoint: "relay.paseo.sh:443" },
|
||||
};
|
||||
|
||||
expect(decodeOfferFragmentPayload(encodeBase64UrlNoPadUtf8(JSON.stringify(payload)))).toEqual(
|
||||
payload,
|
||||
);
|
||||
});
|
||||
|
||||
it("parses connection offers from QR-style URLs", () => {
|
||||
const offer = ConnectionOfferSchema.parse({
|
||||
v: 2,
|
||||
serverId: "server-123",
|
||||
daemonPublicKeyB64: "pubkey",
|
||||
relay: { endpoint: "relay.paseo.sh:443" },
|
||||
});
|
||||
const encoded = encodeBase64UrlNoPadUtf8(JSON.stringify(offer));
|
||||
|
||||
expect(parseConnectionOfferFromUrl(`https://app.paseo.sh/#offer=${encoded}`)).toEqual(offer);
|
||||
});
|
||||
|
||||
it("returns null when the URL has no offer fragment", () => {
|
||||
expect(parseConnectionOfferFromUrl("https://app.paseo.sh/pair")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
@@ -24,7 +23,9 @@ export type ConnectionOffer = ConnectionOfferV2;
|
||||
function decodeBase64UrlToUtf8(input: string): string {
|
||||
const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
||||
return Buffer.from(padded, "base64").toString("utf8");
|
||||
const binary = globalThis.atob(padded);
|
||||
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
}
|
||||
|
||||
export function decodeOfferFragmentPayload(encoded: string): unknown {
|
||||
|
||||
Reference in New Issue
Block a user