@native-sdk/cli 0.8.4 → 0.9.0

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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  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/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -28,6 +28,7 @@ const app_manifest = @import("app_manifest");
28
28
  const canvas = @import("canvas");
29
29
  const runtime = @import("../runtime/root.zig");
30
30
  const platform = @import("../platform/root.zig");
31
+ const security = @import("../security/root.zig");
31
32
  const types = @import("types.zig");
32
33
  const host = @import("host.zig");
33
34
  const conversions = @import("conversions.zig");
@@ -57,7 +58,49 @@ pub const mobile_shell_windows = [_]app_manifest.ShellWindow{.{
57
58
  pub const mobile_shell_scene: app_manifest.ShellConfig = .{ .windows = &mobile_shell_windows };
58
59
 
59
60
  pub fn UiAppHost(comptime AppDef: type) type {
61
+ return UiAppHostWithStorage(AppDef, false, false, &.{});
62
+ }
63
+
64
+ /// Capability-specialized mobile host. The boolean is comptime so a mobile
65
+ /// artifact without `store` never analyzes SQLite open/deinit and carries no
66
+ /// database symbols; `build/app.zig` supplies the manifest-inferred value.
67
+ pub fn UiAppHostWithRecordStore(comptime AppDef: type, comptime record_store_enabled: bool) type {
68
+ return UiAppHostWithStorage(AppDef, record_store_enabled, false, &.{});
69
+ }
70
+
71
+ /// Capability-specialized mobile host for the two SQLite-backed storage
72
+ /// tiers. Both databases use the OS-owned data root but remain separate files.
73
+ pub fn UiAppHostWithStorage(
74
+ comptime AppDef: type,
75
+ comptime record_store_enabled: bool,
76
+ comptime relational_store_enabled: bool,
77
+ comptime relational_migrations: []const runtime.relational_store.Migration,
78
+ ) type {
79
+ return UiAppHostWithStorageAndCredentials(
80
+ AppDef,
81
+ record_store_enabled,
82
+ relational_store_enabled,
83
+ relational_migrations,
84
+ false,
85
+ false,
86
+ "dev.native_sdk.app",
87
+ );
88
+ }
89
+
90
+ /// Capability-specialized mobile host including the OS credential-store
91
+ /// gate and the app identity used as its service namespace.
92
+ pub fn UiAppHostWithStorageAndCredentials(
93
+ comptime AppDef: type,
94
+ comptime record_store_enabled: bool,
95
+ comptime relational_store_enabled: bool,
96
+ comptime relational_migrations: []const runtime.relational_store.Migration,
97
+ comptime credentials_enabled: bool,
98
+ comptime credentials_permitted: bool,
99
+ comptime credentials_service: []const u8,
100
+ ) type {
60
101
  const features: runtime.UiAppFeatures = if (@hasDecl(AppDef, "features")) AppDef.features else .{};
102
+ const RecordStoreType = if (record_store_enabled) runtime.RecordStore else void;
103
+ const RelationalStoreType = if (relational_store_enabled) runtime.RelationalStore else void;
61
104
  return struct {
62
105
  const Self = @This();
63
106
 
@@ -69,6 +112,10 @@ pub fn UiAppHost(comptime AppDef: type) type {
69
112
  /// the host wraps it so ABI-facing counters observe every event.
70
113
  inner_app: runtime.App,
71
114
  embedded: EmbeddedApp,
115
+ record_store: RecordStoreType = undefined,
116
+ record_store_open: bool = false,
117
+ relational_store: RelationalStoreType = undefined,
118
+ relational_store_open: bool = false,
72
119
  started: bool = false,
73
120
  frame_index: u64 = 0,
74
121
  last_error: ?anyerror = null,
@@ -83,6 +130,7 @@ pub fn UiAppHost(comptime AppDef: type) type {
83
130
  automation_io: ?*std.Io.Threaded = null,
84
131
  text_measure: host.MobileTextMeasure = .{},
85
132
  audio: host.MobileAudio = .{},
133
+ credentials: host.MobileCredentials = .{},
86
134
  // Image decode stays declined until the shim registers a real
87
135
  // codec (`native_sdk_app_set_image_service`): the null platform's
88
136
  // strict test decoder is opt-in (`image_decode`, default off), so
@@ -113,7 +161,10 @@ pub fn UiAppHost(comptime AppDef: type) type {
113
161
  const options = AppDef.mobileOptions();
114
162
  if (!std.mem.eql(u8, options.canvas_label, mobile_gpu_surface_label)) return error.InvalidViewOptions;
115
163
  if (!sceneHasMobileSurface(options.scene)) return error.ViewNotFound;
116
- self.null_platform = platform.NullPlatform.init(.{});
164
+ self.null_platform = platform.NullPlatform.initWithOptions(.{}, .system, .{
165
+ .app_name = options.name,
166
+ .bundle_id = credentials_service,
167
+ });
117
168
  self.null_platform.gpu_surfaces = true;
118
169
  // Audio is declined until the shim registers a real service
119
170
  // (`native_sdk_app_set_audio_service`): without one,
@@ -130,6 +181,8 @@ pub fn UiAppHost(comptime AppDef: type) type {
130
181
  // produce real pixels (the buffer M2's surface blit consumes).
131
182
  self.null_platform.gpu_surface_packets = false;
132
183
  self.started = false;
184
+ self.record_store_open = false;
185
+ self.relational_store_open = false;
133
186
  self.frame_index = 0;
134
187
  self.last_error = null;
135
188
  self.command_count = 0;
@@ -143,6 +196,7 @@ pub fn UiAppHost(comptime AppDef: type) type {
143
196
  self.automation_io = null;
144
197
  self.text_measure = .{};
145
198
  self.audio = .{};
199
+ self.credentials = .{};
146
200
  self.image = .{};
147
201
  self.form_factor = .unknown;
148
202
  self.chrome_tabs_projected = false;
@@ -162,6 +216,15 @@ pub fn UiAppHost(comptime AppDef: type) type {
162
216
  .event_fn = hostEvent,
163
217
  .stop_fn = hostStop,
164
218
  }, self.null_platform.platform());
219
+ // The NullPlatform map is for native test only. Installed mobile
220
+ // apps start with no backing until the UIKit/Android shim
221
+ // registers its OS credential service.
222
+ try host.setCredentialService(self, .{}, null);
223
+ self.embedded.runtime.options.credentials_enabled = credentials_enabled;
224
+ self.embedded.runtime.options.security.permissions = if (credentials_permitted)
225
+ &.{security.permission_credentials}
226
+ else
227
+ &.{};
165
228
  // The damage seam: capture pixel presents (chained through
166
229
  // the null platform's recording present, so nonblank
167
230
  // sampling keeps working), drop the packet presenters no
@@ -172,7 +235,11 @@ pub fn UiAppHost(comptime AppDef: type) type {
172
235
  return self;
173
236
  }
174
237
 
175
- pub fn destroy(self: *Self) void {
238
+ /// Returns true when teardown deliberately preserves the host because
239
+ /// an abandoned platform callback may still enter it. Mobile shims
240
+ /// use the companion C ABI result to preserve their callback context
241
+ /// under the same condition.
242
+ pub fn destroy(self: *Self) bool {
176
243
  host.disableAutomation(self);
177
244
  self.render_memo.deinit();
178
245
  self.ui.deinit();
@@ -180,9 +247,15 @@ pub fn UiAppHost(comptime AppDef: type) type {
180
247
  // its heap-owned registrations (registered canvas font
181
248
  // bytes) before the host storage goes.
182
249
  self.embedded.deinit();
250
+ if (comptime record_store_enabled) {
251
+ if (self.record_store_open) self.record_store.deinit();
252
+ }
253
+ if (comptime relational_store_enabled) {
254
+ if (self.relational_store_open) self.relational_store.deinit();
255
+ }
183
256
  // The embedded null platform lives inside `self`, so freeing
184
257
  // `self` IS this path's platform destruction — and an
185
- // abandoned channel wake call may still enter that platform
258
+ // abandoned platform call may still enter that platform
186
259
  // at any later time (see
187
260
  // `PlatformServices.note_channel_wake_abandoned_fn`; the
188
261
  // null platform's own enqueue-only wake never triggers it,
@@ -190,17 +263,58 @@ pub fn UiAppHost(comptime AppDef: type) type {
190
263
  // like every first-party destroy path: skip the free and
191
264
  // leak the host storage, process-lived, with one loud line.
192
265
  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;
266
+ 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", .{});
267
+ return true;
195
268
  }
196
269
  std.heap.page_allocator.destroy(self);
270
+ return false;
197
271
  }
198
272
 
199
273
  pub fn start(self: *Self) anyerror!void {
274
+ if (comptime record_store_enabled) {
275
+ if (!self.record_store_open) return error.StoreDataDirUnavailable;
276
+ }
277
+ if (comptime relational_store_enabled) {
278
+ if (!self.relational_store_open) return error.SqliteDataDirUnavailable;
279
+ }
200
280
  self.started = true;
201
281
  try self.embedded.start();
202
282
  }
203
283
 
284
+ /// Install the OS-owned app-data directory before start. iOS passes
285
+ /// Library/Application Support and Android passes files/, exactly the
286
+ /// `.data` directories resolved by `app_dirs` on those platforms.
287
+ pub fn setDataRoot(self: *Self, data_root: []const u8) !void {
288
+ if (comptime !record_store_enabled and !relational_store_enabled) return;
289
+ if (self.started) return error.AppAlreadyStarted;
290
+ if (data_root.len == 0 or data_root.len > max_mobile_asset_root_bytes) return error.InvalidStoreDataDir;
291
+ if (comptime record_store_enabled) {
292
+ if (self.record_store_open) {
293
+ self.record_store.deinit();
294
+ self.record_store_open = false;
295
+ self.embedded.runtime.options.record_store = null;
296
+ }
297
+ self.record_store = try runtime.RecordStore.open(std.heap.page_allocator, data_root);
298
+ self.record_store_open = true;
299
+ self.embedded.runtime.options.record_store = self.record_store.binding();
300
+ }
301
+ if (comptime relational_store_enabled) {
302
+ if (self.relational_store_open) {
303
+ self.relational_store.deinit();
304
+ self.relational_store_open = false;
305
+ self.embedded.runtime.options.relational_store = null;
306
+ }
307
+ const opened = try runtime.RelationalStore.openMigrated(std.heap.page_allocator, data_root, relational_migrations);
308
+ self.relational_store = switch (opened.outcome) {
309
+ .ok => opened.database.?,
310
+ .migrate_failed => return error.SqliteMigrationFailed,
311
+ .version_unknown => return error.SqliteVersionUnknown,
312
+ };
313
+ self.relational_store_open = true;
314
+ self.embedded.runtime.options.relational_store = self.relational_store.binding();
315
+ }
316
+ }
317
+
204
318
  /// Host-pumped frame step: the shim's display-link (or test) tick.
205
319
  /// Synthesizes the `gpu_surface_frame` event a platform loop would
206
320
  /// 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);
@@ -52,6 +52,18 @@
52
52
  #define NATIVE_SDK_LOGI(...) __android_log_print(ANDROID_LOG_INFO, NATIVE_SDK_LOG_TAG, __VA_ARGS__)
53
53
  #define NATIVE_SDK_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, NATIVE_SDK_LOG_TAG, __VA_ARGS__)
54
54
 
55
+ // Immutable per-registration state for credential worker callbacks. Unlike
56
+ // presentation/audio/image upcalls, credential calls run off the activity
57
+ // thread and teardown may deliberately detach a blocked worker. The runtime
58
+ // therefore reports whether this context must be preserved process-lived.
59
+ typedef struct native_sdk_credential_context {
60
+ JavaVM *vm;
61
+ jobject activity;
62
+ jmethodID set_method;
63
+ jmethodID get_method;
64
+ jmethodID delete_method;
65
+ } native_sdk_credential_context_t;
66
+
55
67
  // One activity drives one embed app per process (the manifest declares a
56
68
  // single launcher activity), so the host-side presentation, measure, and
57
69
  // audio state lives in a single static bundle.
@@ -80,6 +92,7 @@ static struct {
80
92
  jmethodID audio_stop_method;
81
93
  jmethodID audio_seek_method;
82
94
  jmethodID audio_set_volume_method;
95
+ native_sdk_credential_context_t *credential_context;
83
96
  // Image decode upcall target, registered by nativeSetImageService: the
84
97
  // activity owns the platform codec (BitmapFactory on the Java side),
85
98
  // and the embed image service callback below calls back into it.
@@ -104,7 +117,9 @@ JNIEXPORT jlong JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeCreate
104
117
 
105
118
  JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeDestroy(JNIEnv *env, jobject self, jlong app) {
106
119
  (void)self;
107
- native_sdk_app_destroy((void *)app);
120
+ native_sdk_credential_context_t *credential_context = host_state.credential_context;
121
+ host_state.credential_context = NULL;
122
+ const int preserve_callback_context = native_sdk_app_destroy_with_status((void *)app);
108
123
  if (host_state.window) {
109
124
  ANativeWindow_release(host_state.window);
110
125
  host_state.window = NULL;
@@ -128,6 +143,12 @@ JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeDestroy
128
143
  host_state.audio_seek_method = NULL;
129
144
  host_state.audio_set_volume_method = NULL;
130
145
  }
146
+ if (credential_context && !preserve_callback_context) {
147
+ if (credential_context->activity) (*env)->DeleteGlobalRef(env, credential_context->activity);
148
+ free(credential_context);
149
+ } else if (credential_context) {
150
+ NATIVE_SDK_LOGE("credential callback context preserved after an abandoned platform call");
151
+ }
131
152
  if (host_state.image_activity) {
132
153
  (*env)->DeleteGlobalRef(env, host_state.image_activity);
133
154
  host_state.image_activity = NULL;
@@ -403,6 +424,16 @@ JNIEXPORT jboolean JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeScr
403
424
 
404
425
  // ------------------------------------------------------- assets/automation
405
426
 
427
+ JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeSetDataRoot(JNIEnv *env, jobject self, jlong app, jstring path) {
428
+ (void)self;
429
+ if (!path) return;
430
+ const char *chars = (*env)->GetStringUTFChars(env, path, NULL);
431
+ if (!chars) return;
432
+ native_sdk_app_set_data_root((void *)app, chars, strlen(chars));
433
+ host_log_error((void *)app, "data_root");
434
+ (*env)->ReleaseStringUTFChars(env, path, chars);
435
+ }
436
+
406
437
  JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeSetAssetRoot(JNIEnv *env, jobject self, jlong app, jstring path) {
407
438
  (void)self;
408
439
  if (!path) return;
@@ -605,6 +636,156 @@ JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeSetAudi
605
636
  NATIVE_SDK_LOGI("audio service registered");
606
637
  }
607
638
 
639
+ // ----------------------------------------------------------- credentials
640
+
641
+ static JNIEnv *host_credential_env(native_sdk_credential_context_t *credential, int *attached) {
642
+ *attached = 0;
643
+ if (!credential || !credential->vm || !credential->activity) return NULL;
644
+ JNIEnv *env = NULL;
645
+ jint state = (*credential->vm)->GetEnv(credential->vm, (void **)&env, JNI_VERSION_1_6);
646
+ if (state == JNI_OK) return env;
647
+ if (state != JNI_EDETACHED ||
648
+ (*credential->vm)->AttachCurrentThread(credential->vm, &env, NULL) != JNI_OK) return NULL;
649
+ *attached = 1;
650
+ return env;
651
+ }
652
+
653
+ static void host_credential_done(native_sdk_credential_context_t *credential, int attached) {
654
+ if (attached) (*credential->vm)->DetachCurrentThread(credential->vm);
655
+ }
656
+
657
+ static int host_credential_set(void *context,
658
+ const char *service, uintptr_t service_len,
659
+ const char *account, uintptr_t account_len,
660
+ const uint8_t *secret, uintptr_t secret_len) {
661
+ native_sdk_credential_context_t *credential = (native_sdk_credential_context_t *)context;
662
+ int attached = 0;
663
+ JNIEnv *env = host_credential_env(credential, &attached);
664
+ if (!env) return -5;
665
+ jbyteArray service_bytes = host_audio_bytes(env, service, service_len);
666
+ jbyteArray account_bytes = host_audio_bytes(env, account, account_len);
667
+ jbyteArray secret_bytes = host_audio_bytes(env, (const char *)secret, secret_len);
668
+ if (!service_bytes || !account_bytes || !secret_bytes) {
669
+ if (service_bytes) (*env)->DeleteLocalRef(env, service_bytes);
670
+ if (account_bytes) (*env)->DeleteLocalRef(env, account_bytes);
671
+ if (secret_bytes) (*env)->DeleteLocalRef(env, secret_bytes);
672
+ host_credential_done(credential, attached);
673
+ return -5;
674
+ }
675
+ jint result = (*env)->CallIntMethod(env, credential->activity,
676
+ credential->set_method,
677
+ service_bytes, account_bytes, secret_bytes);
678
+ (*env)->DeleteLocalRef(env, secret_bytes);
679
+ (*env)->DeleteLocalRef(env, account_bytes);
680
+ (*env)->DeleteLocalRef(env, service_bytes);
681
+ if ((*env)->ExceptionCheck(env)) {
682
+ (*env)->ExceptionClear(env);
683
+ result = -5;
684
+ }
685
+ host_credential_done(credential, attached);
686
+ return (int)result;
687
+ }
688
+
689
+ static int64_t host_credential_get(void *context,
690
+ const char *service, uintptr_t service_len,
691
+ const char *account, uintptr_t account_len,
692
+ uint8_t *output, uintptr_t output_len) {
693
+ native_sdk_credential_context_t *credential = (native_sdk_credential_context_t *)context;
694
+ int attached = 0;
695
+ JNIEnv *env = host_credential_env(credential, &attached);
696
+ if (!env) return -5;
697
+ jbyteArray service_bytes = host_audio_bytes(env, service, service_len);
698
+ jbyteArray account_bytes = host_audio_bytes(env, account, account_len);
699
+ jobject output_buffer = (*env)->NewDirectByteBuffer(env, output, (jlong)output_len);
700
+ if (!service_bytes || !account_bytes || !output_buffer) {
701
+ if (service_bytes) (*env)->DeleteLocalRef(env, service_bytes);
702
+ if (account_bytes) (*env)->DeleteLocalRef(env, account_bytes);
703
+ if (output_buffer) (*env)->DeleteLocalRef(env, output_buffer);
704
+ host_credential_done(credential, attached);
705
+ return -5;
706
+ }
707
+ jlong result = (*env)->CallLongMethod(env, credential->activity,
708
+ credential->get_method,
709
+ service_bytes, account_bytes, output_buffer);
710
+ (*env)->DeleteLocalRef(env, output_buffer);
711
+ (*env)->DeleteLocalRef(env, account_bytes);
712
+ (*env)->DeleteLocalRef(env, service_bytes);
713
+ if ((*env)->ExceptionCheck(env)) {
714
+ (*env)->ExceptionClear(env);
715
+ result = -5;
716
+ }
717
+ host_credential_done(credential, attached);
718
+ return (int64_t)result;
719
+ }
720
+
721
+ static int host_credential_delete(void *context,
722
+ const char *service, uintptr_t service_len,
723
+ const char *account, uintptr_t account_len) {
724
+ native_sdk_credential_context_t *credential = (native_sdk_credential_context_t *)context;
725
+ int attached = 0;
726
+ JNIEnv *env = host_credential_env(credential, &attached);
727
+ if (!env) return -5;
728
+ jbyteArray service_bytes = host_audio_bytes(env, service, service_len);
729
+ jbyteArray account_bytes = host_audio_bytes(env, account, account_len);
730
+ if (!service_bytes || !account_bytes) {
731
+ if (service_bytes) (*env)->DeleteLocalRef(env, service_bytes);
732
+ if (account_bytes) (*env)->DeleteLocalRef(env, account_bytes);
733
+ host_credential_done(credential, attached);
734
+ return -5;
735
+ }
736
+ jint result = (*env)->CallIntMethod(env, credential->activity,
737
+ credential->delete_method,
738
+ service_bytes, account_bytes);
739
+ (*env)->DeleteLocalRef(env, account_bytes);
740
+ (*env)->DeleteLocalRef(env, service_bytes);
741
+ if ((*env)->ExceptionCheck(env)) {
742
+ (*env)->ExceptionClear(env);
743
+ result = -5;
744
+ }
745
+ host_credential_done(credential, attached);
746
+ return (int)result;
747
+ }
748
+
749
+ JNIEXPORT void JNICALL Java_dev_native_1sdk_host_NativeSdkActivity_nativeSetCredentialService(JNIEnv *env, jobject self, jlong app) {
750
+ native_sdk_credential_context_t *credential = calloc(1, sizeof(*credential));
751
+ if (!credential) return;
752
+ if ((*env)->GetJavaVM(env, &credential->vm) != JNI_OK) {
753
+ free(credential);
754
+ return;
755
+ }
756
+ credential->activity = (*env)->NewGlobalRef(env, self);
757
+ jclass cls = (*env)->GetObjectClass(env, self);
758
+ credential->set_method = (*env)->GetMethodID(env, cls, "credentialSet", "([B[B[B)I");
759
+ credential->get_method = (*env)->GetMethodID(env, cls, "credentialGet", "([B[BLjava/nio/ByteBuffer;)J");
760
+ credential->delete_method = (*env)->GetMethodID(env, cls, "credentialDelete", "([B[B)I");
761
+ (*env)->DeleteLocalRef(env, cls);
762
+ if (!credential->activity || !credential->set_method ||
763
+ !credential->get_method || !credential->delete_method) {
764
+ NATIVE_SDK_LOGE("credential_service registration failed");
765
+ if (credential->activity) (*env)->DeleteGlobalRef(env, credential->activity);
766
+ free(credential);
767
+ return;
768
+ }
769
+ static const native_sdk_credential_service_t service = {
770
+ .set = host_credential_set,
771
+ .get = host_credential_get,
772
+ .delete = host_credential_delete,
773
+ };
774
+ if (native_sdk_app_set_credential_service((void *)app, &service, credential) == 0) {
775
+ (*env)->DeleteGlobalRef(env, credential->activity);
776
+ free(credential);
777
+ host_log_error((void *)app, "credential_service");
778
+ return;
779
+ }
780
+ if (host_state.credential_context) {
781
+ (*env)->DeleteGlobalRef(env, host_state.credential_context->activity);
782
+ free(host_state.credential_context);
783
+ }
784
+ host_state.credential_context = credential;
785
+ host_log_error((void *)app, "credential_service");
786
+ NATIVE_SDK_LOGI("credential service registered");
787
+ }
788
+
608
789
  // ------------------------------------------------------------------ images
609
790
  //
610
791
  // The embed image-decode service, bridged to the activity's Java-side
@@ -156,6 +156,10 @@ typedef struct native_sdk_gpu_frame_state {
156
156
 
157
157
  void *native_sdk_app_create(void);
158
158
  void native_sdk_app_destroy(void *app);
159
+ // Returns 1 when teardown preserved the app because a detached platform
160
+ // callback may still be executing; the shim must preserve that callback's
161
+ // context too. Returns 0 after ordinary complete destruction.
162
+ int native_sdk_app_destroy_with_status(void *app);
159
163
  void native_sdk_app_start(void *app);
160
164
  void native_sdk_app_activate(void *app);
161
165
  void native_sdk_app_deactivate(void *app);
@@ -208,6 +212,18 @@ typedef struct native_sdk_audio_service {
208
212
  int (*set_volume)(void *context, double volume);
209
213
  } native_sdk_audio_service_t;
210
214
  int native_sdk_app_set_audio_service(void *app, const native_sdk_audio_service_t *service, void *context);
215
+ // Secure credential service. Result codes preserve the core effect's closed
216
+ // outcomes: set returns 1 success, -2 locked, -3 denied, 0 I/O failure;
217
+ // get returns a non-negative byte length, -1 miss, -2 locked, -3 denied,
218
+ // -4 output too small, -5 I/O failure; delete returns 1 deleted, 0 miss,
219
+ // -2 locked, -3 denied, -5 I/O failure.
220
+ typedef struct native_sdk_credential_service {
221
+ int (*set)(void *context, const char *service, uintptr_t service_len, const char *account, uintptr_t account_len, const uint8_t *secret, uintptr_t secret_len);
222
+ int64_t (*get)(void *context, const char *service, uintptr_t service_len, const char *account, uintptr_t account_len, uint8_t *output, uintptr_t output_len);
223
+ int (*delete)(void *context, const char *service, uintptr_t service_len, const char *account, uintptr_t account_len);
224
+ } native_sdk_credential_service_t;
225
+ int native_sdk_app_set_credential_service(void *app, const native_sdk_credential_service_t *service, void *context);
226
+
211
227
  // One audio player report (kind ordinals above; position/duration in ms).
212
228
  // Call between runtime entry points on the loop thread, never from inside
213
229
  // an audio service callback.
@@ -227,6 +243,7 @@ typedef struct native_sdk_image_service {
227
243
  } native_sdk_image_service_t;
228
244
  int native_sdk_app_set_image_service(void *app, const native_sdk_image_service_t *service, void *context);
229
245
  int native_sdk_app_set_automation_dir(void *app, const char *path, uintptr_t len);
246
+ int native_sdk_app_set_data_root(void *app, const char *path, uintptr_t len);
230
247
  void native_sdk_app_set_asset_root(void *app, const char *path, uintptr_t len);
231
248
  uintptr_t native_sdk_app_widget_semantics_count(void *app);
232
249
  int native_sdk_app_widget_semantics_at(void *app, uintptr_t index, native_sdk_widget_semantics_t *out);