@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -14,6 +14,10 @@
14
14
  //! `canvas_label` must be `mobile-surface` (use `mobile_shell_scene` /
15
15
  //! `mobile_gpu_surface_label` for the canonical single-surface scene).
16
16
  //! - optional `pub const features: native_sdk.UiAppFeatures`
17
+ //! - optional `pub fn serviceDataRoot([]const u8) void` /
18
+ //! `pub fn serviceTeardown() void` — the generated TypeScript mobile
19
+ //! wiring's hooks: the host hands `setDataRoot`'s directory to the
20
+ //! in-process service pool and tears the pool down on destroy.
17
21
  //!
18
22
  //! The host owns a `NullPlatform` runtime (M1: no real surface — M2 adds
19
23
  //! presentation) and pumps the `UiApp` loop from the shim's frame callback:
@@ -24,10 +28,13 @@
24
28
  //! the ABI via `native_sdk_app_render_pixels`.
25
29
 
26
30
  const std = @import("std");
31
+ const builtin = @import("builtin");
27
32
  const app_manifest = @import("app_manifest");
28
33
  const canvas = @import("canvas");
29
34
  const runtime = @import("../runtime/root.zig");
30
35
  const platform = @import("../platform/root.zig");
36
+ const app_dirs = @import("app_dirs");
37
+ const security = @import("../security/root.zig");
31
38
  const types = @import("types.zig");
32
39
  const host = @import("host.zig");
33
40
  const conversions = @import("conversions.zig");
