46 lines
2.5 KiB
JavaScript
46 lines
2.5 KiB
JavaScript
// Artifacts are documents, not app destinations. Android can capture even
|
|
// _blank links inside an installed PWA's scope; use an explicit VIEW hand-off
|
|
// there, retaining ordinary URLs for copy/share and every other environment.
|
|
|
|
export function artifactBrowserLinkProps(value, environment = globalThis) {
|
|
if (typeof value !== "string" || value.trim() === "") return null;
|
|
let url;
|
|
try {
|
|
url = new URL(String(value ?? ""), environment.location?.href);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
|
|
const standalone = environment.navigator?.standalone === true ||
|
|
environment.matchMedia?.("(display-mode: standalone)")?.matches === true ||
|
|
environment.matchMedia?.("(display-mode: fullscreen)")?.matches === true;
|
|
const userAgent = environment.navigator?.userAgent ?? "";
|
|
const android = /Android/i.test(userAgent);
|
|
// An implicit HTTPS VIEW intent can resolve straight back to this WebAPK.
|
|
// Pin the browser family, never the installed app's link-capturing package.
|
|
const browserPackage = /EdgA\//i.test(userAgent) ? "com.microsoft.emmx"
|
|
: /SamsungBrowser\//i.test(userAgent) ? "com.sec.android.app.sbrowser"
|
|
: /OPR\//i.test(userAgent) ? "com.opera.browser"
|
|
: /Firefox\//i.test(userAgent) ? "org.mozilla.firefox"
|
|
: "com.android.chrome";
|
|
// Intent.parseUri uses the LAST #Intent marker, so an original document
|
|
// fragment remains data. Every field after our marker is fixed or encoded;
|
|
// untrusted artifact names/fragments cannot inject intent extras or packages.
|
|
const href = android && standalone
|
|
? `intent:${url.href.slice(url.protocol.length)}#Intent;scheme=${url.protocol.slice(0, -1)};action=android.intent.action.VIEW;category=android.intent.category.BROWSABLE;package=${browserPackage};S.browser_fallback_url=${encodeURIComponent(url.href)};end`
|
|
: url.href;
|
|
return { href, target: "_blank", rel: "external noopener noreferrer", referrerpolicy: "no-referrer" };
|
|
}
|
|
|
|
/** Recognize same-origin artifacts, including root-relative Markdown links;
|
|
* never turn arbitrary SPA paths or javascript/data URLs into navigation. */
|
|
export function isLocalArtifactLink(value, base) {
|
|
if (!String(value ?? "").startsWith("/artifacts/") && !/^https?:\/\//i.test(String(value ?? ""))) return false;
|
|
try {
|
|
const url = new URL(value, base);
|
|
return url.origin === new URL(base).origin && url.pathname.startsWith("/artifacts/");
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|