Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/app/handle/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { composeHref, formatPhone, parsePhoneUri } from "@/lib/phone-uri";
import { PhoneLinkHandlerButton } from "@/components/phone-link-handler-button";

export const metadata: Metadata = {
title: "Call or text — smshub",
description: "Open a tel: or sms: link with smshub: text from your smshub number, or call and text from your phone.",
robots: { index: false },
};

/**
* The handler for tel: and sms: links: navigator.registerProtocolHandler sends
* `/handle?uri=sms%3A%2B1...` here, and TronBrowser forwards clicks the same way.
*
* An sms: link from someone signed in with a line goes straight to New Message,
* prefilled. Everything else gets this page: the number, "text it from smshub",
* "use your phone" (the original link, which TronBrowser leaves alone here via
* data-tron-native) and, with no line yet, how to get one.
*/
export default async function HandlePhoneLinkPage({
searchParams,
}: {
searchParams: Promise<{ uri?: string | string[] }>;
}) {
const { uri } = await searchParams;
const link = parsePhoneUri(Array.isArray(uri) ? uri[0] : uri);

if (!link) {
return (
<Shell>
<h1 className="text-3xl font-bold">Phone links</h1>
<p className="text-gray-400">
smshub opens <code>tel:</code> and <code>sms:</code> links: texts go out from your smshub number, and calls hand
over to your phone.
</p>
<PhoneLinkHandlerButton />
</Shell>
);
}

const supabase = await createServerSupabaseClient();
const {
data: { user },
} = await supabase.auth.getUser();

let hasLine = false;
if (user) {
const { count } = await supabase
.from("phone_numbers")
.select("id", { count: "exact", head: true })
.eq("user_id", user.id)
.eq("status", "active");
hasLine = (count ?? 0) > 0;
}

const compose = link.e164 ? composeHref(link) : null;
if (link.kind === "sms" && hasLine && compose) redirect(compose);

const shown = link.e164 ? formatPhone(link.e164) : link.raw;
const native = `${link.kind}:${link.e164 ?? link.raw}${link.body ? `?body=${encodeURIComponent(link.body)}` : ""}`;
const textHere = compose ? (user ? compose : `/login?next=${encodeURIComponent(compose)}`) : null;

return (
<Shell>
<p className="text-sm uppercase tracking-wide text-gray-500">{link.kind === "tel" ? "Call" : "Text"}</p>
<h1 className="text-4xl font-bold tabular-nums">{shown}</h1>
{link.body ? <p className="text-gray-300 whitespace-pre-wrap border-l-2 border-gray-700 pl-3">{link.body}</p> : null}

<div className="flex flex-wrap gap-3">
{textHere && (user ? hasLine : true) ? (
<Link href={textHere} className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white font-medium">
Text from smshub
</Link>
) : null}
<a
href={native}
data-tron-native=""
className="px-4 py-2 rounded-lg border border-gray-700 hover:border-gray-500 text-gray-200"
>
{link.kind === "tel" ? "Call from this device" : "Text from this device"}
</a>
</div>

{link.kind === "tel" ? (
<p className="text-sm text-gray-500">
smshub does not place calls from the browser. Call from your phone, or send a text from your smshub number
instead.
</p>
) : null}

{user && !hasLine ? (
<div className="rounded-xl border border-gray-800 p-4 space-y-2">
<p className="text-gray-300">You need an smshub number to text from.</p>
<Link href="/inbox" className="text-blue-400 hover:text-blue-300">
Rent a number or connect your own Twilio or Telnyx number
</Link>
</div>
) : null}

<div className="pt-6 border-t border-gray-800 space-y-3">
<PhoneLinkHandlerButton />
<p className="text-sm text-gray-500">
Numbers, compute, hosting, agents and people for hire are all on the{" "}
<a href="https://c0mpute.com/market" className="text-blue-400 hover:text-blue-300">
c0mpute.com market
</a>
.
</p>
</div>
</Shell>
);
}

function Shell({ children }: { children: React.ReactNode }) {
return <div className="max-w-xl mx-auto px-4 py-16 space-y-6">{children}</div>;
}
21 changes: 19 additions & 2 deletions src/app/inbox/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,31 @@ import { getBrand } from "@/lib/brand-server";
import { priceUsdPerMonth } from "@/lib/plans";
import { unfinishedOrder } from "@/lib/managed-numbers/recovery";
import { paypalEnabled } from "@/lib/coinpay/checkout";
import { toE164 } from "@/lib/phone-uri";