@@ -57,7 +64,51 @@ pub const mobile_shell_windows = [_]app_manifest.ShellWindow{.{
57
64
  pub const mobile_shell_scene: app_manifest.ShellConfig = .{ .windows = &mobile_shell_windows };
58
65
 
59
66
  pub fn UiAppHost(comptime AppDef: type) type {
67
+ return UiAppHostWithStorage(AppDef, false, false, &.{});
68
+ }
69
+
70
+ /// Capability-specialized mobile host. The boolean is comptime so a mobile
71
+ /// artifact without `store` never analyzes SQLite open/deinit and carries no
72
+ /// database symbols; `build/app.zig` supplies the manifest-inferred value.
73
+ pub fn UiAppHostWithRecordStore(comptime AppDef: type, comptime record_store_enabled: bool) type {
74
+ return UiAppHostWithStorage(AppDef, record_store_enabled, false, &.{});
75
+ }
76
+
77
+ /// Capability-specialized mobile host for the two SQLite-backed storage
78
+ /// tiers. Both databases use the OS-owned data root but remain separate files.
79
+ pub fn UiAppHostWithStorage(
80
+ comptime AppDef: type,
81
+ comptime record_store_enabled: bool,
82
+ comptime relational_store_enabled: bool,
83
+ comptime relational_migrations: []const runtime.relational_store.Migration,
84
+ ) type {
85
+ return UiAppHostWithStorageAndCredentials(
86
+ AppDef,
87
+ record_store_enabled,
88
+ relational_store_enabled,
89
+ relational_migrations,
90
+ false,
91
+ false,
92
+ false,
93
+ "dev.native_sdk.app",
94
+ );
95
+ }
96
+
97
+ /// Capability-specialized mobile host including the OS credential-store
98
+ /// gate and the app identity used as its service namespace.
99
+ pub fn UiAppHostWithStorageAndCredentials(
100
+ comptime AppDef: type,
101
+ comptime record_store_enabled: bool,
102
+ comptime relational_store_enabled: bool,
103
+ comptime relational_migrations: []const runtime.relational_store.Migration,
104
+ comptime credentials_enabled: bool,
105
+ comptime credentials_permitted: bool,
106
+ comptime filesystem_permitted: bool,
107
+ comptime credentials_service: []const u8,
108
+ ) type {
60
109
  const features: runtime.UiAppFeatures = if (@hasDecl(AppDef, "features")) AppDef.features else .{};
110
+ const RecordStoreType = if (record_store_enabled) runtime.RecordStore else void;
111
+ const RelationalStoreType = if (relational_store_enabled) runtime.RelationalStore else void;
61
112
  return struct {
62
113
  const Self = @This();
63
114
 
@@ -69,6 +120,10 @@ pub fn UiAppHost(comptime AppDef: type) type {
69
120
  /// the host wraps it so ABI-facing counters observe every event.
70
121
  inner_app: runtime.App,
71
122
  embedded: EmbeddedApp,
123
+ record_store: RecordStoreType = undefined,
124
+ record_store_open: bool = false,
125
+ relational_store: RelationalStoreType = undefined,
126
+ relational_store_open: bool = false,
72
127
  started: bool = false,
73
128
  frame_index: u64 = 0,
74
129
  last_error: ?anyerror = null,
@@ -78,11 +133,14 @@ pub fn UiAppHost(comptime AppDef: type) type {
78
133
  asset_root_len: usize = 0,
79
134
  asset_entry: [max_mobile_asset_entry_bytes]u8 = undefined,
80
135
  asset_entry_len: usize = 0,
136
+ file_root_storage: [6][max_mobile_asset_root_bytes]u8 = undefined,
137
+ file_roots: [6][]const u8 = undefined,
81
138
  automation_dir: [max_mobile_asset_root_bytes]u8 = undefined,
82
139
  automation_dir_len: usize = 0,
83
140
  automation_io: ?*std.Io.Threaded = null,
84
141
  text_measure: host.MobileTextMeasure = .{},
85
142
  audio: host.MobileAudio = .{},
143
+ credentials: host.MobileCredentials = .{},
86
144
  // Image decode stays declined until the shim registers a real
87
145
  // codec (`native_sdk_app_set_image_service`): the null platform's
88
146
  // strict test decoder is opt-in (`image_decode`, default off), so
@@ -113,7 +171,10 @@ pub fn UiAppHost(comptime AppDef: type) type {
113
171
  const options = AppDef.mobileOptions();
114
172
  if (!std.mem.eql(u8, options.canvas_label, mobile_gpu_surface_label)) return error.InvalidViewOptions;
115
173
  if (!sceneHasMobileSurface(options.scene)) return error.ViewNotFound;
116
- self.null_platform = platform.NullPlatform.init(.{});
174
+ self.null_platform = platform.NullPlatform.initWithOptions(.{}, .system, .{
175
+ .app_name = options.name,
176
+ .bundle_id = credentials_service,
177
+ });
117
178
  self.null_platform.gpu_surfaces = true;
118
179
  // Audio is declined until the shim registers a real service
119
180
  // (`native_sdk_app_set_audio_service`): without one,
@@ -130,6 +191,8 @@ pub fn UiAppHost(comptime AppDef: type) type {
130
191
  // produce real pixels (the buffer M2's surface blit consumes).
131
192
  self.null_platform.gpu_surface_packets = false;
132
193
  self.started = false;
194
+ self.record_store_open = false;
195
+ self.relational_store_open = false;
133
196
  self.frame_index = 0;
134
197
  self.last_error = null;
135
198
  self.command_count = 0;
@@ -138,11 +201,14 @@ pub fn UiAppHost(comptime AppDef: type) type {
138
201
  self.asset_root_len = 0;
139
202
  self.asset_entry = undefined;
140
203
  self.asset_entry_len = 0;
204
+ self.file_root_storage = undefined;
205
+ self.file_roots = undefined;
141
206
  self.automation_dir = undefined;
142
207
  self.automation_dir_len = 0;
143
208
  self.automation_io = null;
144
209
  self.text_measure = .{};
145
210
  self.audio = .{};
211
+ self.credentials = .{};
146
212
  self.image = .{};
147
213
  self.form_factor = .unknown;
148
214
  self.chrome_tabs_projected = false;
@@ -162,6 +228,26 @@ pub fn UiAppHost(comptime AppDef: type) type {
162
228
  .event_fn = hostEvent,
163
229
  .stop_fn = hostStop,
164
230
  }, self.null_platform.platform());
231
+ // The NullPlatform map is for native test only. Installed mobile
232
+ // apps start with no backing until the UIKit/Android shim
233
+ // registers its OS credential service.
234
+ try host.setCredentialService(self, .{}, null);
235
+ self.embedded.runtime.options.credentials_enabled = credentials_enabled;
236
+ self.embedded.runtime.options.security.permissions = if (credentials_permitted and filesystem_permitted)
237
+ &.{ security.permission_credentials, security.permission_filesystem }
238
+ else if (credentials_permitted)
239
+ &.{security.permission_credentials}
240
+ else if (filesystem_permitted)
241
+ &.{security.permission_filesystem}
242
+ else
243
+ &.{};
244
+ // Until the OS data root is installed, fail closed for ungranted
245
+ // raw paths. A filesystem grant is sufficient on its own.
246
+ self.embedded.runtime.options.file_access = .{
247
+ .roots = &.{},
248
+ .permitted = filesystem_permitted,
249
+ .enforce = true,
250
+ };
165
251
  // The damage seam: capture pixel presents (chained through
166
252
  // the null platform's recording present, so nonblank
167
253
  // sampling keeps working), drop the packet presenters no
@@ -172,7 +258,11 @@ pub fn UiAppHost(comptime AppDef: type) type {
172
258
  return self;
173
259
  }
174
260
 
175
- pub fn destroy(self: *Self) void {
261
+ /// Returns true when teardown deliberately preserves the host because
262
+ /// an abandoned platform callback may still enter it. Mobile shims
263
+ /// use the companion C ABI result to preserve their callback context
264
+ /// under the same condition.
265
+ pub fn destroy(self: *Self) bool {
176
266
  host.disableAutomation(self);
177
267
  self.render_memo.deinit();
178
268
  self.ui.deinit();
@@ -180,9 +270,20 @@ pub fn UiAppHost(comptime AppDef: type) type {
180
270
  // its heap-owned registrations (registered canvas font
181
271
  // bytes) before the host storage goes.
182
272
  self.embedded.deinit();
273
+ // An AppDef owning module-level service state (the generated
274
+ // TypeScript mobile wiring's in-process pool) tears it down
275
+ // after the effects channel is gone; the pool's own shutdown
276
+ // already ran through the binding.
277
+ if (comptime @hasDecl(AppDef, "serviceTeardown")) AppDef.serviceTeardown();
278
+ if (comptime record_store_enabled) {
279
+ if (self.record_store_open) self.record_store.deinit();
280
+ }
281
+ if (comptime relational_store_enabled) {
282
+ if (self.relational_store_open) self.relational_store.deinit();
283
+ }
183
284
  // The embedded null platform lives inside `self`, so freeing
184
285
  // `self` IS this path's platform destruction — and an
185
- // abandoned channel wake call may still enter that platform
286
+ // abandoned platform call may still enter that platform
186
287
  // at any later time (see
187
288
  // `PlatformServices.note_channel_wake_abandoned_fn`; the
188
289
  // null platform's own enqueue-only wake never triggers it,
@@ -190,17 +291,96 @@ pub fn UiAppHost(comptime AppDef: type) type {
190
291
  // like every first-party destroy path: skip the free and
191
292
  // leak the host storage, process-lived, with one loud line.
192
293
  if (self.null_platform.channel_wake_abandoned.load(.seq_cst)) {
193
- std.debug.print("mobile ui host teardown: an abandoned channel wake call may still enter the embedded platform; skipping the host free and leaking it, process-lived, so the stale call stays safe\n", .{});
194
- return;
294
+ std.debug.print("mobile ui host teardown: an abandoned platform call may still enter the embedded platform; skipping the host free and leaking it, process-lived, so the stale call stays safe\n", .{});
295
+ return true;
195
296
  }
196
297
  std.heap.page_allocator.destroy(self);
298
+ return false;
197
299
  }
198
300
 
199
301
  pub fn start(self: *Self) anyerror!void {
302
+ if (comptime record_store_enabled) {
303
+ if (!self.record_store_open) return error.StoreDataDirUnavailable;
304
+ }
305
+ if (comptime relational_store_enabled) {
306
+ if (!self.relational_store_open) return error.SqliteDataDirUnavailable;
307
+ }
200
308
  self.started = true;
201
309
  try self.embedded.start();
202
310
  }
203
311
 
312
+ /// Install the OS-owned app-data directory before start. iOS passes
313
+ /// Library/Application Support and Android passes files/, exactly the
314
+ /// `.data` directories resolved by `app_dirs` on those platforms.
315
+ /// An AppDef declaring `serviceDataRoot` (the generated TypeScript
316
+ /// mobile wiring) receives the directory too — the in-process
317
+ /// service pool keeps its cooperative-cancellation markers and
318
+ /// stream relays there, and cores reading `NATIVE_SDK_APP_DATA_DIR`
319
+ /// through `envMsgs` get this value.
320
+ pub fn setDataRoot(self: *Self, data_root: []const u8) !void {
321
+ if (self.started) return error.AppAlreadyStarted;
322
+ if (data_root.len == 0 or data_root.len > max_mobile_asset_root_bytes) return error.InvalidStoreDataDir;
323
+ if (comptime @hasDecl(AppDef, "serviceDataRoot")) AppDef.serviceDataRoot(data_root);
324
+ const platform_value = app_dirs.currentPlatform();
325
+ if (builtin.is_test and platform_value != .ios and platform_value != .android) {
326
+ for (&self.file_root_storage, 0..) |*storage, index| {
327
+ @memcpy(storage[0..data_root.len], data_root);
328
+ self.file_roots[index] = storage[0..data_root.len];
329
+ }
330
+ self.embedded.runtime.options.file_access = .{
331
+ .roots = &self.file_roots,
332
+ .permitted = filesystem_permitted,
333
+ .enforce = true,
334
+ };
335
+ } else {
336
+ const home = switch (platform_value) {
337
+ // iOS data_root is HOME/Library/Application Support.
338
+ .ios => std.fs.path.dirname(std.fs.path.dirname(data_root) orelse return error.InvalidStoreDataDir) orelse return error.InvalidStoreDataDir,
339
+ // Android data_root is HOME/files.
340
+ .android => std.fs.path.dirname(data_root) orelse return error.InvalidStoreDataDir,
341
+ else => return error.InvalidStoreDataDir,
342
+ };
343
+ const dir_buffers = app_dirs.Buffers.fromArray(max_mobile_asset_root_bytes, &self.file_root_storage);
344
+ const dirs = try app_dirs.resolve(
345
+ .{ .name = credentials_service },
346
+ platform_value,
347
+ .{ .home = home },
348
+ dir_buffers,
349
+ );
350
+ self.file_roots = .{ dirs.config, dirs.cache, dirs.data, dirs.state, dirs.logs, dirs.temp };
351
+ self.embedded.runtime.options.file_access = .{
352
+ .roots = &self.file_roots,
353
+ .permitted = filesystem_permitted,
354
+ .enforce = true,
355
+ };
356
+ }
357
+ if (comptime record_store_enabled) {
358
+ if (self.record_store_open) {
359
+ self.record_store.deinit();
360
+ self.record_store_open = false;
361
+ self.embedded.runtime.options.record_store = null;
362
+ }
363
+ self.record_store = try runtime.RecordStore.open(std.heap.page_allocator, data_root);
364
+ self.record_store_open = true;
365
+ self.embedded.runtime.options.record_store = self.record_store.binding();
366
+ }
367
+ if (comptime relational_store_enabled) {
368
+ if (self.relational_store_open) {
369
+ self.relational_store.deinit();
370
+ self.relational_store_open = false;
371
+ self.embedded.runtime.options.relational_store = null;
372
+ }
373
+ const opened = try runtime.RelationalStore.openMigrated(std.heap.page_allocator, data_root, relational_migrations);
374
+ self.relational_store = switch (opened.outcome) {
375
+ .ok => opened.database.?,
376
+ .migrate_failed => return error.SqliteMigrationFailed,
377
+ .version_unknown => return error.SqliteVersionUnknown,
378
+ };
379
+ self.relational_store_open = true;
380
+ self.embedded.runtime.options.relational_store = self.relational_store.binding();
381
+ }
382
+ }
383
+
204
384
  /// Host-pumped frame step: the shim's display-link (or test) tick.
205
385
  /// Synthesizes the `gpu_surface_frame` event a platform loop would
206
386
  /// deliver for the mobile surface — first tick installs the widget
@@ -68,6 +68,7 @@
68
68
  package dev.native_sdk.host;
69
69
 
70
70
  import android.app.Activity;
71
+ import android.content.SharedPreferences;
71
72
  import android.content.res.AssetManager;
72
73
  import android.graphics.Bitmap;
73
74
  import android.graphics.BitmapFactory;
@@ -80,8 +81,12 @@ import android.media.MediaPlayer;
80
81
  import android.os.Bundle;
81
82
  import android.os.Handler;
82
83
  import android.os.Looper;
84
+ import android.security.keystore.KeyGenParameterSpec;
85
+ import android.security.keystore.KeyProperties;
86
+ import android.security.keystore.UserNotAuthenticatedException;
83
87
  import android.text.InputType;
84
88
  import android.util.LruCache;
89
+ import android.util.Base64;
85
90
  import android.view.Choreographer;
86
91
  import android.view.KeyEvent;
87
92
  import android.view.MotionEvent;
@@ -98,10 +103,17 @@ import java.io.File;
98
103
  import java.io.FileOutputStream;
99
104
  import java.io.InputStream;
100
105
  import java.io.OutputStream;
106
+ import java.security.GeneralSecurityException;
107
+ import java.security.KeyStore;
108
+ import java.security.MessageDigest;
101
109
  import java.nio.ByteBuffer;
102
110
  import java.nio.charset.CharacterCodingException;
103
111
  import java.nio.charset.CodingErrorAction;
104
112
  import java.nio.charset.StandardCharsets;
113
+ import javax.crypto.Cipher;
114
+ import javax.crypto.KeyGenerator;
115
+ import javax.crypto.SecretKey;
116
+ import javax.crypto.spec.GCMParameterSpec;
105
117
 
106
118
  public final class NativeSdkActivity extends Activity implements SurfaceHolder.Callback, Choreographer.FrameCallback {
107
119
  private static final int TOUCH_MODE_IDLE = 0;
@@ -231,12 +243,23 @@ public final class NativeSdkActivity extends Activity implements SurfaceHolder.C
231
243
  // section below.
232
244
  nativeSetAudioService(nativeApp);
233
245
 
246
+ // Tier-4 secure storage: AndroidKeyStore holds the non-exportable
247
+ // AES key; app-private preferences hold only authenticated
248
+ // ciphertext. Register before start so boot credential effects can
249
+ // run without ever putting a token in Model state.
250
+ nativeSetCredentialService(nativeApp);
251
+
234
252
  // The platform image decoder (registered before start, so a
235
253
  // boot-effect fx.registerImageBytes already decodes): the
236
254
  // BitmapFactory codec behind the embed image seam — see the image
237
255
  // section below.
238
256
  nativeSetImageService(nativeApp);
239
257
 
258
+ // `getFilesDir()` is app_dirs `.data` on Android. Store-capability
259
+ // builds open store.db here before start; other builds accept the
260
+ // same stable host call as a capability-shed no-op.
261
+ nativeSetDataRoot(nativeApp, getFilesDir().getAbsolutePath());
262
+
240
263
  // Verification harness: `am start --ez native-sdk-automation true`
241
264
  // publishes snapshot.txt into the app's files dir, same protocol
242
265
  // as the desktop -Dautomation=true runners (readable over
@@ -431,6 +454,112 @@ public final class NativeSdkActivity extends Activity implements SurfaceHolder.C
431
454
  return Typeface.DEFAULT;
432
455
  }
433
456
 
457
+ // --------------------------------------------------------- credentials
458
+
459
+ private static final String CREDENTIAL_KEY_ALIAS = "native-sdk.credentials.v1";
460
+ private static final String CREDENTIAL_PREFS = "native-sdk.credentials";
461
+
462
+ private synchronized SecretKey credentialEncryptionKey() throws GeneralSecurityException {
463
+ KeyStore store = KeyStore.getInstance("AndroidKeyStore");
464
+ try {
465
+ store.load(null);
466
+ } catch (java.io.IOException e) {
467
+ throw new GeneralSecurityException(e);
468
+ }
469
+ java.security.Key existing = store.getKey(CREDENTIAL_KEY_ALIAS, null);
470
+ if (existing instanceof SecretKey) return (SecretKey)existing;
471
+ KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
472
+ generator.init(new KeyGenParameterSpec.Builder(
473
+ CREDENTIAL_KEY_ALIAS,
474
+ KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
475
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
476
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
477
+ .setRandomizedEncryptionRequired(true)
478
+ .build());
479
+ return generator.generateKey();
480
+ }
481
+
482
+ private String credentialEntryKey(byte[] service, byte[] account) throws GeneralSecurityException {
483
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
484
+ digest.update(service);
485
+ digest.update((byte)0);
486
+ digest.update(account);
487
+ return Base64.encodeToString(digest.digest(), Base64.NO_WRAP | Base64.URL_SAFE);
488
+ }
489
+
490
+ private SharedPreferences credentialPreferences() {
491
+ return getSharedPreferences(CREDENTIAL_PREFS, MODE_PRIVATE);
492
+ }
493
+
494
+ @SuppressWarnings("unused") // called from android_host.c
495
+ int credentialSet(byte[] service, byte[] account, byte[] secret) {
496
+ try {
497
+ String entryKey = credentialEntryKey(service, account);
498
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
499
+ cipher.init(Cipher.ENCRYPT_MODE, credentialEncryptionKey());
500
+ cipher.updateAAD(entryKey.getBytes(StandardCharsets.UTF_8));
501
+ byte[] iv = cipher.getIV();
502
+ byte[] ciphertext = cipher.doFinal(secret);
503
+ if (iv.length > 255) return -5;
504
+ ByteBuffer packed = ByteBuffer.allocate(1 + iv.length + ciphertext.length);
505
+ packed.put((byte)iv.length).put(iv).put(ciphertext);
506
+ boolean committed = credentialPreferences().edit()
507
+ .putString(entryKey,
508
+ Base64.encodeToString(packed.array(), Base64.NO_WRAP))
509
+ .commit();
510
+ return committed ? 1 : -5;
511
+ } catch (UserNotAuthenticatedException e) {
512
+ return -2;
513
+ } catch (SecurityException e) {
514
+ return -3;
515
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
516
+ return -5;
517
+ }
518
+ }
519
+
520
+ @SuppressWarnings("unused") // called from android_host.c
521
+ long credentialGet(byte[] service, byte[] account, ByteBuffer output) {
522
+ try {
523
+ String entryKey = credentialEntryKey(service, account);
524
+ String encoded = credentialPreferences().getString(entryKey, null);
525
+ if (encoded == null) return -1;
526
+ byte[] packed = Base64.decode(encoded, Base64.NO_WRAP);
527
+ if (packed.length < 2) return -5;
528
+ int ivLength = packed[0] & 0xff;
529
+ if (ivLength == 0 || 1 + ivLength >= packed.length) return -5;
530
+ byte[] iv = java.util.Arrays.copyOfRange(packed, 1, 1 + ivLength);
531
+ byte[] ciphertext = java.util.Arrays.copyOfRange(packed, 1 + ivLength, packed.length);
532
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
533
+ cipher.init(Cipher.DECRYPT_MODE, credentialEncryptionKey(), new GCMParameterSpec(128, iv));
534
+ cipher.updateAAD(entryKey.getBytes(StandardCharsets.UTF_8));
535
+ byte[] secret = cipher.doFinal(ciphertext);
536
+ if (secret.length > output.capacity()) return -4;
537
+ output.position(0);
538
+ output.put(secret);
539
+ return secret.length;
540
+ } catch (UserNotAuthenticatedException e) {
541
+ return -2;
542
+ } catch (SecurityException e) {
543
+ return -3;
544
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
545
+ return -5;
546
+ }
547
+ }
548
+
549
+ @SuppressWarnings("unused") // called from android_host.c
550
+ int credentialDelete(byte[] service, byte[] account) {
551
+ try {
552
+ String key = credentialEntryKey(service, account);
553
+ SharedPreferences preferences = credentialPreferences();
554
+ if (!preferences.contains(key)) return 0;
555
+ return preferences.edit().remove(key).commit() ? 1 : -5;
556
+ } catch (SecurityException e) {
557
+ return -3;
558
+ } catch (GeneralSecurityException e) {
559
+ return -5;
560
+ }
561
+ }
562
+
434
563
  // -------------------------------------------------------------- images
435
564
  //
436
565
  // The platform image decoder behind the embed image service — the
@@ -1361,9 +1490,11 @@ public final class NativeSdkActivity extends Activity implements SurfaceHolder.C
1361
1490
  private native boolean nativeTextInputState(long app, long[] widgetId, float[] frame);
1362
1491
  private native boolean nativeScrollableWidgetAt(long app, float x, float y);
1363
1492
  private native void nativeSetAssetRoot(long app, String path);
1493
+ private native void nativeSetDataRoot(long app, String path);
1364
1494
  private native void nativeSetAutomationDir(long app, String path);
1365
1495
  private native void nativeSetTextMeasure(long app);
1366
1496
  private native void nativeSetAudioService(long app);
1497
+ private native void nativeSetCredentialService(long app);
1367
1498
  private native void nativeSetImageService(long app);
1368
1499
  private native void nativeAudioEvent(long app, int kind, long positionMs, long durationMs, int playing, int buffering);
1369
1500
  private native String nativeLastError(long app);