diff --git a/src/app/handle/page.tsx b/src/app/handle/page.tsx new file mode 100644 index 00000000..82d6345b --- /dev/null +++ b/src/app/handle/page.tsx @@ -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 ( + +

Phone links

+

+ smshub opens tel: and sms: links: texts go out from your smshub number, and calls hand + over to your phone. +

+ +
+ ); + } + + 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 ( + +

{link.kind === "tel" ? "Call" : "Text"}

+

{shown}

+ {link.body ?

{link.body}

: null} + +
+ {textHere && (user ? hasLine : true) ? ( + + Text from smshub + + ) : null} + + {link.kind === "tel" ? "Call from this device" : "Text from this device"} + +
+ + {link.kind === "tel" ? ( +

+ smshub does not place calls from the browser. Call from your phone, or send a text from your smshub number + instead. +

+ ) : null} + + {user && !hasLine ? ( +
+

You need an smshub number to text from.

+ + Rent a number or connect your own Twilio or Telnyx number + +
+ ) : null} + +
+ +

+ Numbers, compute, hosting, agents and people for hire are all on the{" "} + + c0mpute.com market + + . +

+
+
+ ); +} + +function Shell({ children }: { children: React.ReactNode }) { + return
{children}
; +} diff --git a/src/app/inbox/page.tsx b/src/app/inbox/page.tsx index 05f67daa..b3625bf1 100644 --- a/src/app/inbox/page.tsx +++ b/src/app/inbox/page.tsx @@ -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 @@ -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 } diff --git a/src/components/inbox-client.tsx b/src/components/inbox-client.tsx index b112b909..954c1914 100644 --- a/src/components/inbox-client.tsx +++ b/src/components/inbox-client.tsx @@ -91,6 +91,7 @@ export function InboxClient({ rentPriceUsd = 5, unfinishedOrder = null, paypalEnabled = false, + compose = null, }: { conversations: Conversation[]; numbers?: LineNumber[]; @@ -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; }) { @@ -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(null); const searchRef = useRef(null); @@ -206,6 +209,8 @@ export function InboxClient({ onClose={() => setShowNewMessage(false)} onSent={reloadConversations} defaultNumberId={activeLine?.id} + initialRecipient={compose?.to} + initialBody={compose?.body} /> {/* Sidebar */} diff --git a/src/components/new-message-modal.tsx b/src/components/new-message-modal.tsx index 53158efe..8b868d70 100644 --- a/src/components/new-message-modal.tsx +++ b/src/components/new-message-modal.tsx @@ -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([]); const [selectedNumberId, setSelectedNumberId] = useState(""); const [recipientPhone, setRecipientPhone] = useState(""); @@ -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; diff --git a/src/components/phone-link-handler-button.tsx b/src/components/phone-link-handler-button.tsx new file mode 100644 index 00000000..11fd731d --- /dev/null +++ b/src/components/phone-link-handler-button.tsx @@ -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

This browser cannot hand phone links to a website.

; + } + + 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" ? ( +

+ Your browser asked whether smshub.dev may open phone links. If you allowed it, tel: and sms: links now open here. +

+ ) : ( + + ); +} diff --git a/src/lib/__tests__/phone-uri.test.ts b/src/lib/__tests__/phone-uri.test.ts new file mode 100644 index 00000000..05612922 --- /dev/null +++ b/src/lib/__tests__/phone-uri.test.ts @@ -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"); + }); +}); diff --git a/src/lib/phone-uri.ts b/src/lib/phone-uri.ts new file mode 100644 index 00000000..256c9172 --- /dev/null +++ b/src/lib/phone-uri.ts @@ -0,0 +1,79 @@ +/** + * tel: and sms: links, as a browser hands them to smshub.dev/handle?uri=%s + * (navigator.registerProtocolHandler) or TronBrowser forwards a click. + * + * RFC 3966 (tel) and RFC 5724 (sms): `tel:+1-800-555-1212`, `sms:+18005551212?body=hi`, + * `sms:+1555...,+1555...` (several recipients; the first is used), plus the + * non-standard `sms://` and `smsto:` forms some pages still write. + */ +export type PhoneUri = { + kind: "tel" | "sms"; + /** E.164 (`+18005551212`) when the number is dialable, else null. */ + e164: string | null; + /** The number as written, for display when it is not E.164-shaped. */ + raw: string; + /** Prefilled text (sms `body=`), trimmed to 1600 characters. */ + body: string; +}; + +const SCHEME = /^\s*(tel|sms|smsto|callto):(?:\/\/)?/i; + +/** Digits with an optional leading +; a bare 10-digit number is taken as US/Canada. */ +export function toE164(input: string): string | null { + const s = String(input ?? "").trim(); + const plus = s.startsWith("+"); + const digits = s.replace(/[^\d]/g, ""); + if (!digits) return null; + if (plus) return digits.length >= 8 && digits.length <= 15 ? `+${digits}` : null; + if (digits.length === 10) return `+1${digits}`; + if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`; + return null; +} + +export function parsePhoneUri(uri: string | null | undefined): PhoneUri | null { + if (!uri) return null; + let s = String(uri); + try { + // The browser substitutes %s percent-encoded; a hand-typed link may not be. + if (/%[0-9a-f]{2}/i.test(s) && !SCHEME.test(s)) s = decodeURIComponent(s); + } catch { + return null; + } + const m = SCHEME.exec(s); + if (!m) return null; + const kind = /^tel|callto$/i.test(m[1]) ? "tel" : "sms"; + const rest = s.slice(m[0].length); + const [target, query = ""] = rest.split("?", 2); + // RFC 3966 parameters (;ext=, ;phone-context=) follow the number. + let raw = target.split(";")[0]; + try { + raw = decodeURIComponent(raw); + } catch { + /* keep as written */ + } + raw = raw.split(",")[0].trim().slice(0, 40); + let body = ""; + if (kind === "sms" && query) { + try { + body = new URLSearchParams(query).get("body") ?? ""; + } catch { + body = ""; + } + } + if (!raw) return null; + return { kind, e164: toE164(raw), raw, body: body.slice(0, 1600) }; +} + +/** `+18005551212` as `+1 (800) 555-1212`; other countries stay E.164. */ +export function formatPhone(e164: string): string { + const m = /^\+1(\d{3})(\d{3})(\d{4})$/.exec(e164); + return m ? `+1 (${m[1]}) ${m[2]}-${m[3]}` : e164; +} + +/** The inbox URL that opens New Message prefilled. */ +export function composeHref(p: Pick): string { + const q = new URLSearchParams(); + if (p.e164) q.set("compose", p.e164); + if (p.body) q.set("body", p.body); + return `/inbox?${q.toString()}`; +}