Display link to EvenHub apps' privacy policy on first run

This commit is contained in:
James Babcock committed 2026-08-16 22:33:04 -07:00
1 parent 604da990a1
commit 526a236193
9 files changed
+361 -29

No files matched your search

@@ -55,6 +55,17 @@
android:usesCleartextTraffic="true"
android:hardwareAccelerated="true">
<!-- Read-only content URIs for cached documents handed to system viewers. -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths" />
</provider>
<activity
android:name="com.tns.NativeScriptActivity"
android:label="@string/title_activity_kimera"
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path
name="privacy_policies"
path="privacy-policies/" />
</paths>
+22 -1
View File
@@ -34,6 +34,8 @@ export type EvenHubManifest = {
networkWhitelist: string[];
/** Normalized declared permissions (both manifest shapes). */
permissions: EvenHubPermission[];
/** App privacy policy, when a locally supplied manifest declares one. */
privacyPolicyUrl: string;
raw: Record<string, unknown>;
};
@@ -119,6 +121,12 @@ export function parseManifest(appJsonText: string): EvenHubManifest {
const entrypoint = String(raw.entrypoint ?? "index.html");
const permissions = parsePermissions(raw.permissions);
const privacyPolicyUrl = firstSafeHttpsUrl(
raw.privacy_link,
raw.privacyLink,
raw.privacy_policy_url,
raw.privacyPolicyUrl,
);
const networkWhitelist: string[] = [];
for (const permission of permissions) {
if (permission.name === "network" && permission.whitelist) {
@@ -126,5 +134,18 @@ export function parseManifest(appJsonText: string): EvenHubManifest {
}
}
return { packageId, name, version, entrypoint, networkWhitelist, permissions, raw };
return { packageId, name, version, entrypoint, networkWhitelist, permissions, privacyPolicyUrl, raw };
}
function firstSafeHttpsUrl(...values: unknown[]): string {
for (const value of values) {
if (typeof value !== "string" || value.length > 2048) continue;
try {
const url = new URL(value.trim());
if (url.protocol === "https:") return url.toString();
} catch {
// Try the next supported manifest spelling.
}
}
return "";
}
+41 -2
View File
@@ -50,6 +50,13 @@ type DownloadMetadata = {
url?: unknown;
size?: unknown;
public_key?: unknown;
privacy_link?: unknown;
meta?: unknown;
};
export type EvenHubAppDownload = {
bytes: Uint8Array;
privacyPolicyUrl: string;
};
export function isEvenHubStoreConfigured(): boolean {
@@ -86,7 +93,7 @@ export class EvenHubApiClient {
}
/** Resolve the signed download URL, then fetch and sanity-check its EHPK. */
async downloadApp(packageId: string): Promise<Uint8Array> {
async downloadApp(packageId: string): Promise<EvenHubAppDownload> {
const data = await this.authenticatedRequest("POST", "/v2/evenhub/app/download", {
body: { package_id: packageId, branch: "public" },
});
@@ -104,7 +111,16 @@ export class EvenHubApiClient {
if (bytes.length < 20 || bytes[0] !== 0x45 || bytes[1] !== 0x48 || bytes[2] !== 0x50 || bytes[3] !== 0x4b) {
throw new Error("EvenHub download is not an EHPK package.");
}
return bytes;
return {
bytes,
// The production API currently returns a CDN-relative `privacy_link`
// at the response root. Accept the nested serialization shape too.
privacyPolicyUrl: resolvePrivacyPolicyUrl(
stringValue(metadata.privacy_link).trim()
? metadata.privacy_link
: asRecord(metadata.meta).privacy_link,
),
};
}
/** Download one public storefront asset, constrained to Even's CDN path. */
@@ -363,3 +379,26 @@ function finiteNumber(value: unknown): number {
const number = Number(value);
return Number.isFinite(number) ? number : 0;
}
function resolvePrivacyPolicyUrl(value: unknown): string {
if (typeof value !== "string" || value.length > 2048) return "";
const candidate = value.trim();
if (!candidate) return "";
try {
const url = new URL(candidate);
return url.protocol === "https:" ? url.toString() : "";
} catch {
// Even stores uploaded policies as public-CDN-relative paths, just like
// app icons. Keep relative resolution constrained to that CDN namespace.
const cleanPath = candidate.replace(/^\/+/, "");
if (
!/^prod\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/i.test(cleanPath)
|| cleanPath.includes("..")
|| candidate.startsWith("//")
|| candidate.includes("\\")
) {
return "";
}
return `${PUBLIC_CDN_HOST}/${cleanPath}`;
}
}
+9
View File
@@ -157,6 +157,15 @@ export function readEvenHubPackageManifest(path: string): EvenHubManifest | null
}
}
/** Inspect already-loaded package bytes before installation/first-run approval. */
export function readEvenHubPackageManifestBytes(bytes: Uint8Array): EvenHubManifest | null {
try {
return inspectEhpk(bytes).manifest;
} catch {
return null;
}
}
/** Remove the stored EHPK, unpacked runtime files, and registry entry. */
export function uninstallEvenHubPackage(packageId: string): boolean {
const apps = getInstalledEvenHubApps();
+27 -10
View File
@@ -4,6 +4,7 @@ import { truncateText } from "../../graphics/textwrap";
import { Layer, type DashboardInputEvent, type LayerContext, type PaintBelow } from "../../ui/layers";
import { drawSelectionHighlight } from "../../ui/menu";
import { permissionDetail, permissionLabel, type EvenHubPermission } from "./permissions";
import { openPrivacyPolicyOnPhone } from "./privacy-policy";
const DIALOG_X = 8;
const DIALOG_Y = 8;
@@ -18,17 +19,18 @@ const ACTION_ROW_HEIGHT = 20;
/**
* Confirmation dialog listing the permissions an EvenHub app declares, shown
* before installing it or running an uninstalled package. Allow proceeds;
* Cancel (or double-click) backs out. Apps that declare no permissions never
* reach this dialog — the caller runs them directly.
* Cancel (or double-click) backs out. A privacy-policy-only app still reaches
* this dialog so the user can review the policy before allowing first run.
*/
export class EvenHubPermissionDialogLayer implements Layer {
/** 0 = Allow, 1 = Cancel. */
/** Starts on Allow; the optional privacy-policy action is inserted after it. */
private selectedIndex = 0;
private resolved = false;
constructor(
private readonly appName: string,
private readonly permissions: EvenHubPermission[],
private readonly privacyPolicyUrl: string,
private readonly onConfirm: () => void,
private readonly onCancel: () => void,
) {}
@@ -44,17 +46,23 @@ export class EvenHubPermissionDialogLayer implements Layer {
(sum, permission) => sum + PERM_LABEL_STEP + (permissionDetail(permission) ? PERM_DETAIL_STEP : 0) + PERM_GAP,
0,
);
const bodyTop = PADDING + HEADER_STEP + 6 + permsHeight + 6;
const height = Math.min(bodyTop + 2 * ACTION_ROW_HEIGHT + PADDING, viewportHeight - 2 * DIALOG_Y);
const emptyPermissionsHeight = this.permissions.length === 0 ? PERM_LABEL_STEP + PERM_GAP : 0;
const bodyTop = PADDING + HEADER_STEP + 6 + permsHeight + emptyPermissionsHeight + 6;
const height = Math.min(bodyTop + this.actions().length * ACTION_ROW_HEIGHT + PADDING, viewportHeight - 2 * DIALOG_Y);
// Fill 1 (transparent color key is 0), outline for the dialog edge.
image.fillRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 1);
image.drawRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 72);
let y = DIALOG_Y + PADDING;
image.drawText(font, left, y, truncateText(font, `${this.appName} needs:`, textWidth), 235);
const heading = this.permissions.length ? `${this.appName} needs:` : `${this.appName} is ready to run`;
image.drawText(font, left, y, truncateText(font, heading, textWidth), 235);
y += HEADER_STEP + 6;
if (this.permissions.length === 0) {
image.drawText(font, left, y, "No special permissions requested.", 140);
y += emptyPermissionsHeight;
}
for (const permission of this.permissions) {
image.drawText(font, left, y, truncateText(font, permissionLabel(permission.name), textWidth), 220);
y += PERM_LABEL_STEP;
@@ -68,7 +76,7 @@ export class EvenHubPermissionDialogLayer implements Layer {
y += 2;
const focused = ctx.stack.isFocused();
const actions = ["Allow", "Cancel"];
const actions = this.actions();
for (let index = 0; index < actions.length; index++) {
const rowY = y + index * ACTION_ROW_HEIGHT;
const selected = index === this.selectedIndex;
@@ -81,15 +89,20 @@ export class EvenHubPermissionDialogLayer implements Layer {
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
const actions = this.actions();
switch (event.type) {
case "scroll-up":
this.selectedIndex = (this.selectedIndex + 1) % 2;
this.selectedIndex = (this.selectedIndex + actions.length - 1) % actions.length;
return;
case "scroll-down":
this.selectedIndex = (this.selectedIndex + 1) % 2;
this.selectedIndex = (this.selectedIndex + 1) % actions.length;
return;
case "click":
this.resolve(ctx, this.selectedIndex === 0);
if (actions[this.selectedIndex] === "Privacy policy") {
openPrivacyPolicyOnPhone(this.privacyPolicyUrl, this.appName);
} else {
this.resolve(ctx, actions[this.selectedIndex] === "Allow");
}
return;
case "double-click":
this.resolve(ctx, false);
@@ -114,4 +127,8 @@ export class EvenHubPermissionDialogLayer implements Layer {
if (confirmed) this.onConfirm();
else this.onCancel();
}
private actions(): string[] {
return this.privacyPolicyUrl ? ["Allow", "Privacy policy", "Cancel"] : ["Allow", "Cancel"];
}
}
+150
View File
@@ -0,0 +1,150 @@
import { Application } from "@nativescript/core";
declare const android: any;
declare const androidx: any;
declare const java: any;
const MAX_POLICY_BYTES = 10_000_000;
const POLICY_DOWNLOAD_TIMEOUT_MS = 30_000;
/** Open an app privacy policy on the phone, using a native viewer for PDFs. */
export function openPrivacyPolicyOnPhone(value: string, appName: string): boolean {
const url = safeHttpsUrl(value);
const activity = Application.android?.foregroundActivity ?? Application.android?.startActivity;
if (!url || !activity) return false;
if (isPdfUrl(url)) {
void downloadAndOpenPdf(url, appName, activity).catch((error) => {
console.warn(`evenhub: could not open privacy policy PDF: ${error}`);
if (!openExternalUrl(url, activity)) {
showOpenError(activity, appName);
}
});
return true;
}
showWebPolicy(url, appName, activity);
return true;
}
/** Show an untrusted HTML policy in an isolated, bridge-free phone WebView. */
function showWebPolicy(url: string, appName: string, activity: any): void {
const webView = new android.webkit.WebView(activity);
const settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(false);
webView.setWebViewClient(new android.webkit.WebViewClient());
const container = new android.widget.FrameLayout(activity);
const displayHeight = activity.getResources().getDisplayMetrics().heightPixels;
container.addView(
webView,
new android.widget.FrameLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
Math.max(1, Math.round(displayHeight * 0.72)),
),
);
const dialog = new android.app.AlertDialog.Builder(activity)
.setTitle(`${appName} privacy policy`)
.setView(container)
.setNegativeButton("Close", null)
.create();
dialog.setOnDismissListener(
new android.content.DialogInterface.OnDismissListener({
onDismiss: () => webView.destroy(),
}),
);
dialog.show();
const window = dialog.getWindow();
if (window) {
window.setLayout(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
);
}
webView.loadUrl(url);
}
async function downloadAndOpenPdf(url: string, appName: string, activity: any): Promise<void> {
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const timeout = new Promise<never>((_resolve, reject) => {
timeoutHandle = setTimeout(() => reject(new Error("Privacy policy download timed out.")), POLICY_DOWNLOAD_TIMEOUT_MS);
});
let response: Response;
try {
response = await Promise.race([fetch(url), timeout]);
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
if (!response.ok) throw new Error(`Privacy policy download failed (HTTP ${response.status}).`);
const declaredSize = Number(response.headers.get("Content-Length") ?? 0);
if (declaredSize > MAX_POLICY_BYTES) throw new Error("Privacy policy PDF is unexpectedly large.");
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.length < 5 || bytes.length > MAX_POLICY_BYTES || !hasPdfMagic(bytes)) {
throw new Error("Privacy policy response is not a valid PDF.");
}
const directory = new java.io.File(activity.getCacheDir(), "privacy-policies");
if (!directory.exists() && !directory.mkdirs()) throw new Error("Could not create the privacy policy cache.");
const hash = Number(new java.lang.String(url).hashCode()) >>> 0;
const file = new java.io.File(directory, `policy-${hash.toString(16)}.pdf`);
const stream = new java.io.FileOutputStream(file);
try {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
stream.getChannel().write(buffer);
} finally {
stream.close();
}
const authority = `${activity.getPackageName()}.fileprovider`;
const contentUri = androidx.core.content.FileProvider.getUriForFile(activity, authority, file);
const intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, "application/pdf");
intent.setClipData(android.content.ClipData.newRawUri("Privacy policy", contentUri));
intent.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(android.content.Intent.createChooser(intent, `${appName} privacy policy`));
}
function openExternalUrl(url: string, activity: any): boolean {
try {
const intent = new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url));
intent.addCategory(android.content.Intent.CATEGORY_BROWSABLE);
activity.startActivity(intent);
return true;
} catch (error) {
console.warn(`evenhub: no browser available for privacy policy: ${error}`);
return false;
}
}
function showOpenError(activity: any, appName: string): void {
new android.app.AlertDialog.Builder(activity)
.setTitle(`${appName} privacy policy`)
.setMessage("No app is available to display this privacy policy PDF.")
.setPositiveButton("Close", null)
.show();
}
function isPdfUrl(value: string): boolean {
try {
return new URL(value).pathname.toLowerCase().endsWith(".pdf");
} catch {
return false;
}
}
function hasPdfMagic(bytes: Uint8Array): boolean {
return bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d;
}
function safeHttpsUrl(value: string): string {
if (!value || value.length > 2048) return "";
try {
const url = new URL(value);
return url.protocol === "https:" ? url.toString() : "";
} catch {
return "";
}
}
+85 -12
View File
@@ -1,19 +1,23 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { truncateText, wrapText } from "../../graphics/textwrap";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../../ui/gestures";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../../ui/gestures";
import { type DashboardInputEvent, type Layer, type LayerContext } from "../../ui/layers";
import { drawSelectionHighlight } from "../../ui/menu";
import { TextViewerLayer } from "../files/text-viewer";
import { evenHubApi, type EvenHubStoreApp } from "./even-api";
import {
getInstalledEvenHubApp,
installEvenHubPackageBytes,
installedEvenHubAppId,
readEvenHubPackageManifestBytes,
setInstalledEvenHubIcon,
type EvenHubInstallIcon,
} from "./installed-apps";
import { EvenHubPermissionDialogLayer } from "./permission-dialog";
const X = 18;
const BUTTON_HEIGHT = 24;
const ACTION_HEIGHT = 24;
export type EvenHubStoreDetailOptions = {
launchApp: (appId: string) => Promise<void> | void;
@@ -22,6 +26,8 @@ export type EvenHubStoreDetailOptions = {
/** Storefront metadata and the Install/Launch action for one public app. */
export class EvenHubStoreDetailLayer implements Layer {
/** About, What's New, Install/Launch. */
private selectedIndex = 2;
private working = false;
private detailPromise: Promise<void> | null = null;
private status = "";
@@ -64,22 +70,28 @@ export class EvenHubStoreDetailLayer implements Layer {
}
const installed = getInstalledEvenHubApp(this.app.packageId);
if (installed) {
const actions = ["About", "What's New", this.working ? "Installing..." : installed ? "Launch" : "Install"];
const actionTop = height - 22 - actions.length * ACTION_HEIGHT;
if (installed && !this.status) {
image.drawText(font, X, y + 2, `Installed version ${installed.version}`, 155);
}
if (this.status) {
image.drawText(font, X, Math.min(height - 58, y + 18), truncateText(font, this.status, textWidth), 180);
image.drawText(font, X, Math.min(actionTop - 14, y + 2), truncateText(font, this.status, textWidth), 180);
}
const buttonY = height - 48;
drawSelectionHighlight(image, X - 5, buttonY, textWidth + 10, BUTTON_HEIGHT, ctx.stack.isFocused(), 8);
const label = this.working ? "Installing..." : installed ? "Launch" : "Install";
image.drawText(font, X + 6, buttonY + 5, label, this.working ? 145 : 245);
for (let index = 0; index < actions.length; index++) {
const actionY = actionTop + index * ACTION_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, X - 5, actionY, textWidth + 10, ACTION_HEIGHT - 1, ctx.stack.isFocused(), 8);
}
image.drawText(font, X + 6, actionY + 5, actions[index]!, this.working && index === 2 ? 145 : selected ? 245 : 190);
}
image.drawText(
font,
X,
height - 16,
`${GESTURE_CLICK} ${installed ? "launch" : "install"} ${GESTURE_DOUBLE_CLICK} back`,
`${GESTURE_SCROLL} select ${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} back`,
105,
);
return image;
@@ -90,21 +102,43 @@ export class EvenHubStoreDetailLayer implements Layer {
if (!this.working) ctx.stack.pop();
return;
}
if (event.type !== "click" || this.working) return;
if (this.working) return;
if (event.type === "scroll-up") {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
return;
}
if (event.type === "scroll-down") {
this.selectedIndex = Math.min(2, this.selectedIndex + 1);
return;
}
if (event.type !== "click") return;
await this.ensureDetail(ctx);
if (this.selectedIndex === 0) {
ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About"));
return;
}
if (this.selectedIndex === 1) {
ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New"));
return;
}
const installed = getInstalledEvenHubApp(this.app.packageId);
if (installed) {
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
return;
}
await this.prepareInstall(ctx);
}
private async prepareInstall(ctx: LayerContext): Promise<void> {
this.working = true;
this.status = `Downloading ${this.app.name}...`;
ctx.actions.requestRender();
try {
const [bytes, icon] = await Promise.all([
const [download, icon] = await Promise.all([
evenHubApi.downloadApp(this.app.packageId),
this.app.iconPath
? evenHubApi.downloadPublicAsset(this.app.iconPath).catch((error) => {
@@ -113,8 +147,47 @@ export class EvenHubStoreDetailLayer implements Layer {
})
: Promise.resolve(undefined),
]);
this.status = "Installing...";
const manifest = readEvenHubPackageManifestBytes(download.bytes);
if (!manifest) throw new Error("The downloaded EHPK manifest could not be read.");
const privacyPolicyUrl = download.privacyPolicyUrl || manifest.privacyPolicyUrl;
this.working = false;
this.status = "";
ctx.actions.requestRender();
if (manifest.permissions.length > 0 || privacyPolicyUrl) {
ctx.stack.push(
new EvenHubPermissionDialogLayer(
manifest.name,
manifest.permissions,
privacyPolicyUrl,
() => {
void this.installAndLaunch(ctx, download.bytes, icon);
},
() => {
this.status = "Installation canceled.";
ctx.actions.requestRender();
},
),
);
return;
}
await this.installAndLaunch(ctx, download.bytes, icon);
} catch (error) {
this.working = false;
this.status = cleanError(error);
this.options.appendLog(`evenhub store: ${this.status}`);
ctx.actions.requestRender();
}
}
private async installAndLaunch(
ctx: LayerContext,
bytes: Uint8Array,
icon: EvenHubInstallIcon | undefined,
): Promise<void> {
this.working = true;
this.status = "Installing...";
ctx.actions.requestRender();
try {
const result = installEvenHubPackageBytes(bytes, {
expectedPackageId: this.app.packageId,
icon,
+10 -4
View File
@@ -143,17 +143,23 @@ export function createImageDocumentWindow(
/**
* Show the permission-confirmation dialog for an .ehpk before install/run,
* then run `proceed` if the user allows. Packages that declare no permissions
* skip the dialog and proceed immediately.
* then run `proceed` if the user allows. Packages with neither permissions nor
* a privacy policy skip the dialog and proceed immediately.
*/
function confirmEhpkPermissions(ctx: LayerContext, entry: DirectoryEntry, proceed: () => void): void {
const manifest = readEvenHubPackageManifest(entry.path);
if (!manifest || manifest.permissions.length === 0) {
if (!manifest || (manifest.permissions.length === 0 && !manifest.privacyPolicyUrl)) {
proceed();
return;
}
ctx.stack.push(
new EvenHubPermissionDialogLayer(manifest.name, manifest.permissions, proceed, () => {}),
new EvenHubPermissionDialogLayer(
manifest.name,
manifest.permissions,
manifest.privacyPolicyUrl,
proceed,
() => {},
),
);
}