export default async function InboxPage({
searchParams,
}: {
searchParams: Promise<{ compose?: string | string[]; body?: string | string[] }>;
}) {
// /inbox?compose=+1...&body=... (from /handle, i.e. a tel:/sms: link) opens New Message prefilled.
const sp = await searchParams;
const first = (v?: string | string[]) => (Array.isArray(v) ? v[0] : v) ?? "";
const composeTo = toE164(first(sp.compose));
const compose = composeTo ? { to: composeTo, body: first(sp.body).slice(0, 1600) } : null;

export default async function InboxPage() {
const supabase = await createServerSupabaseClient();
const {
data: { user },
} = await supabase.auth.getUser();

if (!user) {
redirect("/login");
const q = new URLSearchParams();
if (compose) {
q.set("compose", compose.to);
if (compose.body) q.set("body", compose.body);
}
redirect(compose ? `/login?next=${encodeURIComponent(`/inbox?${q}`)}` : "/login");
}

const { data: conversations } = await supabase
Expand Down Expand Up @@ -58,6 +74,7 @@ export default async function InboxPage() {
userId={user.id}
rentPriceUsd={priceUsdPerMonth()}
paypalEnabled={paypalEnabled()}
compose={compose}
unfinishedOrder={
unfinished
? { id: unfinished.id, amountUsd: Number(unfinished.amount_usd), months: unfinished.months, chain: unfinished.chain }
Expand Down
7 changes: 6 additions & 1 deletion src/components/inbox-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export function InboxClient({
rentPriceUsd = 5,
unfinishedOrder = null,
paypalEnabled = false,
compose = null,
}: {
conversations: Conversation[];
numbers?: LineNumber[];
Expand All @@ -99,6 +100,8 @@ export function InboxClient({
rentPriceUsd?: number;
/** An order that expired unpaid, offered back in one click. */
unfinishedOrder?: UnfinishedOrder | null;
/** Open New Message to this number with this text (from a tel:/sms: link). */
compose?: { to: string; body: string } | null;
/** PayPal checkout is offered (SMSHUB_PAYPAL_ENABLED, issue #146). */
paypalEnabled?: boolean;
}) {
Expand Down Expand Up @@ -129,7 +132,7 @@ export function InboxClient({
reloadConversations,
handleContactUpdated,
} = useInbox(initialConversations, numbers);
const [showNewMessage, setShowNewMessage] = useState(false);
const [showNewMessage, setShowNewMessage] = useState(!!compose);
const [, setSelectedIndex] = useState(-1);
const messagesEndRef = useRef<HTMLDivElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
Expand Down Expand Up @@ -206,6 +209,8 @@ export function InboxClient({
onClose={() => setShowNewMessage(false)}
onSent={reloadConversations}
defaultNumberId={activeLine?.id}
initialRecipient={compose?.to}
initialBody={compose?.body}
/>

{/* Sidebar */}
Expand Down
16 changes: 15 additions & 1 deletion src/components/new-message-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ interface NewMessageModalProps {
onSent: () => void;
/** Preselects this number as "From", e.g. the line the inbox is filtered to. */
defaultNumberId?: string;
/** Prefills "To" (e.g. from a tel:/sms: link via /handle). */
initialRecipient?: string;
/** Prefills the message (an sms: link's body=). */
initialBody?: string;
}

export function NewMessageModal({ isOpen, onClose, onSent, defaultNumberId }: NewMessageModalProps) {
export function NewMessageModal({ isOpen, onClose, onSent, defaultNumberId, initialRecipient, initialBody }: NewMessageModalProps) {
const [phoneNumbers, setPhoneNumbers] = useState<PhoneNumber[]>([]);
const [selectedNumberId, setSelectedNumberId] = useState("");
const [recipientPhone, setRecipientPhone] = useState("");
Expand All @@ -39,6 +43,16 @@ export function NewMessageModal({ isOpen, onClose, onSent, defaultNumberId }: Ne
if (isOpen && defaultNumberId) setSelectedNumberId(defaultNumberId);
}, [isOpen, defaultNumberId]);

// Fill once per prefill value, so typing over it is never reset.
const prefilled = useRef("");
useEffect(() => {
const key = `${initialRecipient ?? ""}\n${initialBody ?? ""}`;
if (!isOpen || !initialRecipient || prefilled.current === key) return;
prefilled.current = key;
setRecipientPhone(initialRecipient);
if (initialBody) setMessageBody(initialBody);
}, [isOpen, initialRecipient, initialBody]);

useEffect(() => {
if (!isOpen) return;

Expand Down
48 changes: 48 additions & 0 deletions src/components/phone-link-handler-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client";

import { useEffect, useState } from "react";

/**
* Makes smshub.dev the browser's handler for tel: and sms: links, so a click on
* one anywhere opens /handle here instead of an OS dialer that may not exist.
* Chrome, Edge and Firefox allow both schemes (they are on the HTML safelist);
* TronBrowser routes them here already and hides this button.
*/
export function PhoneLinkHandlerButton() {
const [state, setState] = useState<"idle" | "asked" | "unsupported" | "tron">("idle");

useEffect(() => {
if (document.documentElement.dataset.tronPhoneLinks === "smshub") setState("tron");
else if (typeof navigator.registerProtocolHandler !== "function") setState("unsupported");
}, []);

if (state === "tron") return null;
if (state === "unsupported") {
return <p className="text-sm text-gray-500">This browser cannot hand phone links to a website.</p>;
}

const register = () => {
const url = `${window.location.origin}/handle?uri=%s`;
try {
navigator.registerProtocolHandler("tel", url);
navigator.registerProtocolHandler("sms", url);
setState("asked");
} catch {
setState("unsupported");
}
};

return state === "asked" ? (
<p className="text-sm text-gray-400">
Your browser asked whether smshub.dev may open phone links. If you allowed it, tel: and sms: links now open here.
</p>
) : (
<button
type="button"
onClick={register}
className="text-sm px-3 py-1.5 rounded-lg border border-gray-700 text-gray-300 hover:text-white hover:border-gray-500"
>
Open phone links with smshub.dev
</button>
);
}
55 changes: 55 additions & 0 deletions src/lib/__tests__/phone-uri.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { composeHref, formatPhone, parsePhoneUri, toE164 } from "../phone-uri";

describe("parsePhoneUri", () => {
it("reads tel: with punctuation", () => {
expect(parsePhoneUri("tel:+1-800-555-1212")).toEqual({ kind: "tel", e164: "+18005551212", raw: "+1-800-555-1212", body: "" });
});

it("reads a percent-encoded uri the browser substituted for %s", () => {
expect(parsePhoneUri(encodeURIComponent("sms:+19166599471?body=hi there"))?.body).toBe("hi there");
});

it("takes sms body and the first of several recipients", () => {
const p = parsePhoneUri("sms:+15551230001,+15551230002?body=Hello%20you");
expect(p).toMatchObject({ kind: "sms", e164: "+15551230001", body: "Hello you" });
});

it("accepts sms://, smsto: and callto: forms", () => {
expect(parsePhoneUri("sms://8005551212")?.e164).toBe("+18005551212");
expect(parsePhoneUri("smsto:8005551212")?.kind).toBe("sms");
expect(parsePhoneUri("callto:+442071234567")).toMatchObject({ kind: "tel", e164: "+442071234567" });
});

it("drops RFC 3966 parameters", () => {
expect(parsePhoneUri("tel:+18005551212;ext=42")?.e164).toBe("+18005551212");
});

it("refuses other schemes and empties", () => {
expect(parsePhoneUri("javascript:alert(1)")).toBeNull();
expect(parsePhoneUri("https://evil.test")).toBeNull();
expect(parsePhoneUri("tel:")).toBeNull();
expect(parsePhoneUri(null)).toBeNull();
});

it("keeps a short code or vanity number as raw with no e164", () => {
expect(parsePhoneUri("sms:56789")).toMatchObject({ e164: null, raw: "56789" });
});
});

describe("toE164 / formatPhone / composeHref", () => {
it("normalizes US numbers", () => {
expect(toE164("(800) 555-1212")).toBe("+18005551212");
expect(toE164("1 800 555 1212")).toBe("+18005551212");
expect(toE164("555-1212")).toBeNull();
});

it("formats NANP and leaves others", () => {
expect(formatPhone("+18005551212")).toBe("+1 (800) 555-1212");
expect(formatPhone("+442071234567")).toBe("+442071234567");
});

it("builds the inbox compose link", () => {
expect(composeHref({ e164: "+18005551212", body: "hi & bye" })).toBe("/inbox?compose=%2B18005551212&body=hi+%26+bye");
});
});
Loading
Loading