@marinoscar/platform-infra 0.1.0-next.3 → 0.1.0-next.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +172 -19
  3. package/android/platform-core/README.md +149 -0
  4. package/android/platform-core/build.gradle.kts +86 -0
  5. package/android/platform-core/consumer-rules.pro +27 -0
  6. package/android/platform-core/identity.gradle.kts +132 -0
  7. package/android/platform-core/src/main/AndroidManifest.xml +17 -0
  8. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/PlatformIdentity.kt +39 -0
  9. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/auth/AuthFailures.kt +27 -0
  10. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/auth/TokenStore.kt +118 -0
  11. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/config/ServerConfig.kt +55 -0
  12. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/config/ServerUrls.kt +86 -0
  13. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/net/ApiClient.kt +248 -0
  14. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/net/ApiResult.kt +55 -0
  15. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/notifications/NotificationPermission.kt +159 -0
  16. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/pairing/DeviceFlow.kt +184 -0
  17. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/pairing/DeviceInfo.kt +38 -0
  18. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/pairing/PairingManager.kt +174 -0
  19. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/twa/TwaLauncher.kt +69 -0
  20. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/update/AppUpdate.kt +401 -0
  21. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/update/AppUpdates.kt +50 -0
  22. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/util/AppInfo.kt +63 -0
  23. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/util/Fingerprints.kt +36 -0
  24. package/android/platform-core/src/main/kotlin/io/github/marinoscar/platform/android/core/util/PlatformLog.kt +26 -0
  25. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/auth/AuthFailuresTest.kt +23 -0
  26. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/auth/SharedPrefsTokenStoreTest.kt +36 -0
  27. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/config/ServerUrlsTest.kt +154 -0
  28. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/net/ApiClientTest.kt +190 -0
  29. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/notifications/NotificationPermissionTest.kt +121 -0
  30. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/pairing/DeviceFlowPollerTest.kt +165 -0
  31. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/pairing/PairingManagerTest.kt +142 -0
  32. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/testing/FakeSharedPreferences.kt +51 -0
  33. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/update/UpdateTest.kt +237 -0
  34. package/android/platform-core/src/test/kotlin/io/github/marinoscar/platform/android/core/util/FingerprintsTest.kt +38 -0
  35. package/compose/app.example.compose.yml +36 -0
  36. package/compose/base.compose.yml +145 -0
  37. package/compose/dev.compose.yml +46 -0
  38. package/compose/devdb.compose.yml +91 -0
  39. package/compose/postgres-init/10-application-role.sh +43 -0
  40. package/compose/prod.compose.yml +48 -0
  41. package/compose/test.compose.yml +53 -0
  42. package/compose/vps.compose.yml +178 -0
  43. package/compose/worker.build.compose.yml +21 -0
  44. package/compose/worker.compose.yml +92 -0
  45. package/dist/app-identity.d.ts +27 -0
  46. package/dist/app-identity.d.ts.map +1 -0
  47. package/dist/app-identity.js +73 -0
  48. package/dist/app-identity.js.map +1 -0
  49. package/dist/cli.d.ts.map +1 -1
  50. package/dist/cli.js +27 -11
  51. package/dist/cli.js.map +1 -1
  52. package/dist/compose-order.d.ts +111 -0
  53. package/dist/compose-order.d.ts.map +1 -0
  54. package/dist/compose-order.js +197 -0
  55. package/dist/compose-order.js.map +1 -0
  56. package/dist/fragment.d.ts +27 -0
  57. package/dist/fragment.d.ts.map +1 -0
  58. package/dist/fragment.js +15 -0
  59. package/dist/fragment.js.map +1 -0
  60. package/dist/fragments.d.ts +65 -0
  61. package/dist/fragments.d.ts.map +1 -0
  62. package/dist/fragments.js +117 -0
  63. package/dist/fragments.js.map +1 -0
  64. package/dist/identity.d.ts +93 -0
  65. package/dist/identity.d.ts.map +1 -0
  66. package/dist/identity.js +131 -0
  67. package/dist/identity.js.map +1 -0
  68. package/dist/index.d.ts +8 -10
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +11 -9
  71. package/dist/index.js.map +1 -1
  72. package/dist/infra-conformance.d.ts +101 -0
  73. package/dist/infra-conformance.d.ts.map +1 -0
  74. package/dist/infra-conformance.js +238 -0
  75. package/dist/infra-conformance.js.map +1 -0
  76. package/dist/package-name.d.ts +7 -0
  77. package/dist/package-name.d.ts.map +1 -0
  78. package/dist/package-name.js +7 -0
  79. package/dist/package-name.js.map +1 -0
  80. package/dist/sync.d.ts +36 -8
  81. package/dist/sync.d.ts.map +1 -1
  82. package/dist/sync.js +218 -45
  83. package/dist/sync.js.map +1 -1
  84. package/dist/telemetry/manifest.d.ts +27 -2
  85. package/dist/telemetry/manifest.d.ts.map +1 -1
  86. package/dist/telemetry/manifest.js +1 -0
  87. package/dist/telemetry/manifest.js.map +1 -1
  88. package/env/app.env.example +9 -0
  89. package/env/base.env.example +539 -0
  90. package/env/worker.env.example +80 -0
  91. package/nginx/app.d/csp/connect-src.conf.example +20 -0
  92. package/nginx/app.d/locations/.gitkeep +0 -0
  93. package/nginx/app.d/locations/stream-route.conf.example +17 -0
  94. package/nginx/app.d/permissions-policy.conf +18 -0
  95. package/nginx/app.d/server/.gitkeep +0 -0
  96. package/nginx/csp.conf +120 -0
  97. package/nginx/csp.dev.conf +93 -0
  98. package/nginx/nginx.conf +416 -0
  99. package/nginx/platform/android-app.conf +89 -0
  100. package/nginx/platform/security-headers.conf +34 -0
  101. package/nginx/platform/sse-proxy.conf +56 -0
  102. package/package.json +10 -1
  103. package/telemetry/compose/vps.telemetry.compose.yml +1 -1
  104. /package/{compose → nginx/app.d/csp}/.gitkeep +0 -0
  105. /package/nginx/{.gitkeep → app.d/http/.gitkeep} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # @marinoscar/platform-infra
2
2
 
