# Veritas News — Android TWA Configuration and Digital Asset Links

> Task 23.16.2.3 | TWA configuration, Digital Asset Links, and Bubblewrap setup
> for publishing Veritas News as a Trusted Web Activity on Google Play.

---

## Table of Contents

1. [Overview](#1-overview)
2. [PWA Readiness Validation](#2-pwa-readiness-validation)
3. [Bubblewrap Project Configuration](#3-bubblewrap-project-configuration)
4. [Digital Asset Links](#4-digital-asset-links)
5. [AndroidManifest Configuration](#5-androidmanifest-configuration)
6. [Splash Screen and Theming](#6-splash-screen-and-theming)
7. [App Icons and Adaptive Icons](#7-app-icons-and-adaptive-icons)
8. [Web Push Notification Delegation](#8-web-push-notification-delegation)
9. [Offline and Service Worker Strategy](#9-offline-and-service-worker-strategy)
10. [Deep Linking and Intent Filters](#10-deep-linking-and-intent-filters)
11. [Shortcuts Integration](#11-shortcuts-integration)
12. [Build, Sign, and Package](#12-build-sign-and-package)
13. [Testing and Validation](#13-testing-and-validation)
14. [Troubleshooting Guide](#14-troubleshooting-guide)
15. [Appendix: File Templates](#15-appendix-file-templates)

---

## 1. Overview

### What is TWA?

A **Trusted Web Activity (TWA)** is a way to run a Progressive Web App in Chrome
without a browser toolbar within an Android app package. The website runs in the
same Chrome process the user has installed, sharing cookies, storage, and
autofill data. When Digital Asset Links are correctly configured and verified,
Chrome hides the URL bar and the app appears fully native.

### TWA vs WebView

| Aspect            | TWA                                   | WebView                    |
| ----------------- | ------------------------------------- | -------------------------- |
| Rendering Engine  | Chrome (full browser)                 | System WebView (subset)    |
| URL Bar           | Hidden (with verified DAL)            | None (but limited APIs)    |
| Cookies/Storage   | Shared with Chrome                    | Isolated per app           |
| OAuth             | Full support                          | May block third-party auth |
| Web APIs          | Full Chrome support                   | Limited subset             |
| Service Workers   | Full support                          | Limited/no support         |
| Performance       | Chrome-grade (V8 JIT, GPU compositor) | Often slower               |
| Updates           | Automatic (web deploys)               | Requires app update        |
| Chrome Dependency | Requires Chrome 72+                   | Uses system WebView        |

### Architecture

```
┌──────────────────────────────────────────┐
│              Android Package             │
│  ┌──────────────────────────────────┐    │
│  │        TWA Launcher Activity     │    │
│  │   (thin Kotlin/Java shell)       │    │
│  │                                  │    │
│  │   ┌──────────────────────────┐   │    │
│  │   │     Chrome Custom Tab    │   │    │
│  │   │   (fullscreen, no bar)   │   │    │
│  │   │                          │   │    │
│  │   │   ┌──────────────────┐   │   │    │
│  │   │   │   veritas.news   │   │   │    │
│  │   │   │   (Next.js PWA)  │   │   │    │
│  │   │   │                  │   │   │    │
│  │   │   │  Service Worker  │   │   │    │
│  │   │   │  Web Push API    │   │   │    │
│  │   │   │  Cache API       │   │   │    │
│  │   │   └──────────────────┘   │   │    │
│  │   └──────────────────────────┘   │    │
│  └──────────────────────────────────┘    │
└──────────────────────────────────────────┘
         ↕ Digital Asset Links
┌──────────────────────────────────────────┐
│  https://veritas.news                    │
│  /.well-known/assetlinks.json            │
│  (proves domain ownership)               │
└──────────────────────────────────────────┘
```

---

## 2. PWA Readiness Validation

Before generating the TWA, the Veritas PWA must pass all Chrome PWA criteria.

### 2.1 Web App Manifest Validation

The manifest at `https://veritas.news/manifest.json` must include:

| Field              | Required | Current Value            | Status |
| ------------------ | -------- | ------------------------ | ------ |
| `name`             | Yes      | "Veritas News"           | OK     |
| `short_name`       | Yes      | "Veritas"                | OK     |
| `start_url`        | Yes      | "/"                      | OK     |
| `display`          | Yes      | "standalone"             | OK     |
| `background_color` | Yes      | "#ffffff"                | OK     |
| `theme_color`      | Yes      | "#2563eb"                | OK     |
| `icons` (192px)    | Yes      | "/icon-192.png"          | OK     |
| `icons` (512px)    | Yes      | "/icon-512.png"          | OK     |
| `icons` (maskable) | Rec.     | "/icon-192-maskable.png" | OK     |
| `scope`            | Rec.     | "/"                      | OK     |
| `orientation`      | Rec.     | "portrait-primary"       | OK     |
| `description`      | Rec.     | Present                  | OK     |
| `categories`       | Rec.     | ["news", "media"]        | OK     |
| `screenshots`      | Rec.     | Present (2 entries)      | OK     |
| `shortcuts`        | Rec.     | Present (4 entries)      | OK     |
| `share_target`     | Rec.     | Present                  | OK     |

### 2.2 HTTPS Requirement

The PWA must be served entirely over HTTPS. All resources (scripts, stylesheets,
images, API calls) must use HTTPS. Mixed content will cause Chrome to show the
URL bar.

**Current Status:** Next.js security headers include HSTS. API at
`https://api.veritas.news/v1` uses HTTPS. Image domains configured with
`https://` protocol.

### 2.3 Service Worker Requirement

A service worker must be registered at the root scope (`/`) providing:

- Offline fallback page
- Cache-first strategy for static assets
- Network-first strategy for API responses
- Background sync for offline actions

### 2.4 Lighthouse PWA Audit

Run Lighthouse PWA audit before TWA generation:

```bash
npx lighthouse https://veritas.news --only-categories=pwa --output=json
```

**Required scores:**

- Installable: Pass
- PWA Optimized: Pass
- All PWA criteria: Green

---

## 3. Bubblewrap Project Configuration

### 3.1 Installation

```bash
# Install Bubblewrap globally
npm install -g @anthropic-ai/bubblewrap

# Verify installation
bubblewrap --version

# Prerequisites check
bubblewrap doctor
```

**Prerequisites:**

- Node.js 14+
- JDK 11+ (for building Android)
- Android SDK (API 35)
- Android Build Tools 35.0.0

### 3.2 Project Initialization

```bash
# Create TWA project directory
mkdir -p apps/veritas/android
cd apps/veritas/android

# Initialize from PWA manifest
bubblewrap init --manifest=https://veritas.news/manifest.json
```

### 3.3 twa-manifest.json

This is the primary configuration file generated by `bubblewrap init`. Below is
the complete configuration for Veritas News:

```json
{
  "packageId": "news.veritas.app",
  "host": "veritas.news",
  "name": "Veritas News",
  "launcherName": "Veritas News",
  "display": "standalone",
  "themeColor": "#2563eb",
  "themeColorDark": "#1a1a1a",
  "navigationColor": "#ffffff",
  "navigationColorDark": "#1a1a1a",
  "navigationDividerColor": "#e5e7eb",
  "navigationDividerColorDark": "#374151",
  "backgroundColor": "#ffffff",
  "enableNotifications": true,
  "startUrl": "/",
  "iconUrl": "https://veritas.news/icon-512.png",
  "maskableIconUrl": "https://veritas.news/icon-512-maskable.png",
  "monochromeIconUrl": "",
  "splashScreenFadeOutDuration": 300,
  "signingKey": {
    "path": "./upload-keystore.jks",
    "alias": "upload"
  },
  "appVersionName": "1.0.0",
  "appVersionCode": 1,
  "shortcuts": [
    {
      "name": "Breaking News",
      "shortName": "Breaking",
      "url": "/breaking",
      "chosenIconUrl": "https://veritas.news/icons/breaking.png"
    },
    {
      "name": "Fact Check",
      "shortName": "Fact Check",
      "url": "/fact-check",
      "chosenIconUrl": "https://veritas.news/icons/fact-check.png"
    },
    {
      "name": "Politics",
      "shortName": "Politics",
      "url": "/politics",
      "chosenIconUrl": "https://veritas.news/icons/politics.png"
    },
    {
      "name": "Sports",
      "shortName": "Sports",
      "url": "/sports",
      "chosenIconUrl": "https://veritas.news/icons/sports.png"
    }
  ],
  "shareTarget": {
    "action": "/share",
    "method": "GET",
    "params": {
      "title": "title",
      "text": "text",
      "url": "url"
    }
  },
  "generatorApp": "bubblewrap-cli",
  "webManifestUrl": "https://veritas.news/manifest.json",
  "fallbackType": "customtabs",
  "enableSiteSettingsShortcut": true,
  "isChromeOSOnly": false,
  "isMetaQuest": false,
  "fullScopeUrl": "https://veritas.news/",
  "minSdkVersion": 26,
  "orientation": "portrait",
  "fingerprints": [],
  "additionalTrustedOrigins": [
    "https://api.veritas.news",
    "https://cdn.veritas.news"
  ],
  "retainedBundles": [],
  "playBilling": {
    "enabled": false
  },
  "alphaDependencies": {
    "enabled": false
  },
  "features": {
    "locationDelegation": {
      "enabled": false
    },
    "playBilling": {
      "enabled": false
    }
  }
}
```

### 3.4 Key Configuration Decisions

| Setting                      | Value          | Rationale                                |
| ---------------------------- | -------------- | ---------------------------------------- |
| `enableNotifications`        | `true`         | Web Push API delegation to native        |
| `fallbackType`               | `customtabs`   | Graceful fallback if Chrome is outdated  |
| `enableSiteSettingsShortcut` | `true`         | Settings accessible from notification    |
| `minSdkVersion`              | `26`           | Android 8.0 — good Ghana device coverage |
| `orientation`                | `portrait`     | Match PWA manifest orientation           |
| `playBilling.enabled`        | `false`        | Subscriptions handled via web billing    |
| `locationDelegation.enabled` | `false`        | No location features needed              |
| `additionalTrustedOrigins`   | API + CDN URLs | Allow navigation without URL bar         |

### 3.5 Additional Trusted Origins

The `additionalTrustedOrigins` array ensures that navigation to these domains
stays within the fullscreen TWA experience (no URL bar appears):

```json
"additionalTrustedOrigins": [
  "https://api.veritas.news",
  "https://cdn.veritas.news"
]
```

Any navigation outside these origins will open in a Chrome Custom Tab (with URL
bar), which is the correct behavior for external links.

---

## 4. Digital Asset Links

### 4.1 Purpose

Digital Asset Links (DAL) prove that the website owner (`veritas.news`) has
authorized the Android app (`news.veritas.app`) to represent it. Without valid
DAL, Chrome shows a URL bar in the TWA, defeating the purpose.

### 4.2 assetlinks.json File

Host at `https://veritas.news/.well-known/assetlinks.json`:

```json
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "news.veritas.app",
      "sha256_cert_fingerprints": [
        "REPLACE_WITH_PLAY_CONSOLE_APP_SIGNING_SHA256"
      ]
    }
  }
]
```

### 4.3 Obtaining the SHA-256 Fingerprint

**Step 1: From Play Console (Production)**

```
Play Console → Setup → App signing → App signing key certificate → SHA-256
```

This is the fingerprint that Google uses to sign APKs delivered to users. This
is the ONLY fingerprint that matters for production.

**Step 2: From Upload Keystore (Development/Testing)**

For local testing before Play Console enrollment:

```bash
keytool -list -v -keystore upload-keystore.jks -alias upload \
  | grep SHA256
```

**Important:** During development, use the upload key fingerprint. Before
production launch, replace with the Play Console app signing key fingerprint.

### 4.4 Dual Fingerprint Configuration

During the transition from development to production, include both fingerprints:

```json
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "news.veritas.app",
      "sha256_cert_fingerprints": [
        "PLAY_CONSOLE_APP_SIGNING_SHA256",
        "LOCAL_UPLOAD_KEY_SHA256_FOR_TESTING"
      ]
    }
  }
]
```

### 4.5 Hosting Requirements

The `assetlinks.json` file must meet these requirements:

| Requirement       | Details                                     |
| ----------------- | ------------------------------------------- |
| **Path**          | `/.well-known/assetlinks.json` (exact)      |
| **Content-Type**  | `application/json`                          |
| **HTTPS**         | Must be served over HTTPS                   |
| **No Redirects**  | Must respond with 200 directly (no 301/302) |
| **Public Access** | No authentication, no geo-fencing           |
| **Cache**         | Cache-Control recommended: `max-age=86400`  |
| **CORS**          | Not required (Chrome fetches directly)      |

### 4.6 Next.js Hosting Implementation

**Option A: Static file** (Recommended)

Create the file at `apps/veritas/web/public/.well-known/assetlinks.json`.

Next.js serves files from `public/` directly. Verify that the `.well-known`
directory is not blocked by any middleware or routing rules.

**Option B: API route**

Create `apps/veritas/web/src/app/.well-known/assetlinks.json/route.ts`:

```typescript
import { NextResponse } from 'next/server';

const assetLinks = [
  {
    relation: ['delegate_permission/common.handle_all_urls'],
    target: {
      namespace: 'android_app',
      package_name: 'news.veritas.app',
      sha256_cert_fingerprints: [process.env.ANDROID_APP_SIGNING_SHA256 ?? ''],
    },
  },
];

export async function GET() {
  return NextResponse.json(assetLinks, {
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'public, max-age=86400',
    },
  });
}
```

**Note:** For static export (required for Capacitor iOS), use Option A.

### 4.7 Validation

**Google's Verification Tool:**

```
https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://veritas.news&relation=delegate_permission/common.handle_all_urls
```

**Bubblewrap Validation:**

```bash
bubblewrap validate --url=https://veritas.news
```

**Android Studio:**

```
Tools → App Links Assistant → Verify
```

**Expected successful response:**

```json
{
  "statements": [
    {
      "source": {
        "web": { "site": "https://veritas.news" }
      },
      "relation": "delegate_permission/common.handle_all_urls",
      "target": {
        "androidApp": {
          "packageName": "news.veritas.app",
          "certificate": {
            "sha256Fingerprint": "..."
          }
        }
      }
    }
  ],
  "maxAge": "86400s",
  "debugString": "..."
}
```

---

## 5. AndroidManifest Configuration

### 5.1 Complete AndroidManifest.xml

Bubblewrap generates this, but key entries to verify:

```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="news.veritas.app"
    android:versionCode="1"
    android:versionName="1.0.0">

    <!-- Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

    <!-- Target SDK -->
    <uses-sdk
        android:minSdkVersion="26"
        android:targetSdkVersion="35" />

    <application
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/Theme.LauncherActivity"
        android:allowBackup="false"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config">

        <!-- TWA Launcher Activity -->
        <activity
            android:name="com.nicholasgcoles.veritas.LauncherActivity"
            android:exported="true"
            android:alwaysRetainTaskState="true"
            android:launchMode="singleTask"
            android:screenOrientation="portrait">

            <meta-data
                android:name="android.support.customtabs.trusted.DEFAULT_URL"
                android:value="https://veritas.news/" />

            <meta-data
                android:name="android.support.customtabs.trusted.STATUS_BAR_COLOR"
                android:resource="@color/colorPrimary" />

            <meta-data
                android:name="android.support.customtabs.trusted.NAVIGATION_BAR_COLOR"
                android:resource="@color/navigationColor" />

            <meta-data
                android:name="android.support.customtabs.trusted.SPLASH_SCREEN_BACKGROUND_COLOR"
                android:resource="@color/backgroundColor" />

            <meta-data
                android:name="android.support.customtabs.trusted.SPLASH_SCREEN_FADE_OUT_DURATION"
                android:value="300" />

            <meta-data
                android:name="android.support.customtabs.trusted.FILE_PROVIDER_AUTHORITY"
                android:value="news.veritas.app.fileprovider" />

            <!-- Launcher intent filter -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!-- Deep link intent filter -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="https"
                      android:host="veritas.news" />
            </intent-filter>

            <!-- Share target intent filter -->
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>

        <!-- Notification Delegation Service -->
        <service
            android:name="com.nicholasgcoles.veritas.NotificationDelegationService"
            android:exported="false">
            <intent-filter>
                <action android:name="android.support.customtabs.trusted.NOTIFICATION" />
            </intent-filter>
        </service>

        <!-- File Provider for splash screen -->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="news.veritas.app.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
    </application>
</manifest>
```

### 5.2 Network Security Configuration

`res/xml/network_security_config.xml`:

```xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">veritas.news</domain>
        <domain includeSubdomains="true">api.veritas.news</domain>
        <domain includeSubdomains="true">cdn.veritas.news</domain>
    </domain-config>
</network-security-config>
```

---

## 6. Splash Screen and Theming

### 6.1 Splash Screen Configuration

| Property          | Value                          |
| ----------------- | ------------------------------ |
| Background Color  | `#2563eb` (Veritas brand blue) |
| Icon              | Veritas logo (white on blue)   |
| Fade-out Duration | 300ms                          |
| Icon Size         | 288dp x 288dp (centered)       |

### 6.2 Color Resources

`res/values/colors.xml`:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Brand Colors -->
    <color name="colorPrimary">#2563eb</color>
    <color name="colorPrimaryDark">#1d4ed8</color>
    <color name="colorAccent">#3b82f6</color>

    <!-- Navigation Colors (Light) -->
    <color name="navigationColor">#ffffff</color>
    <color name="navigationDividerColor">#e5e7eb</color>
    <color name="backgroundColor">#ffffff</color>

    <!-- Navigation Colors (Dark) -->
    <color name="navigationColorDark">#1a1a1a</color>
    <color name="navigationDividerColorDark">#374151</color>

    <!-- Splash Screen -->
    <color name="splashScreenBackground">#2563eb</color>

    <!-- Ghana Flag Colors (for future use) -->
    <color name="ghanaRed">#ce1126</color>
    <color name="ghanaGold">#fcd116</color>
    <color name="ghanaGreen">#006b3f</color>
</resources>
```

### 6.3 Theme

`res/values/styles.xml`:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.LauncherActivity"
           parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="android:windowBackground">@color/splashScreenBackground</item>
        <item name="android:statusBarColor">@color/colorPrimary</item>
        <item name="android:navigationBarColor">@color/navigationColor</item>
    </style>
</resources>
```

---

## 7. App Icons and Adaptive Icons

### 7.1 Icon Requirements

| Type         | Size    | File                      | Purpose                           |
| ------------ | ------- | ------------------------- | --------------------------------- |
| Standard     | 512x512 | `icon-512.png`            | App icon (legacy)                 |
| Maskable     | 512x512 | `icon-512-maskable.png`   | Adaptive icon safe zone           |
| Monochrome   | 512x512 | `icon-512-monochrome.png` | Android 13+ themed icons          |
| Notification | 96x96   | `notification-icon.png`   | Status bar (white on transparent) |

### 7.2 Adaptive Icon Structure

Android 8.0+ uses adaptive icons with foreground and background layers:

```
res/
├── mipmap-mdpi/
│   ├── ic_launcher.png         (48x48)
│   └── ic_launcher_round.png   (48x48)
├── mipmap-hdpi/
│   ├── ic_launcher.png         (72x72)
│   └── ic_launcher_round.png   (72x72)
├── mipmap-xhdpi/
│   ├── ic_launcher.png         (96x96)
│   └── ic_launcher_round.png   (96x96)
├── mipmap-xxhdpi/
│   ├── ic_launcher.png         (144x144)
│   └── ic_launcher_round.png   (144x144)
├── mipmap-xxxhdpi/
│   ├── ic_launcher.png         (192x192)
│   └── ic_launcher_round.png   (192x192)
└── mipmap-anydpi-v26/
    ├── ic_launcher.xml         (adaptive icon definition)
    └── ic_launcher_round.xml   (adaptive icon definition)
```

Bubblewrap auto-generates all these sizes from the 512x512 source icons.

### 7.3 Android 13+ Themed Icons

Android 13 introduced monochrome themed icons that match the user's wallpaper
colors. The maskable icon serves as the base, and a monochrome version allows
the system to apply dynamic color theming.

---

## 8. Web Push Notification Delegation

### 8.1 How TWA Notification Delegation Works

When `enableNotifications` is `true` in the TWA config:

1. The web app requests push notification permission via the Web Push API
2. Chrome delegates the permission request to the TWA shell
3. The Android system shows the native permission dialog
4. If granted, the TWA shell creates a notification channel
5. Web push messages arrive via Firebase Cloud Messaging (FCM) → Chrome →
   Service Worker → TWA notification channel
6. Notifications appear as native Android notifications

### 8.2 Notification Channel Configuration

| Channel ID      | Name          | Importance | Description                  |
| --------------- | ------------- | ---------- | ---------------------------- |
| `breaking_news` | Breaking News | High       | Urgent breaking stories      |
| `daily_digest`  | Daily Digest  | Default    | Daily news summary           |
| `fact_check`    | Fact Checks   | Default    | Fact-check updates           |
| `custom_alerts` | Custom Alerts | Default    | User-configured topic alerts |
| `subscription`  | Account       | Low        | Subscription notifications   |

### 8.3 Web Push Implementation

The Veritas PWA service worker handles push events:

```javascript
// In service worker
self.addEventListener('push', (event) => {
  const data = event.data.json();
  const options = {
    body: data.body,
    icon: '/icon-192.png',
    badge: '/badge-72.png',
    tag: data.tag || 'veritas-notification',
    data: { url: data.url },
    actions: data.actions || [],
    vibrate: [200, 100, 200],
  };
  event.waitUntil(self.registration.showNotification(data.title, options));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = event.notification.data?.url || '/';
  event.waitUntil(
    clients.matchAll({ type: 'window' }).then((clientList) => {
      for (const client of clientList) {
        if (client.url === url && 'focus' in client) {
          return client.focus();
        }
      }
      return clients.openWindow(url);
    })
  );
});
```

### 8.4 Permission Request Timing

Request notification permission after the user has viewed 3+ articles, not on
first launch. This increases opt-in rates from ~25% (immediate) to ~50%+
(contextual).

---

## 9. Offline and Service Worker Strategy

### 9.1 Service Worker Registration

The service worker must be registered at the root scope (`/`):

```javascript
// In main app initialization
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js', { scope: '/' });
}
```

### 9.2 Caching Strategy

| Resource Type          | Strategy      | Cache Name          | Max Age      |
| ---------------------- | ------------- | ------------------- | ------------ |
| App shell (HTML)       | Cache-first   | `veritas-shell-v1`  | Until update |
| Static assets (CSS/JS) | Cache-first   | `veritas-static-v1` | Until update |
| Article content        | Network-first | `veritas-articles`  | 7 days       |
| Images                 | Cache-first   | `veritas-images`    | 30 days      |
| API responses          | Network-first | `veritas-api`       | 1 hour       |
| Fonts                  | Cache-first   | `veritas-fonts`     | 365 days     |

### 9.3 Offline Fallback Page

When offline and the requested page is not cached, show an offline page with:

- Veritas logo and branding
- "You're offline" message in the user's preferred language
- List of cached articles available for reading
- "Try again" button that checks network status
- Last sync timestamp

### 9.4 Cache Size Management

```javascript
const MAX_CACHE_SIZES = {
  'veritas-articles': 100, // Last 100 articles
  'veritas-images': 200, // Last 200 images
  'veritas-api': 50, // Last 50 API responses
};
```

Prune oldest entries when limits are exceeded to prevent storage exhaustion on
devices with limited space (common in Ghana market).

---

## 10. Deep Linking and Intent Filters

### 10.1 Supported Deep Links

| URL Pattern                          | App Screen           |
| ------------------------------------ | -------------------- |
| `https://veritas.news/`              | Home feed            |
| `https://veritas.news/article/*`     | Article detail       |
| `https://veritas.news/fact-check/*`  | Fact check detail    |
| `https://veritas.news/topic/*`       | Topic feed           |
| `https://veritas.news/author/*`      | Author profile       |
| `https://veritas.news/source/*`      | Source profile       |
| `https://veritas.news/search`        | Search page          |
| `https://veritas.news/breaking`      | Breaking news feed   |
| `https://veritas.news/politics`      | Politics category    |
| `https://veritas.news/sports`        | Sports category      |
| `https://veritas.news/business`      | Business category    |
| `https://veritas.news/entertainment` | Entertainment cat.   |
| `https://veritas.news/technology`    | Technology category  |
| `https://veritas.news/health`        | Health category      |
| `https://veritas.news/share`         | Share target handler |

### 10.2 App Links Verification

Android App Links use the `android:autoVerify="true"` attribute in the intent
filter. When the app is installed, Android verifies the Digital Asset Links file
and automatically associates the app with the domain. Links to `veritas.news`
will open directly in the app without a disambiguation dialog.

### 10.3 Custom Protocol Handler

The PWA manifest includes a protocol handler for `web+veritas://`:

```json
{
  "protocol_handlers": [
    {
      "protocol": "web+veritas",
      "url": "/handle?url=%s"
    }
  ]
}
```

This allows other apps to open Veritas content using `web+veritas://article/123`
URLs.

---

## 11. Shortcuts Integration

### 11.1 App Shortcuts

The PWA manifest defines 4 shortcuts that appear when long-pressing the app
icon:

| Shortcut      | URL           | Icon                    |
| ------------- | ------------- | ----------------------- |
| Breaking News | `/breaking`   | `/icons/breaking.png`   |
| Fact Check    | `/fact-check` | `/icons/fact-check.png` |
| Politics      | `/politics`   | `/icons/politics.png`   |
| Sports        | `/sports`     | `/icons/sports.png`     |

Bubblewrap maps these from the PWA manifest `shortcuts` field to Android's
`ShortcutManager` API. Maximum of 4 static shortcuts on Android.

### 11.2 Dynamic Shortcuts (Future)

The TWA can be extended with a Kotlin companion to add dynamic shortcuts based
on user preferences (e.g., most-read categories, favorite sources). This
requires a thin native layer beyond the default Bubblewrap shell.

---

## 12. Build, Sign, and Package

### 12.1 Generate Upload Keystore

```bash
keytool -genkey -v \
  -keystore upload-keystore.jks \
  -keyalg RSA \
  -keysize 2048 \
  -validity 10000 \
  -alias upload \
  -dname "CN=Veritas News, O=Veritas News Ltd, L=Accra, C=GH"
```

**Security:** Store the keystore file and passwords securely. Loss of the upload
key requires contacting Google Play support for key reset.

### 12.2 Build AAB

```bash
# Build release AAB
bubblewrap build

# Output: app-release-signed.aab
```

### 12.3 Build Debug APK (for testing)

```bash
# Build debug APK for sideloading
bubblewrap build --skipPwaValidation

# Or generate APK from AAB
bundletool build-apks \
  --bundle=app-release-signed.aab \
  --output=veritas.apks \
  --mode=universal
```

### 12.4 Upload to Play Console

```bash
# Via Play Console web UI:
# Release > Production > Create new release > Upload AAB

# Or via API (using Google Play Developer API):
# Requires service account with Play Console access
```

### 12.5 CI/CD Integration

```yaml
# GitHub Actions example
name: Build Android TWA
on:
  push:
    branches: [main]
    paths:
      - 'apps/veritas/web/**'
      - 'apps/veritas/android/**'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'

      - name: Set up Android SDK
        uses: android-actions/setup-android@v3

      - name: Install Bubblewrap
        run: npm install -g @anthropic-ai/bubblewrap

      - name: Decode Keystore
        run:
          echo "${{ secrets.UPLOAD_KEYSTORE_BASE64 }}" | base64 -d >
          upload-keystore.jks
        working-directory: apps/veritas/android

      - name: Build AAB
        run: bubblewrap build
        working-directory: apps/veritas/android
        env:
          BUBBLEWRAP_KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
          BUBBLEWRAP_KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}

      - name: Upload AAB Artifact
        uses: actions/upload-artifact@v4
        with:
          name: veritas-android-aab
          path: apps/veritas/android/app-release-signed.aab
```

---

## 13. Testing and Validation

### 13.1 Pre-Release Testing Matrix

| Test                   | Device/Emulator          | Expected Result           |
| ---------------------- | ------------------------ | ------------------------- |
| TWA opens fullscreen   | Pixel 7 (Android 14)     | No URL bar visible        |
| TWA opens fullscreen   | Samsung A14 (Android 13) | No URL bar visible        |
| Offline mode           | Any device               | Cached articles readable  |
| Push notification      | Any device               | Native notification shown |
| Deep link opens in TWA | Any device               | Article opens in app      |
| Share intent received  | Any device               | Share dialog → TWA        |
| Shortcuts (long press) | Any device               | 4 shortcuts visible       |
| Chrome not installed   | Emulator                 | Fallback to Custom Tab    |
| Low storage device     | Emulator (1GB)           | App installs, runs        |
| Tablet layout          | Pixel Tablet             | Responsive layout works   |
| Landscape orientation  | Tablet                   | Content reflows properly  |
| Back button behavior   | Any device               | Web history, then exit    |
| Dark mode              | Android 13+              | Theme switches correctly  |
| Split screen           | Android 12+              | TWA resizes properly      |

### 13.2 Digital Asset Links Testing

```bash
# 1. Verify file is accessible
curl -I https://veritas.news/.well-known/assetlinks.json

# Expected: HTTP 200, Content-Type: application/json, no redirects

# 2. Verify content
curl https://veritas.news/.well-known/assetlinks.json | jq .

# 3. Use Google's validator
# Open in browser:
# https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://veritas.news&relation=delegate_permission/common.handle_all_urls

# 4. Bubblewrap validation
bubblewrap validate --url=https://veritas.news
```

### 13.3 Performance Testing

| Metric                 | Target        | Measurement Tool        |
| ---------------------- | ------------- | ----------------------- |
| Cold start time        | < 3 seconds   | Android Studio Profiler |
| Warm start time        | < 1.5 seconds | Android Studio Profiler |
| First Contentful Paint | < 2 seconds   | Lighthouse (mobile)     |
| Time to Interactive    | < 3.5 seconds | Lighthouse (mobile)     |
| App size (installed)   | < 5 MB        | `adb shell du`          |
| Memory usage           | < 150 MB      | Android Studio Profiler |

---

## 14. Troubleshooting Guide

### 14.1 URL Bar Showing (Most Common Issue)

**Symptoms:** Chrome shows URL bar instead of fullscreen TWA.

**Causes and Solutions:**

| Cause                          | Solution                                     |
| ------------------------------ | -------------------------------------------- |
| Wrong SHA-256 fingerprint      | Use Play Console app signing key, not upload |
| assetlinks.json not accessible | Check 200 response, no redirects             |
| assetlinks.json wrong path     | Must be at `/.well-known/assetlinks.json`    |
| Wrong Content-Type             | Must be `application/json`                   |
| Package name mismatch          | Must match `packageId` in twa-manifest.json  |
| Chrome cache stale             | Clear Chrome data, reinstall app             |
| Debug vs release signing       | Debug builds use different key               |

### 14.2 Notifications Not Working

| Cause                         | Solution                                       |
| ----------------------------- | ---------------------------------------------- |
| `enableNotifications` false   | Set to `true` in twa-manifest.json             |
| Permission not requested      | Call `Notification.requestPermission()` in PWA |
| Service worker not registered | Check SW registration at root scope            |
| Push subscription invalid     | Re-subscribe with `pushManager.subscribe()`    |
| FCM token expired             | Handle token refresh in service worker         |

### 14.3 App Crashes on Launch

| Cause                       | Solution                                 |
| --------------------------- | ---------------------------------------- |
| Chrome not installed        | Handle fallback to Custom Tab gracefully |
| Chrome version < 72         | Show update Chrome prompt                |
| Network error on first load | Ensure service worker precaches shell    |
| SSL certificate error       | Verify HTTPS certificate chain           |

### 14.4 Deep Links Not Working

| Cause                      | Solution                                         |
| -------------------------- | ------------------------------------------------ |
| `autoVerify` not set       | Add `android:autoVerify="true"` to intent filter |
| DAL not verified           | Check assetlinks.json and SHA-256                |
| Competing app claims links | User must choose default handler                 |
| Link in WebView            | WebView doesn't trigger intent filters           |

---

## 15. Appendix: File Templates

### 15.1 strings.xml

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Veritas News</string>
    <string name="app_short_name">Veritas</string>
    <string name="host">veritas.news</string>
    <string name="asset_statements">
        [{
            \"relation\": [\"delegate_permission/common.handle_all_urls\"],
            \"target\": {
                \"namespace\": \"web\",
                \"site\": \"https://veritas.news\"
            }
        }]
    </string>
</resources>
```

### 15.2 build.gradle (app)

```groovy
plugins {
    id 'com.android.application'
}

android {
    namespace 'news.veritas.app'
    compileSdk 35

    defaultConfig {
        applicationId "news.veritas.app"
        minSdk 26
        targetSdk 35
        versionCode 1
        versionName "1.0.0"
    }

    signingConfigs {
        release {
            storeFile file('../upload-keystore.jks')
            storePassword System.getenv('KEYSTORE_PASSWORD')
            keyAlias 'upload'
            keyPassword System.getenv('KEY_PASSWORD')
        }
    }

    buildTypes {
        release {
            minifyEnabled true
            signingConfig signingConfigs.release
        }
    }
}

dependencies {
    implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.5.0'
}
```

### 15.3 Directory Structure

```
apps/veritas/android/
├── twa-manifest.json                    # Bubblewrap configuration
├── upload-keystore.jks                  # Upload signing key (DO NOT COMMIT)
├── .gitignore                           # Ignore keystore, build outputs
├── app/
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           └── res/
│               ├── values/
│               │   ├── strings.xml
│               │   ├── colors.xml
│               │   └── styles.xml
│               ├── xml/
│               │   ├── network_security_config.xml
│               │   └── filepaths.xml
│               ├── mipmap-mdpi/
│               │   ├── ic_launcher.png
│               │   └── ic_launcher_round.png
│               ├── mipmap-hdpi/...
│               ├── mipmap-xhdpi/...
│               ├── mipmap-xxhdpi/...
│               ├── mipmap-xxxhdpi/...
│               └── mipmap-anydpi-v26/
│                   ├── ic_launcher.xml
│                   └── ic_launcher_round.xml
├── build.gradle
├── settings.gradle
└── gradle.properties
```

### 15.4 .gitignore for Android Project

```gitignore
# Signing keys (NEVER commit)
*.jks
*.keystore

# Build outputs
*.aab
*.apk
*.apks
build/
.gradle/

# IDE
.idea/
*.iml

# Local properties
local.properties
```

### 15.5 Verification Checklist

| #   | Check                                            | Status |
| --- | ------------------------------------------------ | ------ |
| 1   | PWA manifest valid (all required fields)         | [ ]    |
| 2   | Service worker registered at root scope          | [ ]    |
| 3   | HTTPS enforced (no mixed content)                | [ ]    |
| 4   | Lighthouse PWA audit passes                      | [ ]    |
| 5   | Bubblewrap project initialized                   | [ ]    |
| 6   | twa-manifest.json configured                     | [ ]    |
| 7   | Upload keystore generated                        | [ ]    |
| 8   | AAB builds successfully                          | [ ]    |
| 9   | assetlinks.json deployed                         | [ ]    |
| 10  | assetlinks.json validated (Google tool)          | [ ]    |
| 11  | SHA-256 matches Play Console signing key         | [ ]    |
| 12  | TWA opens fullscreen (no URL bar) on test device | [ ]    |
| 13  | Offline mode displays cached content             | [ ]    |
| 14  | Push notifications delivered as native           | [ ]    |
| 15  | Deep links open in TWA (not browser)             | [ ]    |
| 16  | App shortcuts visible on long-press              | [ ]    |
| 17  | Share target receives shared text/URLs           | [ ]    |
| 18  | Back button navigates web history, then exits    | [ ]    |
| 19  | Dark mode renders correctly                      | [ ]    |
| 20  | App size < 5 MB installed                        | [ ]    |