3
+ ## 0.1.0-next.31
4
+
5
+ ## 0.1.0-next.30
6
+
7
+ ## 0.1.0-next.29
8
+
9
+ ## 0.1.0-next.28
10
+
11
+ ## 0.1.0-next.27
12
+
13
+ ## 0.1.0-next.26
14
+
15
+ ## 0.1.0-next.25
16
+
17
+ ## 0.1.0-next.24
18
+
19
+ ## 0.1.0-next.23
20
+
21
+ ## 0.1.0-next.22
22
+
23
+ ## 0.1.0-next.21
24
+
25
+ ## 0.1.0-next.20
26
+
27
+ ## 0.1.0-next.19
28
+
29
+ ## 0.1.0-next.18
30
+
31
+ ### Patch Changes
32
+
33
+ - bca937b: Example names in doc comments, README examples and schema examples are replaced with invented placeholders (Org Kappa, Org Sigma, Org Theta and similar) instead of well-known fictional brands. No behaviour change.
34
+
35
+ ## 0.1.0-next.17
36
+
37
+ ## 0.1.0-next.16
38
+
39
+ ## 0.1.0-next.15
40
+
41
+ ## 0.1.0-next.14
42
+
43
+ ## 0.1.0-next.13
44
+
45
+ ## 0.1.0-next.12
46
+
47
+ ## 0.1.0-next.11
48
+
49
+ ## 0.1.0-next.10
50
+
51
+ ## 0.1.0-next.9
52
+
53
+ ## 0.1.0-next.8
54
+
55
+ ## 0.1.0-next.7
56
+
57
+ ## 0.1.0-next.6
58
+
59
+ ## 0.1.0-next.5
60
+
61
+ ## 0.1.0-next.4
62
+
63
+ ### Minor Changes
64
+
65
+ - fa3f5b9: Open the CLI and infra seams an app needs without editing a package (PP-14.22, #940).
66
+
67
+ Proxy (a production bug): an app SSE route worked through the app's own nginx but was buffered and cut at 60 s by the shared VPS host proxy, which knew only the platform's three streaming paths. `createCli({ proxy: { streamPaths } })` and `registerProxyStreamPath(path | { path, timeoutSeconds })` make `renderVhost` add one unbuffered, long-lived location per path with the directives of the platform's SSE locations (`ProxyTarget` gains `streamPaths` and `extraLocations`). Paths are validated before they reach the shared nginx config (a leading `/`, letters, digits and `. _ ~ / : @ + , = -`; a newline, `;`, quote, brace, `$`, `#` or space throws). A vhost for an app that declares none is byte-identical.
68
+
69
+ CLI: `registerEnvGroup` (the three platform groups register through it; `ENV_GROUPS` stays as the built-in list and `EnvGroup` widens to `string`), `registerEnvGenerator` (`GenerateKind` widens to `string`; a generator is a function whose value is checked against a safe character set, never a command) and `annotateEnvKey` (the app wins for `fixed` and `help` on a platform key; a secret cannot be fixed); `registerDeployCheck` (`allChecks()` is the built-ins plus the app's; `ALL_CHECKS` is unchanged); `registerDeployStep` takes exactly one of `after`, `before` and `replaces` plus `skipWhen`, and `DeployStepContext` gains read-only `env` and `answers` that withhold secret keys; `registerEdgeConfigFile`; `registerTuiScreenSection` for the node and deploy screens; `registerCliConformanceSuite` and a `deployRegistrations` suite. `createCli` gains `envGroups`, `envGenerators`, `envAnnotations`, `deployChecks`, `edgeConfigFiles`, `tuiSections` and `proxy`.
70
+
71
+ Migration notes for `@marinoscar/platform-cli`: in `runPlatformConformance`, `cli: false` now throws; pass `cli: { skip: 'reason' }` (an empty reason also throws). `DeployStepRegistration.step` and `.after` are optional (a registration reading `.step` needs a check; the registrations the package builds keep `step` defined). A hand-built `DeployStepContext` in a test needs `env` and `answers`: use `testDeployStepContext` from `/testing`.
72
+
73
+ Infra: the default CSP is composed from `$csp_*_extra` maps that include `app.d/csp/*.conf` (sources for `connect-src`, `img-src`, `media-src`, `font-src`, `style-src`, and whole extra directives); with no file the header is byte-identical, there is no `script-src` hook, and the `/api/docs` policy is not extended. `sync` creates `app.d/csp/` and two inert example files. `composeFilesForMode('test')` and `app.test.*` overlays, `registerComposeMode`, and `runInfraConformance({ appRoot })` at `@marinoscar/platform-infra/testing` (sync check, `docker compose config` per mode with the app's overlays, `nginx -t` over `app.d`; a missing tool is a passing case named with the reason). Run `npm run platform:infra:sync` to refresh `csp.conf` and `csp.dev.conf`.
74
+
75
+ - a1f5999: Ship the Android companion's infra: the `platform/android-app.conf` nginx snippet (`/.well-known/assetlinks.json`, the unbuffered APK upload and download routes), and `android/platform-core`, a Kotlin Android library module distributed as files (TWA launcher, server configuration, device-flow pairing, encrypted token store, API client, app updates, notification-permission rules, and `identity.gradle.kts` deriving the Android identity from `identity.json`). An app includes it from `settings.gradle.kts` with `include(":platform-core")`.
76
+ - e4ad7d5: `platform-infra sync` ships executable scripts: a generated file marked `executable` keeps its `#!` shebang on line 1 (the header goes after it), is written with mode 0755 and listed under its fragment's `executable` key in `infra/platform-infra.lock.json`, and `sync --check` fails when it loses its executable bit. The compose fragment now ships `postgres-init/10-application-role.sh`, the init script `devdb.compose.yml` and `test.compose.yml` mount to create the ordinary (NOSUPERUSER NOBYPASSRLS) role the API runs as.
77
+ - 94a63a2: Ship the base, dev, devdb, prod, vps, worker, worker.build and test compose fragments, nginx.conf with its app include points and the security-headers and SSE snippets, and the env templates; render the app identity into them on `platform-infra sync` (`--identity`), and order each mode's compose files with the app's `app.*.compose.yml` overlays last (`composeFilesForMode`, `appComposeOverlays`).
78
+ - 1171b1c: Complete the telemetry slice in all five packages. `@marinoscar/platform-api/telemetry/testing` gains the telemetry conformance suite (registered with `runPlatformConformance()` as `suites.telemetry`: metric groups, route permissions, read-only Doctor checks, no secrets in responses, the cron coverage and the boot without a store), the stub host ports, and the five activity and six coach fixture tables; `ConformanceCase.run` may be async and a slice may add a suite key by augmenting `PlatformConformanceSuiteOptions`. Every telemetry slice README now follows the Package documentation standard with a catalog that links a working example in the reference app.
79
+
80
+ ### Patch Changes
81
+
82
+ - 8bf9606: Move the CLI into `@marinoscar/platform-cli`: `createCli({ identity, version, extraCommands, tuiScreens, deploySteps, nodeExecutors, envSpecFragments })` builds an app's CLI (the `init`, `login`, `api`, `config`, `node` and `deploy` commands, the TUI, the deploy pipeline and the worker engine) with the identity as configuration; add the `/commands`, `/tui`, `/deploy`, `/node`, `/api-client` and `/testing` entry points, the `registerTuiScreen`, `registerDeployStep` and `registerNodeExecutor` registries, the credential-hygiene check and the `cli` conformance suite. platform-infra: point its README examples at the reference app now that the CLI lives in a package.
83
+ - f6e319b: Documentation only: every slice README's Extension-point catalog links the new extension author guide (`docs/EXTENDING.md`); the email README no longer promises that a provider of `SmtpEmailProvider` in the app module replaces the transport (it does not reach the package's consumers; a transport registry is not supported yet); the AI READMEs say that a provider cannot be enabled from an app yet; the platform-db README documents `rlsPolicies` in `platform.lock` with the migration SQL for an app table protected by row-level security.
84
+ - b46d405: Name the disposable GreptimeDB test container after the app (`greptime-@@PLATFORM_TEST_CONTAINER@@`) instead of a fixed `my-app-greptime-test`, so an app renders no other app's identity, and point the fragments' comments at the CLI's packaged sources (`packages/platform-cli/src/engine/...`).
85
+
3
86
  ## 0.1.0-next.3
4
87
 
5
88
  ## 0.1.0-next.2
package/README.md CHANGED
@@ -1,16 +1,26 @@
1
1
  # @marinoscar/platform-infra
2
2
 
3
- Deployment configuration shipped as files: Compose fragments (`compose/`), nginx configuration (`nginx/`) and OpenTelemetry collector configuration (`otel/`), layered by an app with its own overlays. `infraFile('compose/<file>')` returns the absolute path of a shipped file, for `docker compose -f`.
3
+ Deployment configuration shipped as files, plus the small ESM API that orders and renders them: the platform's Compose fragments (`compose/`), its nginx configuration (`nginx/`), its env templates (`env/`) and the telemetry slice's collector and GreptimeDB files (`telemetry/`). An app never references them from `node_modules`: `platform-infra sync` materialises them into the app's `infra/`, rendered with the app's identity, and the app changes the platform through overlay files, never by editing a generated one. The reference app (`apps/`, `infra/` in this repository) and the CLI's deploy (`apps/cli`) consume it.
4
4
 
5
5
  ## Purpose and scope
6
6
 
7
- Compose fragments, nginx and collector configuration of the platform, plus `infraFile()` to locate them. It does not own the app's own overlays, `.env` or images.
7
+ What the package owns:
8
+
9
+ - the Compose files `base`, `dev`, `devdb`, `prod`, `vps` (with the stack agent), `worker`, `worker.build` and `test`, and the order Compose applies them in per mode (`composeFilesForMode()`, `dev`, `devdb`, `prod`, `vps`, `worker` and `test`, plus the modes an app adds with `registerComposeMode`), with the app's overlays last;
10
+ - `postgres-init/10-application-role.sh`, the executable init script `devdb` and `test` mount at `/docker-entrypoint-initdb.d`: it creates the ordinary (`NOSUPERUSER NOBYPASSRLS`) role the API runs as, so row-level security applies to it;
11
+ - `nginx.conf` with its include points (`app.d/http`, `server`, `locations`, `csp` and the Permissions-Policy file), the two CSP maps and the `platform/` snippets (`security-headers.conf`, `sse-proxy.conf`);
12
+ - the platform's environment variables (`env/base.env.example`) and the worker's (`env/worker.env.example`);
13
+ - identity rendering: the app's CLI name, env prefix, service name, worker image and test database names written into those files (`deriveInfraIdentity()`, `renderInfraText()`);
14
+ - the `platform-infra sync` command and its lock;
15
+ - `runInfraConformance` (`@marinoscar/platform-infra/testing`): the app's own test that its overlays merge and its `app.d/` is valid nginx.
16
+
17
+ What it does not own: the app's overlays (`infra/compose/app.*.compose.yml`, `infra/nginx/app.d/`, `infra/compose/app.env.example`, `infra/otel/app-collector.yaml`), its `.env`, its Dockerfiles and images, and `apps/stack-agent` (still an app workspace; the `vps` fragment builds it from `apps/stack-agent/Dockerfile`). A Helm chart is deferred.
8
18
 
9
19
  Slices, each a subpath export with its own README:
10
20
 
11
21
  - [`@marinoscar/platform-infra/telemetry`](src/telemetry/README.md): the collector and GreptimeDB compose fragments, the platform collector config, the app-owned collector overlay and their typed manifest.
12
22
 
13
- The package also ships the `platform-infra` command (`bin/platform-infra.mjs`), which materialises the fragments into the app. Version `0.0.0`, unpublished; the base, prod, vps and worker fragments and nginx follow (#714).
23
+ The `@marinoscar/platform-infra/testing` subpath exports `runInfraConformance`. It is a module of the package root, not a slice, because it wraps the compose order and the sync check; see Conformance suite below.
14
24
 
15
25
  ## Install and peer dependencies
16
26
 
@@ -22,28 +32,108 @@ No peer dependencies: the package needs nothing installed beside it.
22
32
 
23
33
  ## Quick start
24
34
 
25
- ```ts
26
- import { infraFile } from '@marinoscar/platform-infra';
27
-
28
- const base = infraFile('compose/base.compose.yml'); // absolute path for docker compose -f
35
+ ```bash
36
+ npx platform-infra sync # render every fragment into infra/, write infra/platform-infra.lock.json
37
+ npx platform-infra sync --check # CI: fail when a generated file differs from the package or the lock
29
38
  ```
30
39
 
31
- Fragments are copied into the app and committed, never resolved from `node_modules` at deploy time (an app's VPS deploy runs `docker compose` from its cloned repository, where there is no `node_modules`):
40
+ In this repository the root script is `npm run platform:infra:sync` (it runs the built `dist/`, so `npm run build:packages` comes first). Then start the stack exactly as before, from `infra/compose`:
32
41
 
33
42
  ```bash
34
- npx platform-infra sync # materialise every fragment into infra/, write infra/platform-infra.lock.json
35
- npx platform-infra sync --check # CI: fail when a generated file differs from the package or the lock
43
+ docker compose -f base.compose.yml -f dev.compose.yml -f devdb.compose.yml up
36
44
  ```
37
45
 
38
- In this repository the root script is `npm run platform:infra:sync`.
46
+ The order of the `-f` files, with the app's overlays last, comes from the package:
47
+
48
+ ```ts
49
+ import { readdirSync } from 'node:fs';
50
+ import { composeFilesForMode } from '@marinoscar/platform-infra';
51
+
52
+ const files = composeFilesForMode('vps', { telemetry: true, overlays: readdirSync('infra/compose') });
53
+ ```
39
54
 
40
55
  ## Configuration
41
56
 
42
- No `forRoot()`. The `platform-infra sync` command takes `--check` (write nothing; exit 1 on drift) and `--root <dir>` (the app's repository root, default the current directory); see the [telemetry slice README](src/telemetry/README.md#configuration).
57
+ No `forRoot()`. `platform-infra sync` takes:
58
+
59
+ | Option | Meaning |
60
+ |---|---|
61
+ | `--check` | Write nothing; exit 1 when a generated file differs from the package (rendered) or from the lock. |
62
+ | `--root <dir>` | The app's repository root (default: the current directory). |
63
+ | `--identity <file>` | The app identity, relative to the root. Default `packages/shared/identity.json`; when it has no `cliName`, the single `bin` key of `apps/cli/package.json` is the CLI name. |
64
+
65
+ The identity file may carry any `InfraIdentityInput` field: `cliName` (required unless the `bin` fallback applies), `productName` (slugified for the defaults below), and explicit `envPrefix`, `serviceName`, `workerImage`, `testDatabase`, `testContainer`. No environment variable is read.
43
66
 
44
67
  ## Extension-point catalog
45
68
 
46
- None. The root entry point exports no extension point; each slice lists its own (`telemetryInfraFragment` and the collector overlay: [telemetry slice README](src/telemetry/README.md#extension-point-catalog)).
69
+ The extension ladder and a recipe per extension: [docs/EXTENDING.md](../../docs/EXTENDING.md).
70
+
71
+ The exported seams, then the seams that are files and a command (below). Every row links a working use in the reference app.
72
+
73
+ | Name | Kind | Signature | When to use | Stability | Example |
74
+ |---|---|---|---|---|---|
75
+ | `composeFilesForMode` | overlay | `(mode: ComposeMode, options?: ComposeFilesOptions) => string[]` | Build the `-f` list of a mode (dev, devdb, prod, vps, worker, test, or one registered) with the app's overlays last, instead of hard-coding it | experimental | [an app overlay it appends](../../infra/compose/app.example.compose.yml) (called by `@marinoscar/platform-cli`'s `deploy` and `init`) |
76
+ | `appComposeOverlays` | overlay | `(names: readonly string[], mode: ComposeMode) => string[]` | Find which `app.*.compose.yml` files of a directory apply to a mode, sorted | experimental | [example overlay](../../infra/compose/app.example.compose.yml) |
77
+ | `runInfraConformance` | option | `(options: InfraConformanceOptions) => void` (`@marinoscar/platform-infra/testing`) | Prove in the app's own tests that `sync --check` is clean, every mode's `docker compose config` renders with the app's overlays and `nginx -t` accepts `app.d/` with both CSP files | experimental | [example](../../apps/cli/src/infra-conformance.test.ts) |
78
+ | `registerComposeMode` | registry | `(mode: ComposeModeRegistration) => void` | Add a stack of the app's own (a staging server built from the production files); its id is the overlay scope of `app.<id>.*.compose.yml` | experimental | [example](../../apps/cli/src/examples/staging.compose-mode.ts) |
79
+ | `composeInfraFragment` | overlay | `PlatformInfraFragment` | Locate the generated compose files and the app's example overlay | experimental | [example overlay](../../infra/compose/app.example.compose.yml) |
80
+ | `nginxInfraFragment` | overlay | `PlatformInfraFragment` | Locate the generated nginx files and the app-owned `app.d/` include points | experimental | [Permissions-Policy](../../infra/nginx/app.d/permissions-policy.conf) |
81
+ | `envInfraFragment` | overlay | `PlatformInfraFragment` | Locate the env templates and the app-owned `app.env.example` appended to `.env.example` | experimental | [app variables](../../infra/compose/app.env.example) |
82
+ | `deriveInfraIdentity` | option | `(input: InfraIdentityInput) => InfraIdentity` | Derive the names rendered into the files (env prefix, service name, test database) from the CLI and product names | experimental | [rendered worker file](../../infra/compose/worker.compose.yml) |
83
+
84
+ ### Compose overlays
85
+
86
+ An app changes the stack with `infra/compose/app.*.compose.yml` files, appended after every platform file and sorted by file name, so an overlay always wins. `app.<name>.compose.yml` applies to every mode built on `base.compose.yml` (dev, devdb, prod, vps); `app.<scope>.<name>.compose.yml` (scope `dev`, `devdb`, `prod`, `vps`, `worker` or `test`, or the id of a mode registered with `registerComposeMode`) only to the modes whose platform files include `<scope>.compose.yml`: `app.prod.*` to prod and vps, `app.dev.*` to dev and devdb, `app.vps.*` to vps alone, `app.test.*` to the disposable test database alone (which has no `base.compose.yml`, so a plain `app.<name>` overlay never reaches it). A name ending in `.example.compose.yml` is never applied: the reference app's [`app.example.compose.yml`](../../infra/compose/app.example.compose.yml) is the documented example, and the reference stack runs without an overlay. The deploy (`composeFilesFor()` in [`compose-files.ts`](../../packages/platform-cli/src/engine/deploy/compose-files.ts)) and `init`'s printed start command include them. The tested fixtures: kvox's memory limits ([`app.prod.memory-limits.compose.yml`](test/fixtures/overlays/kvox/compose/app.prod.memory-limits.compose.yml)) and its stack-agent opt-out with `profiles: ["disabled"]` ([`app.vps.no-stack-agent.compose.yml`](test/fixtures/overlays/kvox/compose/app.vps.no-stack-agent.compose.yml)), rendered with `docker compose config` by [`reference-compose.test.ts`](src/reference-compose.test.ts).
87
+
88
+ ### nginx include points
89
+
90
+ `nginx.conf` and `csp.conf` include five app-owned points under `/etc/nginx/app.d/` (the app's `infra/nginx/app.d/`, mounted by `base.compose.yml`), each created by the sync:
91
+
92
+ | Include point | Level | Use |
93
+ |---|---|---|
94
+ | `app.d/http/*.conf` | `http` | maps, upstreams, rate-limit zones |
95
+ | `app.d/server/*.conf` | public `server` | server-level directives |
96
+ | `app.d/locations/*.conf` | public `server`, before `location /api` | the app's locations |
97
+ | `app.d/csp/*.conf` | `http`, in `csp.conf` (a `map` body per directive) | sources appended to the default policy, below |
98
+ | `app.d/permissions-policy.conf` | in `platform/security-headers.conf` | the `Permissions-Policy` header; created from the platform default ([reference](../../infra/nginx/app.d/permissions-policy.conf)) |
99
+
100
+ An empty directory is valid. An app's SSE route is one location whose body is [`platform/sse-proxy.conf`](../../infra/nginx/platform/sse-proxy.conf) (unbuffered proxy to the API, 600 s timeouts, the security headers):
101
+
102
+ ```nginx
103
+ location /api/coach/chat/stream { include /etc/nginx/platform/sse-proxy.conf; }
104
+ ```
105
+
106
+ EvoPath's two SSE routes and its `geolocation=(self)` are the tested fixture ([`test/fixtures/overlays/evopath/nginx/app.d/`](test/fixtures/overlays/evopath/nginx/app.d/permissions-policy.conf)): `nginx -t` passes on it and every response carries the security headers ([`reference-nginx.test.ts`](src/reference-nginx.test.ts), [`nginx-app-locations.spec.ts`](../../apps/api/test/nginx-app-locations.spec.ts)).
107
+
108
+ **Extending the CSP without copying it.** The default policy of `csp.conf` and `csp.dev.conf` is composed from `$csp_*_extra` maps, each empty unless a file in `app.d/csp/` fills it. Name a file after the directive: `connect-src*.conf`, `img-src*.conf`, `media-src*.conf`, `font-src*.conf` or `style-src*.conf` append sources to that directive; `extra*.conf` appends whole directives the policy does not carry. Each file is the body of a map keyed on the request path, normally one line:
109
+
110
+ ```nginx
111
+ # infra/nginx/app.d/csp/connect-src.conf: one more WebSocket host (connect-src already allows https:)
112
+ default " wss://realtime.example.com";
113
+ ```
114
+
115
+ The value is appended as written, so it starts with a space (`extra`: `; `). With no file the header is byte-identical to the policy the platform shipped. Additions only: a CSP ignores a repeated directive after the first, so `extra` cannot widen a directive the policy has; there is deliberately **no hook for `script-src`, `default-src`, `object-src`, `base-uri`, `form-action` or `frame-ancestors`**, and the `/api/docs` policy is not extended. Widening those is an edit of the policy (the override below), not an include. The additions live in the app's repository, so review sees them. [`connect-src.conf.example`](../../infra/nginx/app.d/csp/connect-src.conf.example) is created inert by the sync. The tested fixture is [`test/fixtures/overlays/csp/`](test/fixtures/overlays/csp/nginx/app.d/csp/connect-src.conf): `nginx -t` passes on it and the served header carries both additions ([`reference-nginx.test.ts`](src/reference-nginx.test.ts)), while [`csp-include.test.ts`](src/csp-include.test.ts) pins, without nginx, that the empty policy equals the shipped string.
116
+
117
+ **The CSP override.** `csp.conf` is mounted at `/etc/nginx/csp.conf` by `base.compose.yml` and replaced by `csp.dev.conf` in `dev.compose.yml`; Compose merges `volumes` by container path, so an app replaces the policy with an overlay that mounts its own file at the same path, for example `- ../nginx/app.d/csp.conf:/etc/nginx/csp.conf:ro`. Precedence follows the file order: the app overlay comes after `dev.compose.yml`, so it wins in development too (provide a dev variant in an `app.dev.*` overlay if the app's policy is strict).
118
+
119
+ ### Identity placeholders
120
+
121
+ Package files carry `@@PLATFORM_<NAME>@@` placeholders, rendered before write (no `$`, so Compose never interpolates one; no `#`, so nginx and dotenv never read one as a comment). Rendering is pure and idempotent.
122
+
123
+ | Placeholder | Identity field | Reference value | Used in |
124
+ |---|---|---|---|
125
+ | `@@PLATFORM_CLI_NAME@@` | `cliName` | `appctl` | `vps` messages, worker comments |
126
+ | `@@PLATFORM_ENV_PREFIX@@` | `envPrefix` | `APPCTL_` | every worker variable (`worker.compose.yml`, `.env.worker.example`) |
127
+ | `@@PLATFORM_SERVICE_NAME@@` | `serviceName` | `<slug>-api` | `OTEL_SERVICE_NAME` default (`base.compose.yml`, `.env.example`) |
128
+ | `@@PLATFORM_WORKER_IMAGE@@` | `workerImage` | `ghcr.io/OWNER/REPO-worker:latest` | the worker's default image |
129
+ | `@@PLATFORM_TEST_DATABASE@@` | `testDatabase` | `<slug>_test` | `test.compose.yml` |
130
+ | `@@PLATFORM_TEST_CONTAINER@@` | `testContainer` | `<slug>-db-test` | `test.compose.yml` |
131
+
132
+ The identity the reference app was rendered with is recorded in [`infra/platform-infra.lock.json`](../../infra/platform-infra.lock.json).
133
+
134
+ ### `platform-infra sync` and the lock
135
+
136
+ Materialises the generated files, creates each app-owned file once, and writes `infra/platform-infra.lock.json` (version, identity, sha256 of each generated body, and per fragment the generated files that are `executable`). The reference app runs `npm run platform:infra:sync` and CI fails on drift with `npm run platform:infra:sync -- --check` (the `Build & Test` job of `.github/workflows/ci.yml`). It is a command of the package's bin, not an export.
47
137
 
48
138
  ## Data
49
139
 
@@ -59,9 +149,50 @@ None. The package renders nothing.
59
149
 
60
150
  ## Infra
61
151
 
62
- Slice files ship under `<slice>/` (`telemetry/compose/`, `telemetry/otel/`); the root `compose/`, `nginx/` and `otel/` folders are still empty. `infraFile(relativePath)` (`@stability experimental`) returns the absolute path of a shipped file and throws on an empty, absolute or escaping path. No environment variable is read.
152
+ ### File order per mode
153
+
154
+ Platform fragments in the documented order, then the app overlays that apply to the mode, sorted by file name:
155
+
156
+ | Mode | Platform files | Overlays applied |
157
+ |---|---|---|
158
+ | dev | `base`, `dev`, [`telemetry`] | `app.<name>`, `app.dev.<name>` |
159
+ | devdb | `base`, `dev`, `devdb`, [`telemetry`] | `app.<name>`, `app.dev.<name>`, `app.devdb.<name>` |
160
+ | prod | `base`, `prod`, [`telemetry`] | `app.<name>`, `app.prod.<name>` |
161
+ | vps (the deploy) | `base`, `prod`, `telemetry`, `vps`, `vps.telemetry` | `app.<name>`, `app.prod.<name>`, `app.vps.<name>` |
162
+ | worker | `worker`, [`worker.build`] | `app.worker.<name>` |
163
+
164
+ The VPS files come after every file whose `ports:` they override (`ports: !override` only replaces what came before), `telemetry` adds services before them, and app overlays come last so they win. `test.compose.yml` is used on its own (`docker compose -f infra/compose/test.compose.yml up -d`, PostgreSQL on 5433).
165
+
166
+ ### Where the files land
63
167
 
64
- Generated files start with a `# GENERATED from @marinoscar/platform-infra@<version> (<slice>)` header and are never edited in the app; `infra/platform-infra.lock.json` records the version and the sha256 of each body. App-owned files (the collector overlay `infra/otel/app-collector.yaml`) are created once from a package example and never overwritten.
168
+ | Package | App (generated) | App-owned, created once |
169
+ |---|---|---|
170
+ | `compose/*.compose.yml` | `infra/compose/*.compose.yml` | `infra/compose/app.example.compose.yml` |
171
+ | `compose/postgres-init/10-application-role.sh` (executable) | `infra/compose/postgres-init/10-application-role.sh`, mode `0755` | |
172
+ | `nginx/nginx.conf`, `csp.conf`, `csp.dev.conf`, `platform/*` | `infra/nginx/…` | `infra/nginx/app.d/` (`permissions-policy.conf`, `http/`, `server/`, `locations/`) |
173
+ | `env/base.env.example` + the app's `app.env.example` | `infra/compose/.env.example` | `infra/compose/app.env.example` |
174
+ | `env/worker.env.example` | `infra/compose/.env.worker.example` | |
175
+ | `telemetry/**` | see the [telemetry slice](src/telemetry/README.md#infra) | `infra/otel/app-collector.yaml` |
176
+
177
+ Generated files start with a `# GENERATED from @marinoscar/platform-infra@<version> (<fragment>)` header and are never edited in the app. They are committed, because a VPS deploy runs Compose in a git checkout with no `node_modules`; Compose keeps resolving `context: ../..` and `../nginx/…` against `infra/compose`, as before.
178
+
179
+ ### Executable scripts
180
+
181
+ A generated file marked `executable` in its fragment (`InfraFile.executable`; today `postgres-init/10-application-role.sh`) is a script a container runs by path, so the copy keeps what running it needs:
182
+
183
+ - **the shebang stays on line 1.** The two-line generated header goes after it, and the lock's checksum covers the body with its shebang and without the header. An executable package file without a `#!` line is refused before anything is written.
184
+ - **the mode is `0755`.** Sync writes the file with that mode and restores it when only the mode was lost (it then reports the file as written). The lock lists the file under its fragment's `executable` key, so the mode is part of what a reviewer sees in a lock diff.
185
+ - **`--check` fails on a lost executable bit**: a `chmod -x`, or a checkout of a commit that recorded the file as `100644`. It reads the owner's execute bit, the one git records. A lock whose `executable` list does not match the manifest fails as well.
186
+
187
+ Commit the mode with the file (`git add` records it; on a checkout without mode bits, such as Windows, `git update-index --chmod=+x <file>`). Windows has no executable bit, so there sync neither sets nor checks it. The package's own copy is `100755` too, and npm keeps the mode when it packs and installs, but sync does not rely on it: the manifest decides.
188
+
189
+ The `postgres-init/` directory is mounted whole, and sync removes nothing it does not generate, so an app adds its own first-start step as another script beside the platform's (`infra/compose/postgres-init/20-<name>.sh`, run in file-name order after `10-application-role.sh`). That file is the app's: sync never lists it in the lock nor checks it.
190
+
191
+ ### Env fragments
192
+
193
+ `infra/compose/.env.example`, the one template the deploy wizard, `init` and Compose's `env_file` read, is `env/base.env.example` (the platform's variables, rendered) followed by the app's `infra/compose/app.env.example`. A new platform variable goes into `env/base.env.example`; an app's own into `app.env.example`, then `sync`. Never write a commented `# KEY=value` line in either: the wizard reads it as a declared variable (`packages/platform-cli/src/engine/deploy/env-spec.test.ts` checks every fragment). No environment variable exists for a runtime-configured feature (storage, AI, SMTP, Web Push).
194
+
195
+ `infraFile(relativePath)` (`@stability experimental`) returns the absolute path of a shipped file and throws on an empty, absolute or escaping path.
65
196
 
66
197
  ## Observability
67
198
 
@@ -69,22 +200,44 @@ None. The package emits nothing at run time; the telemetry slice ships the colle
69
200
 
70
201
  ## Security notes
71
202
 
72
- `infraFile()` refuses absolute paths and any path that resolves outside the package root, so a caller cannot use it to read arbitrary files. `platform-infra sync` refuses any path that leaves the app root or the package, validates its whole plan before writing, and never overwrites an app-owned file.
203
+ - **Header inheritance.** nginx's `add_header` replaces, never merges: a location that declares one header of its own drops every server-level one, CSP and HSTS included, with no error. The security set therefore lives in one file, `platform/security-headers.conf`, included at server level and by `platform/sse-proxy.conf`, so an app's SSE location keeps every header even when it adds one (`Cache-Control` in the EvoPath fixture). An app location that adds a header without the snippet must `include /etc/nginx/platform/security-headers.conf;`; `nginx-app-locations.spec.ts` fails otherwise.
204
+ - **The stack agent holds the Docker socket** (root-equivalent on the host). It is confined to `apps/stack-agent`: no parameters, no published port, token-gated, read-only, all capabilities dropped (see `vps.compose.yml`). An app that does not want it switches it off with an overlay (`profiles: ["disabled"]`), never by editing `vps.compose.yml`.
205
+ - `infraFile()` and `sync` refuse absolute paths and any path that leaves the package or the app root; `sync` validates its whole plan before writing, never overwrites an app-owned file, and refuses an identity value that could break the file it is rendered into (whitespace, `$`, quotes).
206
+ - The internal `stub_status` listener (port 8081) is published by no compose file; an app file must not serve it either (`nginx-app-locations.spec.ts`).
73
207
 
74
208
  ## Conformance suite
75
209
 
76
- None yet. The package ships no conformance suite; `runPlatformConformance()` and the suites arrive with the platform's conformance harness.
210
+ `runInfraConformance({ appRoot, testApi })` from `@marinoscar/platform-infra/testing`, called from the app's own test file ([`apps/cli/src/infra-conformance.test.ts`](../../apps/cli/src/infra-conformance.test.ts)). Three checks:
211
+
212
+ - `sync --check`: the generated files are the package's and match the lock.
213
+ - `docker compose config` for each mode (`dev`, `devdb`, `prod`, `vps`, `test` by default; `modes` and `env` override) over the platform files and the app's overlays, so an overlay that does not merge fails here, not on the server.
214
+ - `nginx -t` over the composed configuration with the app's `app.d/`, once for `csp.conf` and once for `csp.dev.conf`: with a local `nginx` binary in a scratch directory, else in the image `base.compose.yml` pins when a Docker daemon runs.
215
+
216
+ Docker and nginx are tools, not dependencies. When one is missing the case is registered as a passing case whose name carries the reason (`compose config: skipped (docker compose is not available)`) and a warning is printed, so a missing tool is visible and never reads as a check. `skip: { sync, compose, nginx }` opts out of a check on purpose, and each opt-out needs a reason. The check is read-only: nothing starts a container or writes into the app.
217
+
218
+ The package's own invariants also run as its tests (`docker compose config` snapshots, `nginx -t` and served headers) and as CI's `sync --check` and pinned-image `nginx -t`.
77
219
 
78
220
  ## Upgrade notes
79
221
 
80
- None. No version has been published yet, so there is nothing to migrate from.
222
+ From the files an app copied by hand (before #714): run `npx platform-infra sync`, then move every difference from the generated files into an overlay: extra compose settings into `infra/compose/app.*.compose.yml`, nginx locations into `infra/nginx/app.d/locations/` (SSE routes through `platform/sse-proxy.conf`), the `Permissions-Policy` into `infra/nginx/app.d/permissions-policy.conf`, app variables into `infra/compose/app.env.example`. After a rename (`scripts/rename.mjs`), run the sync again: it re-renders the identity and rewrites the lock.
81
223
 
82
224
  ## Troubleshooting
83
225
 
84
- `sync --check` failures (a hand-edited generated file, a stale lock) are in the [telemetry slice README](src/telemetry/README.md#troubleshooting) and [the telemetry runbook § 12](../../docs/runbooks/telemetry.md#12-troubleshooting). Build and import problems common to every platform package are in [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages).
226
+ - **`sync --check`: `differs from @marinoscar/platform-infra@…`.** A generated file was edited. Run `npm run platform:infra:sync`, then make the change in the overlay the message names.
227
+ - **`is not executable`.** A generated script lost its mode bit (a `chmod -x`, an editor that rewrote it, or a commit that recorded `100644`). Run `npm run platform:infra:sync`, then commit the mode change; on Windows use `git update-index --chmod=+x <file>`. Why it matters: the postgres image runs an executable `.sh` in `/docker-entrypoint-initdb.d` but *sources* one that is not, so the script's `set -eu` and `exit` act on the image's entrypoint itself. If a volume was initialised that way, check the Doctor's `db.rls_role` and recreate the volume if the role is wrong.
228
+ - **`records a different checksum`.** The lock was edited or not rewritten (for example after `scripts/rename.mjs` changed a rendered value): run the sync.
229
+ - **`is rendered with the app identity, and none was found`.** Add `packages/shared/identity.json` with `productName` and `cliName`, or pass `--identity <file>`.
230
+ - **nginx: `open() "/etc/nginx/app.d/permissions-policy.conf" failed`.** The app-owned file is missing; the sync recreates it from the platform default.
231
+ - **`Unknown compose mode "x"`.** `composeFilesForMode` got a mode that is neither built in nor registered: call `registerComposeMode({ id, files })` first.
232
+ - **nginx: `unknown "csp_..._extra" variable` or a CSP line that did not change.** A file in `app.d/csp/` must be named after a directive (`connect-src*.conf` and the others listed above) and contain a `default "<value>";` line with a leading space (or `; ` for `extra`). A file ending in `.example` is inert.
233
+ - **A changed `app.d/` file is not served.** The directory mount shows the new file at once, but nginx reads its configuration at start: recreate or reload nginx (`docker compose … up -d --force-recreate nginx`).
234
+
235
+ Collector overlay failures are in the [telemetry slice README](src/telemetry/README.md#troubleshooting). Build and import problems common to every platform package are in [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages).
85
236
 
86
237
  ## Links
87
238
 
88
239
  - [Platform packages spec](../../docs/specs/platform-packages.md): the extension contract and the package documentation standard
240
+ - [VPS deploy spec](../../docs/specs/vps-deploy.md) and [runbook](../../docs/runbooks/deploy-to-vps.md): where the deploy's fragments come from and how an app adds an overlay
241
+ - [Worker nodes runbook](../../docs/runbooks/run-worker-nodes.md): the rendered worker variables
89
242
  - [Package documentation standard and checks](../../docs/PACKAGES.md): how this README, the TSDoc and the catalog are checked
90
243
  - [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages): build, test and lint commands
@@ -0,0 +1,149 @@
1
+ # @marinoscar/platform-infra/android/platform-core
2
+
3
+ The platform's Android library module (`:platform-core`, Kotlin package `io.github.marinoscar.platform.android.core`): the Trusted Web Activity launcher, server configuration, the device-flow pairing, encrypted token storage, the JSON API client, app updates from the server's APK releases and notification-permission rules, shared by every platform Android app. It ships as plain Gradle files inside `@marinoscar/platform-infra`, so no Maven registry is involved; the app's `settings.gradle.kts` includes it from `node_modules`. Design: [native companion architecture](../../../../docs/specs/native-companion-architecture.md).
4
+
5
+ ## Purpose and scope
6
+
7
+ What the module owns, merged from EvoPath's and MemoriaHub's apps:
8
+
9
+ | Package | Contents |
10
+ |---|---|
11
+ | `twa` | `TwaLauncher`, the base launcher activity (a `LauncherActivity` of androidbrowserhelper) |
12
+ | `config` | `ServerUrls` (https origin rules, the launch URL), `ServerConfig` (the saved server, `<storagePrefix>_config`) |
13
+ | `pairing` | `DeviceFlowTransport`, `DeviceFlowPoller` (RFC 8628), `PairingManager`, the `PairingHook` seam, `TokenRevoker`, `DeviceInfo` |
14
+ | `auth` | `TokenStore` (`EncryptedTokenStore` in `<storagePrefix>_secure`), `AuthFailures` (the `401` and `409 DEVICE_REVOKED` rules) |
15
+ | `net` | `ApiClient` (envelope unwrapping, error parsing, no secret in a log line), `ApiResult`, `ApiError` |
16
+ | `update` | `UpdateChecker`, `UpdatePolicy`, `BackgroundUpdateCheck`, `AppUpdates.download` (`/api/android-app/releases/latest`, then a signed link) |
17
+ | `notifications` | `NotificationPermissions` (state, action and row for `POST_NOTIFICATIONS`), the first-open prompt |
18
+ | `util` | `AppInfo` (installed version, signing fingerprint), `Fingerprints`, `PlatformLog` |
19
+ | (root) | `PlatformIdentity` (product name, storage prefix, deep-link scheme, default server, from `BuildConfig`) |
20
+
21
+ Out of scope, owned by each app: native capabilities (EvoPath's Health Connect sync, MemoriaHub's media sync), their device tables, screens and diagnostics, and the app's own icons and copy. A capability plugs in through `PairingHook` here and `registerAndroidDeviceSource` on the server ([API slice](../../../platform-api/src/android-app/README.md)).
22
+
23
+ ## Install and peer dependencies
24
+
25
+ Ships inside `@marinoscar/platform-infra` (the npm workspace or the installed package). Include it from the app's `settings.gradle.kts`, the recipe the reference shell uses ([apps/android/settings.gradle.kts](../../../../apps/android/settings.gradle.kts)):
26
+
27
+ ```kotlin
28
+ include(":platform-core")
29
+ project(":platform-core").projectDir =
30
+ file("../../node_modules/@marinoscar/platform-infra/android/platform-core")
31
+ ```
32
+
33
+ The app's root `build.gradle.kts` declares the plugins with `apply false`: `com.android.application` and `com.android.library` 8.13.2, `org.jetbrains.kotlin.android` and `org.jetbrains.kotlin.plugin.serialization` 2.2.21 ([example](../../../../apps/android/build.gradle.kts), [versions](../../../../apps/android/gradle/libs.versions.toml)); Gradle 8.14.3 and JDK 17 or newer. The module pins its own dependencies (androidbrowserhelper 2.6.2, OkHttp 4.12.0, kotlinx.serialization 1.9.0, coroutines 1.10.2, security-crypto 1.1.0, core-ktx 1.17.0), so the app's version catalog needs no entry for them. compileSdk 36, minSdk 26.
34
+
35
+ ## Quick start
36
+
37
+ The reference shell ([apps/android](../../../../apps/android)) is the whole recipe:
38
+
39
+ ```kotlin
40
+ // app/build.gradle.kts
41
+ apply(from = project(":platform-core").file("identity.gradle.kts"))
42
+ val identity = project.extensions.extraProperties.get("platformIdentity") as Map<String, String>
43
+ android { defaultConfig { applicationId = identity.getValue("applicationId") /* … */ } }
44
+ dependencies { implementation(project(":platform-core")) }
45
+ ```
46
+
47
+ ```kotlin
48
+ // The launcher (declared in the manifest with the TWA meta-data and an activity-alias)
49
+ class TwaLauncherActivity : TwaLauncher() {
50
+ override fun setupActivity() = SetupActivity::class.java
51
+ }
52
+ ```
53
+
54
+ The setup screen saves the server with `ServerConfig.from(context).setServerUrl(input)` ([SetupActivity](../../../../apps/android/app/src/main/kotlin/com/enterpriseapp/android/SetupActivity.kt)). Build: `cd apps/android && ./gradlew assembleDebug testDebugUnitTest`.
55
+
56
+ ## Configuration
57
+
58
+ Identity and version come from Gradle, through `identity.gradle.kts`, applied by the module and by the app. It reads the app's `packages/shared/identity.json` (two levels above the Gradle root) and its optional `android` block, and derives exactly what `androidIdentity()` of `@marinoscar/platform-contract/android-app` derives for the CLI and the API:
59
+
60
+ | Value | Default | `android` block | `-P` override |
61
+ |---|---|---|---|
62
+ | `applicationId` | `com.<token>.android` (token: the repository name lower-cased to letters and digits) | `applicationId` | `app.applicationId` |
63
+ | `storagePrefix` | `<token>` (never change it for a shipped app) | `storagePrefix` | none |
64
+ | `deepLinkScheme` | the repository name lower-cased to scheme characters (`app`-prefixed when it starts with a digit), plus `-android` | `deepLinkScheme` | `app.deepLinkScheme` |
65
+ | `apkStem` | `slugify(productName)-android` | `apkStem` | none |
66
+ | `productName` | identity.json `productName` | none | `app.productName` |
67
+ | `versionName`, `versionCode` | `apps/android/version.properties` | none | `app.versionName`, `app.versionCode` |
68
+ | default server | empty (the setup screen asks) | none | `app.serverUrl` |
69
+ | identity file | `../../packages/shared/identity.json` from the Gradle root | none | `app.identityJson` |
70
+
71
+ The script stores the result as the extra property `platformIdentity` (a `Map<String, String>`, also carrying `themeColor` and `backgroundColor` as `#FFRRGGBB`, `twaHost` and `twaHostUnset`). The module's `BuildConfig` gets `PRODUCT_NAME`, `STORAGE_PREFIX`, `DEEP_LINK_SCHEME`, `DEFAULT_SERVER_URL` and `TWA_HOST`, read through `PlatformIdentity`.
72
+
73
+ ## Extension-point catalog
74
+
75
+ The extension ladder and a recipe per extension: [docs/EXTENDING.md](../../../../docs/EXTENDING.md).
76
+
77
+ Kotlin and Gradle seams (not TypeScript symbols, so `check:package-docs` does not read this table):
78
+
79
+ | Name | Kind | Signature | When to use | Stability | Example |
80
+ |---|---|---|---|---|---|
81
+ | `:platform-core` include | overlay | `include(":platform-core")` + `projectDir` | Add the module to an app's Gradle build | experimental | [settings.gradle.kts](../../../../apps/android/settings.gradle.kts) |
82
+ | `identity.gradle.kts` | option | `apply(from = …)` then `extra["platformIdentity"]` | Derive applicationId, label, scheme, prefix and version from identity.json | experimental | [app/build.gradle.kts](../../../../apps/android/app/build.gradle.kts) |
83
+ | `TwaLauncher` | component | `abstract class TwaLauncher : LauncherActivity` | The app's launcher: subclass it and name the setup screen | experimental | [TwaLauncherActivity.kt](../../../../apps/android/app/src/main/kotlin/com/enterpriseapp/android/TwaLauncherActivity.kt) |
84
+ | `TwaLauncher.onAppOpen` | hook | `protected open fun onAppOpen()` | A native capability's debounced "app opened" work | experimental | [TwaLauncher.kt](src/main/kotlin/io/github/marinoscar/platform/android/core/twa/TwaLauncher.kt) |
85
+ | `PairingHook` | hook | `interface PairingHook { register; unregister; onPaired; onForgotten }` | Register this phone with a native capability's device API after the device flow | experimental | [PairingManagerTest.kt](src/test/kotlin/io/github/marinoscar/platform/android/core/pairing/PairingManagerTest.kt) |
86
+ | `PlatformLog.sink` | hook | `var sink: (Level, String, String, Throwable?) -> Unit` | Keep the module's log lines in the app's diagnostics buffer | experimental | [ApiClientTest.kt](src/test/kotlin/io/github/marinoscar/platform/android/core/net/ApiClientTest.kt) |
87
+ | `ServerConfig` | option | `ServerConfig.from(context).setServerUrl(input)` | Save the server address from a setup or settings screen | experimental | [SetupActivity.kt](../../../../apps/android/app/src/main/kotlin/com/enterpriseapp/android/SetupActivity.kt) |
88
+
89
+ ## Data
90
+
91
+ On-device only, every name prefixed with `storagePrefix`:
92
+
93
+ | File | Kind | Contents |
94
+ |---|---|---|
95
+ | `<prefix>_config` | SharedPreferences | `server_url` (not secret) |
96
+ | `<prefix>_secure` | EncryptedSharedPreferences (Keystore AES-256 GCM) | `token`, `token_id`, `expires_at`, `device_id`, `installation_id` |
97
+ | `<prefix>_app_update` | SharedPreferences | the last check, the offered release, the notified versionCode |
98
+ | `<prefix>_notifications` | SharedPreferences | whether the permission prompt was shown or requested |
99
+
100
+ The app excludes shared preferences from cloud backup and device transfer (the reference shell's `backup_rules.xml` and `data_extraction_rules.xml`). Server-side data (releases, trusted apps, push subscriptions) belongs to the [API slice](../../../platform-api/src/android-app/README.md#data).
101
+
102
+ ## Permissions and settings
103
+
104
+ Android permissions merged into the app: `INTERNET`, `ACCESS_NETWORK_STATE`, `POST_NOTIFICATIONS`, plus a `<queries>` entry for Custom Tabs services. Server permissions: none of its own; pairing mints a personal access token for the approving user, and the release routes need only an authenticated user. The trusted apps behind `/.well-known/assetlinks.json` are the `android_app` system setting (`system_settings:write`).
105
+
106
+ ## UI
107
+
108
+ None. The module draws nothing: the app owns its setup screen, its native screens and their copy. `NotificationPermissions.row()` returns the strings and action for a Notifications row, and `UpdatePolicy` the update notification's title and text.
109
+
110
+ ## Infra
111
+
112
+ The server publishes `/.well-known/assetlinks.json` for the trusted (package, signing key) pairs; the nginx snippet `platform/android-app.conf` routes it ([infra README](../../README.md#infra)). CI builds the reference shell with `.github/workflows/android.yml` (debug APK and JVM unit tests, no secret).
113
+
114
+ ## Observability
115
+
116
+ `PlatformLog` writes one line per failed API call (method, path, status, API code and `details.reason`) and pairing milestones, to logcat by default. Never a token, a query string, a body or a header. Device-flow polling noise (`authorization_pending`, `slow_down`) is left out.
117
+
118
+ ## Security notes
119
+
120
+ - No WebView and no JavaScript interface, anywhere: the web app runs in the user's browser through the TWA, and the two sides coordinate only through the launch URL, deep links, the server and Digital Asset Links. A bridge would turn XSS into native code execution. `src/android-core.test.ts` greps the module and the reference shell.
121
+ - Tokens live only in `EncryptedTokenStore`; an unreadable keyset resets the pairing instead of falling back to plain storage.
122
+ - The device flow asks for a PAT (`clientInfo.tokenType: "pat"`) and refuses any other credential type.
123
+ - `AuthFailures.classify`: a `401` stops work and asks to re-pair; `409 DEVICE_REVOKED` forgets the pairing.
124
+ - A download link is followed only on the configured server's origin (`UpdatePolicy.downloadUrl`); the server address must be https.
125
+
126
+ ## Conformance suite
127
+
128
+ JVM unit tests in `src/test` (100 tests): `ServerUrls` and `ServerConfig`, the device-flow poller and request shape, `PairingManager` with and without a hook, the token store, `ApiClient` envelope and error parsing, `AuthFailures`, fingerprint normalisation (the server's two accepted forms), the update policy and checker, `sizeBytes` as a decimal string, notification-permission states. Run them with `cd apps/android && ./gradlew :platform-core:testDebugUnitTest`.
129
+
130
+ ## Upgrade notes
131
+
132
+ New in `@marinoscar/platform-infra` 0.1 (#746). For EvoPath and MemoriaHub, adopting it means deleting their copies of `twa/`, `pairing/`, `auth/`, `net/`, `config/`, `update/` and `util/` and importing from this package; an app that shipped with another `storagePrefix` or `applicationId` pins both in identity.json's `android` block first, or installed phones lose the server address and the pairing.
133
+
134
+ ## Troubleshooting
135
+
136
+ | Symptom | Cause | Fix |
137
+ |---|---|---|
138
+ | `platform-core not found` at configuration | `node_modules` is not installed | `npm install` at the repository root |
139
+ | `Product identity not found` | the Gradle root is not two levels below the repository root | pass `-Papp.identityJson=<path>` |
140
+ | The TWA shows a URL bar | `assetlinks.json` does not list this package and signing key | trust the app in Admin, Android app, or publish a release with `--trust` |
141
+ | Web Push stays Chrome's | the build had no `app.serverUrl`, so the https intent-filter names `invalid.example` | build with `-Papp.serverUrl=https://<server>` |
142
+ | Pairing fails with "issued a … instead of an access token" | the server answered a non-PAT credential | update the server; the device flow must honour `tokenType: "pat"` |
143
+
144
+ ## Links
145
+
146
+ - [Native companion architecture](../../../../docs/specs/native-companion-architecture.md)
147
+ - [Android app runbook](../../../../docs/runbooks/android-app.md) and [release runbook](../../../../docs/runbooks/android-release.md)
148
+ - [API slice](../../../platform-api/src/android-app/README.md), [web slice](../../../platform-web/src/android-app/README.md), [CLI group](../../../platform-cli/src/android/README.md)
149
+ - [Device authorization](../../../../docs/DEVICE-AUTH.md)
@@ -0,0 +1,86 @@
1
+ // =============================================================================
2
+ // :platform-core — the platform's Android library module (#746)
3
+ // =============================================================================
4
+ //
5
+ // Shipped as files inside @marinoscar/platform-infra (no Maven publishing). An
6
+ // app includes it from its settings.gradle.kts:
7
+ //
8
+ // include(":platform-core")
9
+ // project(":platform-core").projectDir =
10
+ // file("../../node_modules/@marinoscar/platform-infra/android/platform-core")
11
+ //
12
+ // The app's root build.gradle.kts declares the plugin versions (`apply false`):
13
+ // com.android.library and com.android.application 8.13.2, Kotlin 2.2.21
14
+ // (org.jetbrains.kotlin.android and org.jetbrains.kotlin.plugin.serialization).
15
+ // The library pins its own dependencies below, so an app's version catalog
16
+ // needs no entry for it.
17
+ //
18
+ // Identity (product name, storage prefix, deep-link scheme, default server)
19
+ // comes from the app's packages/shared/identity.json through
20
+ // identity.gradle.kts, applied here and by the app module, into BuildConfig.
21
+ // =============================================================================
22
+
23
+ plugins {
24
+ id("com.android.library")
25
+ id("org.jetbrains.kotlin.android")
26
+ id("org.jetbrains.kotlin.plugin.serialization")
27
+ }
28
+
29
+ apply(from = file("identity.gradle.kts"))
30
+
31
+ @Suppress("UNCHECKED_CAST")
32
+ val platformIdentity = project.extensions.extraProperties.get("platformIdentity") as Map<String, String>
33
+
34
+ fun quoted(value: String): String = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
35
+
36
+ android {
37
+ namespace = "io.github.marinoscar.platform.android.core"
38
+ compileSdk = 36
39
+
40
+ defaultConfig {
41
+ minSdk = 26
42
+ consumerProguardFiles("consumer-rules.pro")
43
+
44
+ buildConfigField("String", "PRODUCT_NAME", quoted(platformIdentity.getValue("productName")))
45
+ // Prefix of SharedPreferences files and other on-device names. Never change it for a
46
+ // shipped app: phones would lose the server address and the pairing.
47
+ buildConfigField("String", "STORAGE_PREFIX", quoted(platformIdentity.getValue("storagePrefix")))
48
+ buildConfigField("String", "DEEP_LINK_SCHEME", quoted(platformIdentity.getValue("deepLinkScheme")))
49
+ buildConfigField("String", "DEFAULT_SERVER_URL", quoted(platformIdentity.getValue("defaultServerUrl")))
50
+ buildConfigField("String", "TWA_HOST", quoted(platformIdentity.getValue("twaHost")))
51
+ }
52
+
53
+ compileOptions {
54
+ sourceCompatibility = JavaVersion.VERSION_17
55
+ targetCompatibility = JavaVersion.VERSION_17
56
+ }
57
+
58
+ buildFeatures {
59
+ buildConfig = true
60
+ }
61
+
62
+ testOptions {
63
+ unitTests.isReturnDefaultValues = true
64
+ }
65
+ }
66
+
67
+ kotlin {
68
+ compilerOptions {
69
+ jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
70
+ }
71
+ }
72
+
73
+ dependencies {
74
+ // `api`: the app's launcher extends TwaLauncher (a LauncherActivity), and its code sees
75
+ // ApiResult, OkHttp and kotlinx.serialization types in the public surface.
76
+ api("com.google.androidbrowserhelper:androidbrowserhelper:2.6.2")
77
+ api("com.squareup.okhttp3:okhttp:4.12.0")
78
+ api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
79
+ api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
80
+ implementation("androidx.core:core-ktx:1.17.0")
81
+ implementation("androidx.security:security-crypto:1.1.0")
82
+
83
+ testImplementation("junit:junit:4.13.2")
84
+ testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
85
+ testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
86
+ }