@mikrojs/native 0.21.1-next.20260928214050 → 0.23.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 (52) hide show
  1. package/CMakeLists.txt +21 -0
  2. package/dist/runtime/result/native-result.node-shim.d.ts +2 -0
  3. package/dist/runtime/result/native-result.node-shim.d.ts.map +1 -1
  4. package/dist/runtime/result/native-result.node-shim.js +57 -0
  5. package/dist/runtime/result/native-result.node-shim.js.map +1 -1
  6. package/dist/runtime/result/types.d.ts +33 -0
  7. package/dist/runtime/result/types.d.ts.map +1 -1
  8. package/include/mikrojs/app_store.h +16 -0
  9. package/include/mikrojs/ble_port.h +50 -0
  10. package/include/mikrojs/build_install.h +36 -0
  11. package/include/mikrojs/device_store.h +84 -0
  12. package/include/mikrojs/http_native.h +52 -0
  13. package/include/mikrojs/mikrojs.h +19 -9
  14. package/include/mikrojs/ota.h +75 -0
  15. package/include/mikrojs/ota_env.h +1 -1
  16. package/include/mikrojs/platform.h +35 -0
  17. package/include/mikrojs/private.h +13 -3
  18. package/include/mikrojs/utils.h +17 -7
  19. package/package.json +4 -4
  20. package/prebuilds/darwin-arm64/mikrojs.napi.node +0 -0
  21. package/prebuilds/linux-arm64/mikrojs.napi.node +0 -0
  22. package/prebuilds/linux-x64/mikrojs.napi.node +0 -0
  23. package/runtime/http/server-impl.ts +5 -60
  24. package/runtime/http/server.ts +0 -1
  25. package/runtime/internal.d.ts +2 -0
  26. package/runtime/modules.json +1 -1
  27. package/runtime/result/native-result.node-shim.ts +60 -0
  28. package/runtime/result/result.ts +1 -1
  29. package/runtime/result/types.ts +61 -0
  30. package/runtime/sys/sys.ts +1 -2
  31. package/runtime/sys/types.ts +5 -2
  32. package/src/mik_app_store.cpp +32 -0
  33. package/src/mik_ble.cpp +1573 -0
  34. package/src/mik_build_install.cpp +785 -0
  35. package/src/mik_config.cpp +330 -0
  36. package/src/mik_console.cpp +15 -24
  37. package/src/mik_deploy.cpp +759 -0
  38. package/src/mik_ota.cpp +1403 -0
  39. package/src/mik_ota_client_module.cpp +1142 -0
  40. package/src/mik_ota_env.cpp +318 -0
  41. package/src/mik_repl.cpp +15 -6
  42. package/src/mik_result.cpp +159 -0
  43. package/src/mik_sys.cpp +57 -52
  44. package/src/mik_test.cpp +1334 -0
  45. package/src/mik_test_supervisor.cpp +151 -0
  46. package/src/mik_udp.cpp +4 -1
  47. package/src/mik_watchdog.cpp +4 -5
  48. package/src/mik_wifi_client.cpp +1 -2
  49. package/src/mikrojs.cpp +15 -6
  50. package/src/modules.cpp +2 -1
  51. package/src/utils.cpp +1 -2
  52. package/runtime/test/test.ts +0 -686
@@ -0,0 +1,1142 @@
1
+ /**
2
+ * native:mikro/ota_client — the JS surface of the native OTA client.
3
+ *
4
+ * Thin by design: the state machine lives in the portable library
5
+ * (mikrojs/ota_client.h) where host tests drive it. This file does three things
6
+ * the machine cannot do for itself — marshal options and results across the JS
7
+ * boundary, settle a promise when a round finishes, and re-enter JS for the
8
+ * app's `beforeCheck` hook, which is the one place JS runs inside a round.
9
+ */
10
+
11
+ #include <memory>
12
+ #include <vector>
13
+
14
+ #include "mikrojs/cbor_helpers.h"
15
+ #include "mikrojs/http_native.h"
16
+ #include "mikrojs/ota.h"
17
+ #include "mikrojs/ota_client.h"
18
+ #include "mikrojs/ota_config.h"
19
+ #include "mikrojs/ota_js_hooks.h"
20
+ #include "mikrojs/ota_policy.h"
21
+ #include "mikrojs/ota_slots.h"
22
+ #include "mikrojs/private.h"
23
+ #include "mikrojs/utils.h"
24
+
25
+ using mikrojs::MIKOtaCheckOptions;
26
+ using mikrojs::MIKOtaCheckResult;
27
+ using mikrojs::MIKOtaCheckStatus;
28
+ using mikrojs::MIKOtaClient;
29
+ using mikrojs::MIKOtaConfigReader;
30
+ using mikrojs::MIKOtaConfigWrite;
31
+ using mikrojs::MIKOtaJsHooks;
32
+ using mikrojs::MIKOtaApplyOutcome;
33
+ using mikrojs::MIKOtaApplySession;
34
+ using mikrojs::MIKOtaDeclineRecord;
35
+ using mikrojs::MIKOtaError;
36
+ using mikrojs::MIKOtaInstallOptions;
37
+ using mikrojs::MIKOtaOffer;
38
+ using mikrojs::MIKOtaHookState;
39
+ using mikrojs::MIKOtaRoundHooks;
40
+ using mikrojs::MIKOtaWatchOptions;
41
+
42
+ #define MIK_OTA_CLIENT_TAG "native:mikro/ota_client"
43
+
44
+ namespace {
45
+
46
+ /* One in-flight check() and the promise waiting on it. */
47
+ struct PendingCheck {
48
+ MIKPromise promise;
49
+ bool settled = false;
50
+ };
51
+
52
+ /* One apply attempt, held open while the app's download callback runs. Staging
53
+ * is a single native session, so there is at most one. */
54
+ struct PendingApply {
55
+ MIKOtaApplySession session;
56
+ MIKPromise promise;
57
+ MIKOtaInstallOptions options;
58
+ bool active = false;
59
+ };
60
+
61
+ struct MIKOtaClientState {
62
+ JSContext* ctx = nullptr;
63
+ const MIKOtaEnv* env = nullptr;
64
+ PendingApply apply;
65
+ std::unique_ptr<MIKOtaConfigReader> config;
66
+ std::unique_ptr<MIKOtaClient> client;
67
+ std::unique_ptr<MIKOtaJsHooks> hooks;
68
+ /* The watcher's onConfig, held for the life of the watch. */
69
+ JSValue on_config = JS_UNDEFINED;
70
+ std::vector<std::unique_ptr<PendingCheck>> pending;
71
+ bool watching = false;
72
+ /* The reconcile diagnostic, held for report() the way the built-in client
73
+ * holds it for its own rounds: env->reconcile is read-once, so this is the
74
+ * only copy left after ota.reconcile() ran. settle() marks it delivered. */
75
+ bool has_last_install = false;
76
+ MIKOtaDiagnostic last_install = {};
77
+ /* Set by report() when the stored decline made it into the body, so settle()
78
+ * clears only a record the registry has seen. A read that failed leaves the
79
+ * record for the next round. */
80
+ bool decline_reported = false;
81
+ };
82
+
83
+ int mik__ota_client_slot = -1;
84
+
85
+ inline MIKOtaClientState*& mik__ota_client_st(MIKRuntime* rt) {
86
+ return reinterpret_cast<MIKOtaClientState*&>(rt->module_data[mik__ota_client_slot]);
87
+ }
88
+
89
+ // ── result marshalling ───────────────────────────────────────────────────────
90
+
91
+ void set_error(JSContext* ctx, JSValue target, const mikrojs::MIKOtaError& error,
92
+ int http_status) {
93
+ JSValue obj = JS_NewObject(ctx);
94
+ JS_SetPropertyStr(ctx, obj, "name",
95
+ JS_NewString(ctx, error.name.empty() ? "Network" : error.name.c_str()));
96
+ if (!error.kind.empty()) {
97
+ JS_SetPropertyStr(ctx, obj, "kind", JS_NewString(ctx, error.kind.c_str()));
98
+ }
99
+ if (!error.message.empty()) {
100
+ JS_SetPropertyStr(ctx, obj, "message", JS_NewString(ctx, error.message.c_str()));
101
+ }
102
+ if (error.name == "Status" && http_status != 0) {
103
+ JS_SetPropertyStr(ctx, obj, "status", JS_NewInt32(ctx, http_status));
104
+ }
105
+ JS_SetPropertyStr(ctx, target, "error", obj);
106
+ }
107
+
108
+ JSValue result_to_js(JSContext* ctx, const MIKOtaCheckResult& result) {
109
+ JSValue obj = JS_NewObject(ctx);
110
+ JS_SetPropertyStr(ctx, obj, "status",
111
+ JS_NewString(ctx, mikrojs::mik__ota_check_status_to_str(result.status)));
112
+ switch (result.status) {
113
+ case MIKOtaCheckStatus::kStaged: {
114
+ JSValue offer = JS_NewObject(ctx);
115
+ JS_SetPropertyStr(ctx, offer, "url", JS_NewString(ctx, result.offer.url.c_str()));
116
+ JS_SetPropertyStr(ctx, offer, "checksum",
117
+ JS_NewString(ctx, result.offer.checksum.c_str()));
118
+ JS_SetPropertyStr(ctx, offer, "size", JS_NewInt64(ctx, (int64_t)result.offer.size));
119
+ JS_SetPropertyStr(ctx, obj, "offer", offer);
120
+ break;
121
+ }
122
+ case MIKOtaCheckStatus::kUpToDate:
123
+ /* Omitted rather than false when nothing changed, matching the JS
124
+ * client: the key's presence is the signal. */
125
+ if (result.config_updated) {
126
+ JS_SetPropertyStr(ctx, obj, "configUpdated", JS_TRUE);
127
+ }
128
+ break;
129
+ case MIKOtaCheckStatus::kNotStaged:
130
+ JS_SetPropertyStr(
131
+ ctx, obj, "reason",
132
+ JS_NewString(ctx, mikrojs::mik__ota_decline_reason_to_str(result.decline_reason)));
133
+ if (!result.error.name.empty()) set_error(ctx, obj, result.error, result.http_status);
134
+ break;
135
+ case MIKOtaCheckStatus::kFailed:
136
+ set_error(ctx, obj, result.error, result.http_status);
137
+ break;
138
+ case MIKOtaCheckStatus::kUnauthorized:
139
+ case MIKOtaCheckStatus::kNotEnrolled:
140
+ break;
141
+ }
142
+ return obj;
143
+ }
144
+
145
+ // ── option marshalling ───────────────────────────────────────────────────────
146
+
147
+ uint32_t opt_u32(JSContext* ctx, JSValue options, const char* key, uint32_t fallback) {
148
+ JSValue value = JS_GetPropertyStr(ctx, options, key);
149
+ uint32_t out = fallback;
150
+ if (JS_IsNumber(value)) {
151
+ int64_t raw = 0;
152
+ if (JS_ToInt64(ctx, &raw, value) == 0 && raw >= 0) out = (uint32_t)raw;
153
+ }
154
+ JS_FreeValue(ctx, value);
155
+ return out;
156
+ }
157
+
158
+ bool opt_bool(JSContext* ctx, JSValue options, const char* key, bool fallback) {
159
+ JSValue value = JS_GetPropertyStr(ctx, options, key);
160
+ bool out = JS_IsUndefined(value) ? fallback : JS_ToBool(ctx, value);
161
+ JS_FreeValue(ctx, value);
162
+ return out;
163
+ }
164
+
165
+ void read_check_options(JSContext* ctx, JSValue options, MIKOtaCheckOptions* out) {
166
+ if (!JS_IsObject(options)) return;
167
+ out->checkin_timeout_ms = opt_u32(ctx, options, "checkinTimeoutMs", out->checkin_timeout_ms);
168
+ out->download_timeout_ms = opt_u32(ctx, options, "downloadTimeoutMs", out->download_timeout_ms);
169
+ out->require_confirm = opt_bool(ctx, options, "requireConfirm", out->require_confirm);
170
+ out->trial_boots = (int)opt_u32(ctx, options, "trialBoots", (uint32_t)out->trial_boots);
171
+ }
172
+
173
+ // ── JS functions ─────────────────────────────────────────────────────────────
174
+
175
+ JSValue mik__ota_client_check(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
176
+ (void)this_val;
177
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
178
+ CHECK_NOT_NULL(mik_rt);
179
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
180
+ CHECK_NOT_NULL(state);
181
+
182
+ MIKOtaCheckOptions options;
183
+ if (argc > 0) read_check_options(ctx, argv[0], &options);
184
+
185
+ auto pending = std::make_unique<PendingCheck>();
186
+ JSValue promise = MIK_InitPromise(ctx, &pending->promise);
187
+ if (JS_IsException(promise)) return JS_EXCEPTION;
188
+
189
+ PendingCheck* slot = pending.get();
190
+ state->pending.push_back(std::move(pending));
191
+
192
+ state->client->Check(options, [state, slot](const MIKOtaCheckResult& result) {
193
+ JSValue value = result_to_js(state->ctx, result);
194
+ MIK_ResolvePromise(state->ctx, &slot->promise, 1, &value);
195
+ slot->settled = true;
196
+ });
197
+
198
+ /* A not-enrolled device settles inline, before Check() returns. Reap it here
199
+ * so the vector does not grow with every call on such a device. */
200
+ for (size_t i = state->pending.size(); i > 0; i--) {
201
+ if (state->pending[i - 1]->settled) state->pending.erase(state->pending.begin() + (i - 1));
202
+ }
203
+ return promise;
204
+ }
205
+
206
+ /* config() -> the effective config, or undefined. */
207
+ JSValue mik__ota_client_config(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
208
+ (void)this_val;
209
+ (void)argc;
210
+ (void)argv;
211
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
212
+ CHECK_NOT_NULL(mik_rt);
213
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
214
+ CHECK_NOT_NULL(state);
215
+ return state->config->Read(ctx);
216
+ }
217
+
218
+ JSValue mik__ota_client_stop(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
219
+ (void)this_val;
220
+ (void)argc;
221
+ (void)argv;
222
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
223
+ CHECK_NOT_NULL(mik_rt);
224
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
225
+ if (state && state->client) state->client->StopWatch();
226
+ return JS_UNDEFINED;
227
+ }
228
+
229
+ JSValue mik__ota_client_set_interval(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
230
+ (void)this_val;
231
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
232
+ CHECK_NOT_NULL(mik_rt);
233
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
234
+ if (!state || !state->client) return JS_UNDEFINED;
235
+ int64_t interval = 0;
236
+ if (argc < 1 || JS_ToInt64(ctx, &interval, argv[0]) < 0 || interval < 0) {
237
+ return JS_ThrowTypeError(ctx, "setCheckinInterval(ms) needs a non-negative number");
238
+ }
239
+ state->client->SetCheckinInterval(static_cast<uint32_t>(interval));
240
+ return JS_UNDEFINED;
241
+ }
242
+
243
+ JSValue mik__ota_client_watch(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
244
+ (void)this_val;
245
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
246
+ CHECK_NOT_NULL(mik_rt);
247
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
248
+ CHECK_NOT_NULL(state);
249
+
250
+ /* One watcher per runtime, and never a swap mid-round: replacing the hooks
251
+ * would pull them out from under the round that is still running them, and
252
+ * stop() only takes effect once that round finishes. */
253
+ if (state->client && state->client->watching()) {
254
+ return JS_ThrowTypeError(
255
+ ctx, "ota.watch() is already running; call stop() on its watcher first");
256
+ }
257
+ if (state->client && state->client->state() != mikrojs::MIKOtaClientState::kIdle) {
258
+ return JS_ThrowTypeError(
259
+ ctx, "ota.watch(): the previous round is still finishing; try again shortly");
260
+ }
261
+
262
+ MIKOtaWatchOptions options;
263
+ if (argc > 0 && JS_IsObject(argv[0])) {
264
+ read_check_options(ctx, argv[0], &options);
265
+ options.checkin_interval_ms =
266
+ opt_u32(ctx, argv[0], "checkinIntervalMs", options.checkin_interval_ms);
267
+ options.initial_delay_ms =
268
+ opt_u32(ctx, argv[0], "initialDelayMs", options.initial_delay_ms);
269
+ options.retry_after_failure_ms =
270
+ opt_u32(ctx, argv[0], "retryAfterFailureMs", options.retry_after_failure_ms);
271
+ options.jitter = opt_bool(ctx, argv[0], "jitter", options.jitter);
272
+
273
+ JSValue before_check = JS_GetPropertyStr(ctx, argv[0], "beforeCheck");
274
+ if (JS_IsFunction(ctx, before_check)) {
275
+ state->hooks = std::make_unique<MIKOtaJsHooks>(ctx, before_check);
276
+ options.hooks = state->hooks.get();
277
+ } else {
278
+ JS_FreeValue(ctx, before_check);
279
+ }
280
+
281
+ JS_FreeValue(ctx, state->on_config);
282
+ state->on_config = JS_GetPropertyStr(ctx, argv[0], "onConfig");
283
+ if (JS_IsFunction(ctx, state->on_config)) {
284
+ /* Only when a round actually changed the stored document. A staged
285
+ * release's config applies at its trial boot, not now, so it is not
286
+ * a change the running app can read yet. */
287
+ options.on_round = [state](const MIKOtaCheckResult& result) {
288
+ if (!result.config_updated) return;
289
+ JSValue config = state->config->Read(state->ctx);
290
+ if (JS_IsException(config)) {
291
+ /* Nothing to hand over: a build with no readable manifest
292
+ * and no stored document has no config to report. */
293
+ JS_FreeValue(state->ctx, JS_GetException(state->ctx));
294
+ return;
295
+ }
296
+ JSValue ignored =
297
+ JS_Call(state->ctx, state->on_config, JS_UNDEFINED, 1, &config);
298
+ if (JS_IsException(ignored)) mik_dump_error(state->ctx);
299
+ JS_FreeValue(state->ctx, ignored);
300
+ JS_FreeValue(state->ctx, config);
301
+ };
302
+ } else {
303
+ JS_FreeValue(ctx, state->on_config);
304
+ state->on_config = JS_UNDEFINED;
305
+ }
306
+ }
307
+
308
+ if (!state->client->Watch(options)) {
309
+ /* Enrollment is written over the cable, so nothing this boot does can
310
+ * make a later round succeed. Drop the hooks installed above and hand
311
+ * the app a typed error instead of an inert watcher. */
312
+ state->hooks.reset();
313
+ JS_FreeValue(ctx, state->on_config);
314
+ state->on_config = JS_UNDEFINED;
315
+ return mik__result_err_named(
316
+ ctx, "NotEnrolled",
317
+ "device not enrolled; run `mikro ota enroll` to enable OTA updates");
318
+ }
319
+ state->watching = true;
320
+
321
+ JSValue handle = JS_NewObject(ctx);
322
+ JS_SetPropertyStr(ctx, handle, "stop",
323
+ JS_NewCFunction(ctx, mik__ota_client_stop, "stop", 0));
324
+ JS_SetPropertyStr(
325
+ ctx, handle, "setCheckinInterval",
326
+ JS_NewCFunction(ctx, mik__ota_client_set_interval, "setCheckinInterval", 1));
327
+ return mik__result_ok(ctx, handle);
328
+ }
329
+
330
+ // ── the policy surface (mikro/ota) ──────────────────────────────────────────
331
+ // Everything below marshals for functions that already exist in the portable
332
+ // policy. The only one with any machinery of its own is applyOffer, which has to
333
+ // hand the app's download callback a staging session and wait for it.
334
+
335
+ JSValue error_to_js(JSContext* ctx, const MIKOtaError& error) {
336
+ JSValue obj = JS_NewObject(ctx);
337
+ JS_SetPropertyStr(ctx, obj, "name",
338
+ JS_NewString(ctx, error.name.empty() ? "InstallFailed" : error.name.c_str()));
339
+ if (!error.kind.empty()) {
340
+ JS_SetPropertyStr(ctx, obj, "kind", JS_NewString(ctx, error.kind.c_str()));
341
+ }
342
+ JS_SetPropertyStr(ctx, obj, "message", JS_NewString(ctx, error.message.c_str()));
343
+ return obj;
344
+ }
345
+
346
+ MIKOtaClientState* state_of(JSContext* ctx) {
347
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
348
+ if (!mik_rt) return nullptr;
349
+ return mik__ota_client_st(mik_rt);
350
+ }
351
+
352
+ JSValue kv_string_or_undefined(JSContext* ctx, const char* key) {
353
+ MIKOtaClientState* state = state_of(ctx);
354
+ if (!state || !state->env || !state->env->kv_get_str) return JS_UNDEFINED;
355
+ char buf[256] = {};
356
+ if (state->env->kv_get_str(state->env->opaque, key, buf, sizeof(buf)) != MIK_OTA_KV_OK ||
357
+ buf[0] == '\0') {
358
+ return JS_UNDEFINED;
359
+ }
360
+ return JS_NewString(ctx, buf);
361
+ }
362
+
363
+ /* reconcile() -> { installed?, reverted, lastInstall? } */
364
+ JSValue ota_reconcile(JSContext* ctx, JSValue, int, JSValue*) {
365
+ MIKOtaClientState* state = state_of(ctx);
366
+ CHECK_NOT_NULL(state);
367
+ MIKOtaReconcileOutcome outcome = mikrojs::mik__ota_policy_reconcile(state->env);
368
+ if (outcome.has_diagnostic) {
369
+ state->has_last_install = true;
370
+ state->last_install = outcome.diagnostic;
371
+ }
372
+
373
+ JSValue obj = JS_NewObject(ctx);
374
+ if (outcome.installed[0]) {
375
+ JS_SetPropertyStr(ctx, obj, "installed", JS_NewString(ctx, outcome.installed));
376
+ }
377
+ JS_SetPropertyStr(ctx, obj, "reverted", JS_NewBool(ctx, outcome.reverted));
378
+ if (outcome.has_diagnostic) {
379
+ JSValue diag = JS_NewObject(ctx);
380
+ JS_SetPropertyStr(ctx, diag, "reason", JS_NewString(ctx, outcome.diagnostic.reason));
381
+ if (outcome.diagnostic.detail[0]) {
382
+ JS_SetPropertyStr(ctx, diag, "detail", JS_NewString(ctx, outcome.diagnostic.detail));
383
+ }
384
+ JS_SetPropertyStr(ctx, obj, "lastInstall", diag);
385
+ }
386
+ return obj;
387
+ }
388
+
389
+ /* The running-build object, { checksum?, version?, trial }, for report(). */
390
+ JSValue ota_running(JSContext* ctx, JSValue, int, JSValue*) {
391
+ MIKOtaClientState* state = state_of(ctx);
392
+ CHECK_NOT_NULL(state);
393
+ MIKOtaRunningBuild running = mikrojs::mik__ota_policy_running(state->env);
394
+
395
+ JSValue obj = JS_NewObject(ctx);
396
+ if (running.checksum[0]) {
397
+ JS_SetPropertyStr(ctx, obj, "checksum", JS_NewString(ctx, running.checksum));
398
+ }
399
+ if (running.version[0]) {
400
+ JS_SetPropertyStr(ctx, obj, "version", JS_NewString(ctx, running.version));
401
+ }
402
+ JS_SetPropertyStr(ctx, obj, "trial", JS_NewBool(ctx, running.trial));
403
+ return obj;
404
+ }
405
+
406
+ JSValue ota_confirm(JSContext* ctx, JSValue, int, JSValue*) {
407
+ MIKOtaClientState* state = state_of(ctx);
408
+ CHECK_NOT_NULL(state);
409
+ mikrojs::mik__ota_policy_confirm(state->env);
410
+ return JS_UNDEFINED;
411
+ }
412
+
413
+ JSValue ota_revert(JSContext* ctx, JSValue, int, JSValue*) {
414
+ MIKOtaClientState* state = state_of(ctx);
415
+ CHECK_NOT_NULL(state);
416
+ MIKOtaError error;
417
+ if (!mikrojs::mik__ota_policy_revert(state->env, &error)) {
418
+ return mik__result_err_obj(ctx, error_to_js(ctx, error));
419
+ }
420
+ return mik__result_ok_void(ctx);
421
+ }
422
+
423
+ JSValue ota_bearer(JSContext* ctx, JSValue, int, JSValue*) {
424
+ return kv_string_or_undefined(ctx, "ota.updateKey");
425
+ }
426
+
427
+ JSValue ota_registry(JSContext* ctx, JSValue, int, JSValue*) {
428
+ return kv_string_or_undefined(ctx, "ota.registry");
429
+ }
430
+
431
+ JSValue offer_to_js(JSContext* ctx, const MIKOtaOffer& offer) {
432
+ JSValue obj = JS_NewObject(ctx);
433
+ JS_SetPropertyStr(ctx, obj, "url", JS_NewString(ctx, offer.url.c_str()));
434
+ JS_SetPropertyStr(ctx, obj, "checksum", JS_NewString(ctx, offer.checksum.c_str()));
435
+ JS_SetPropertyStr(ctx, obj, "size", JS_NewInt64(ctx, static_cast<int64_t>(offer.size)));
436
+ return obj;
437
+ }
438
+
439
+ // ── applyOffer ──────────────────────────────────────────────────────────────
440
+
441
+ /* The staging session, as the download callback sees it. Recovered from the
442
+ * module state rather than carried on the object: staging is a single native
443
+ * session, so there is only ever one to find. */
444
+ JSValue update_write(JSContext* ctx, JSValue, int argc, JSValue* argv) {
445
+ MIKOtaClientState* state = state_of(ctx);
446
+ if (!state || !state->apply.active || !state->apply.session.update) {
447
+ return mik__result_err_named(ctx, "StagingFailed", "no staging session");
448
+ }
449
+ size_t len = 0;
450
+ const uint8_t* data = argc > 0 ? JS_GetUint8Array(ctx, &len, argv[0]) : nullptr;
451
+ if (!data) {
452
+ JS_FreeValue(ctx, JS_GetException(ctx));
453
+ return mik__result_err_named(ctx, "StagingFull", "bytes not a Uint8Array");
454
+ }
455
+ MIKOtaError error;
456
+ if (!state->apply.session.update->write(data, len, &error)) {
457
+ return mik__result_err_obj(ctx, error_to_js(ctx, error));
458
+ }
459
+ return mik__result_ok_void(ctx);
460
+ }
461
+
462
+ JSValue update_finish(JSContext* ctx, JSValue, int argc, JSValue* argv) {
463
+ MIKOtaClientState* state = state_of(ctx);
464
+ if (!state || !state->apply.active || !state->apply.session.update) {
465
+ return mik__result_err_named(ctx, "StagingFailed", "no staging session");
466
+ }
467
+ MIKOtaInstallOptions options = state->apply.options;
468
+ if (argc > 0 && JS_IsObject(argv[0])) {
469
+ options.trial_boots =
470
+ (int)opt_u32(ctx, argv[0], "trialBoots", (uint32_t)options.trial_boots);
471
+ options.require_confirm = opt_bool(ctx, argv[0], "requireConfirm", options.require_confirm);
472
+ }
473
+ MIKOtaError error;
474
+ if (!state->apply.session.update->finish(options, &error)) {
475
+ return mik__result_err_obj(ctx, error_to_js(ctx, error));
476
+ }
477
+ return mik__result_ok_void(ctx);
478
+ }
479
+
480
+ JSValue update_abort(JSContext* ctx, JSValue, int, JSValue*) {
481
+ MIKOtaClientState* state = state_of(ctx);
482
+ if (state && state->apply.active && state->apply.session.update) {
483
+ state->apply.session.update->abort();
484
+ }
485
+ return JS_UNDEFINED;
486
+ }
487
+
488
+ JSValue make_update_object(JSContext* ctx, size_t resume_offset) {
489
+ JSValue update = JS_NewObject(ctx);
490
+ JS_SetPropertyStr(ctx, update, "resumeOffset",
491
+ JS_NewInt64(ctx, static_cast<int64_t>(resume_offset)));
492
+ JS_SetPropertyStr(ctx, update, "write", JS_NewCFunction(ctx, update_write, "write", 1));
493
+ JS_SetPropertyStr(ctx, update, "finish", JS_NewCFunction(ctx, update_finish, "finish", 1));
494
+ JS_SetPropertyStr(ctx, update, "abort", JS_NewCFunction(ctx, update_abort, "abort", 0));
495
+ return update;
496
+ }
497
+
498
+ /* True for the checksum shape the registry's checkin validation accepts. A
499
+ * lastDecline with any other checksum would 400 every future check-in — and
500
+ * permanently, since a failed round never settles and so never clears it. */
501
+ bool is_wire_checksum(const char* s) {
502
+ for (int i = 0; i < 64; i++) {
503
+ char c = s[i];
504
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;
505
+ }
506
+ return s[64] == '\0';
507
+ }
508
+
509
+ /* Record why an offered build was not taken, for the next report() to carry as
510
+ * lastDecline and a later settle() to mark delivered — the own-transport twin
511
+ * of the built-in client's NoteDecline, persisted because here the decline
512
+ * lands after the wake's check-in and must survive a deep sleep to make the
513
+ * next one. */
514
+ void note_decline(const MIKOtaEnv* env, const std::string& checksum, const char* reason,
515
+ const std::string& detail) {
516
+ if (!is_wire_checksum(checksum.c_str())) return;
517
+ MIKOtaDeclineRecord record;
518
+ snprintf(record.checksum, sizeof(record.checksum), "%s", checksum.c_str());
519
+ snprintf(record.reason, sizeof(record.reason), "%s", reason);
520
+ snprintf(record.detail, sizeof(record.detail), "%s", detail.c_str());
521
+ mikrojs::MIKOtaStore(env).SetDecline(record);
522
+ }
523
+
524
+ /* Close the attempt and settle applyOffer's promise. */
525
+ void settle_apply(JSContext* ctx, bool downloaded, const std::string& message) {
526
+ MIKOtaClientState* state = state_of(ctx);
527
+ if (!state || !state->apply.active) return;
528
+
529
+ std::string checksum = state->apply.session.checksum;
530
+ MIKOtaApplyOutcome outcome = MIKOtaApplyOutcome::kStaged;
531
+ MIKOtaError error;
532
+ bool ok = mikrojs::mik__ota_policy_apply_end(&state->apply.session, downloaded, message,
533
+ state->apply.options, &outcome, &error);
534
+ if (!ok) {
535
+ note_decline(state->env, checksum,
536
+ error.name == "DownloadFailed" ? "download-failed" : "install-failed",
537
+ error.message);
538
+ }
539
+ JSValue result = ok ? mik__result_ok(ctx, JS_NewString(ctx, mikrojs::mik__ota_outcome_to_str(
540
+ outcome)))
541
+ : mik__result_err_obj(ctx, error_to_js(ctx, error));
542
+ state->apply.active = false;
543
+ MIK_ResolvePromise(ctx, &state->apply.promise, 1, &result);
544
+ }
545
+
546
+ JSValue download_fulfilled(JSContext* ctx, JSValue, int argc, JSValue* argv) {
547
+ /* The callback's contract is Result<void, {message}>: a rejected download is
548
+ * transient, so the message is all that survives into DownloadFailed. */
549
+ bool downloaded = false;
550
+ std::string message = "download failed";
551
+ if (argc > 0 && JS_IsObject(argv[0])) {
552
+ JSValue ok = JS_GetPropertyStr(ctx, argv[0], "ok");
553
+ downloaded = JS_ToBool(ctx, ok);
554
+ JS_FreeValue(ctx, ok);
555
+ if (!downloaded) {
556
+ JSValue error = JS_GetPropertyStr(ctx, argv[0], "error");
557
+ JSValue msg = JS_GetPropertyStr(ctx, error, "message");
558
+ const char* text = JS_ToCString(ctx, msg);
559
+ if (text) {
560
+ message = text;
561
+ JS_FreeCString(ctx, text);
562
+ }
563
+ JS_FreeValue(ctx, msg);
564
+ JS_FreeValue(ctx, error);
565
+ }
566
+ }
567
+ settle_apply(ctx, downloaded, message);
568
+ return JS_UNDEFINED;
569
+ }
570
+
571
+ JSValue download_rejected(JSContext* ctx, JSValue, int argc, JSValue* argv) {
572
+ std::string message = "download threw";
573
+ if (argc > 0) {
574
+ const char* text = JS_ToCString(ctx, argv[0]);
575
+ if (text) {
576
+ message = text;
577
+ JS_FreeCString(ctx, text);
578
+ }
579
+ }
580
+ settle_apply(ctx, false, message);
581
+ return JS_UNDEFINED;
582
+ }
583
+
584
+ /* applyOffer(offer, download, options?) -> Promise<Result<ApplyOutcome, OtaError>> */
585
+ JSValue ota_apply_offer(JSContext* ctx, JSValue, int argc, JSValue* argv) {
586
+ MIKOtaClientState* state = state_of(ctx);
587
+ CHECK_NOT_NULL(state);
588
+ if (argc < 2 || !JS_IsFunction(ctx, argv[1])) {
589
+ return JS_ThrowTypeError(ctx, "applyOffer(offer, download) needs a download function");
590
+ }
591
+ if (state->apply.active) {
592
+ JSValue busy = mik__result_err_named(ctx, "StagingFailed", "an update is already staging");
593
+ return MIK_NewResolvedPromise(ctx, 1, &busy);
594
+ }
595
+
596
+ MIKOtaOffer offer;
597
+ if (!mikrojs::mik__ota_parse_offer_js(ctx, argv[0], /*allow_insecure=*/true, &offer)) {
598
+ JSValue bad = mik__result_err_named(ctx, "StagingFailed", "offer is not usable");
599
+ return MIK_NewResolvedPromise(ctx, 1, &bad);
600
+ }
601
+
602
+ MIKOtaInstallOptions options;
603
+ if (argc > 2 && JS_IsObject(argv[2])) {
604
+ options.trial_boots =
605
+ (int)opt_u32(ctx, argv[2], "trialBoots", (uint32_t)options.trial_boots);
606
+ options.require_confirm = opt_bool(ctx, argv[2], "requireConfirm", options.require_confirm);
607
+ JSValue install = JS_GetPropertyStr(ctx, argv[2], "install");
608
+ const char* mode = JS_IsString(install) ? JS_ToCString(ctx, install) : nullptr;
609
+ options.install_now = mode && strcmp(mode, "now") == 0;
610
+ if (mode) JS_FreeCString(ctx, mode);
611
+ JS_FreeValue(ctx, install);
612
+ }
613
+
614
+ MIKOtaApplyOutcome outcome = MIKOtaApplyOutcome::kStaged;
615
+ MIKOtaError error;
616
+ if (!mikrojs::mik__ota_policy_apply_begin(state->env, offer, &state->apply.session, &outcome,
617
+ &error)) {
618
+ note_decline(state->env, offer.checksum, "install-failed", error.message);
619
+ JSValue failed = mik__result_err_obj(ctx, error_to_js(ctx, error));
620
+ return MIK_NewResolvedPromise(ctx, 1, &failed);
621
+ }
622
+ if (!state->apply.session.update) {
623
+ /* Declined before staging: trial pending, current, abandoned, exhausted.
624
+ * Only the last two are recorded for the registry — the first two are
625
+ * the policy working as intended, mirroring the built-in's NoteDecline. */
626
+ if (outcome == MIKOtaApplyOutcome::kAbandoned ||
627
+ outcome == MIKOtaApplyOutcome::kExhausted) {
628
+ note_decline(state->env, offer.checksum, mikrojs::mik__ota_outcome_to_str(outcome), "");
629
+ }
630
+ JSValue declined =
631
+ mik__result_ok(ctx, JS_NewString(ctx, mikrojs::mik__ota_outcome_to_str(outcome)));
632
+ return MIK_NewResolvedPromise(ctx, 1, &declined);
633
+ }
634
+
635
+ state->apply.options = options;
636
+ state->apply.active = true;
637
+ JSValue promise = MIK_InitPromise(ctx, &state->apply.promise);
638
+ if (JS_IsException(promise)) {
639
+ state->apply.active = false;
640
+ state->apply.session.update.reset();
641
+ return JS_EXCEPTION;
642
+ }
643
+
644
+ JSValue update = make_update_object(ctx, state->apply.session.update->resume_offset());
645
+ JSValue returned = JS_Call(ctx, argv[1], JS_UNDEFINED, 1, &update);
646
+ JS_FreeValue(ctx, update);
647
+
648
+ if (JS_IsException(returned)) {
649
+ JSValue exc = JS_GetException(ctx);
650
+ const char* text = JS_ToCString(ctx, exc);
651
+ std::string message = text ? text : "download threw";
652
+ if (text) JS_FreeCString(ctx, text);
653
+ JS_FreeValue(ctx, exc);
654
+ JS_FreeValue(ctx, returned);
655
+ settle_apply(ctx, false, message);
656
+ return promise;
657
+ }
658
+
659
+ /* The callback may hand back a plain Result rather than a promise — or
660
+ * nothing, which is not a Result but must not throw on the way to being
661
+ * reported as a failed download. */
662
+ JSValue then = JS_IsObject(returned) ? JS_GetPropertyStr(ctx, returned, "then") : JS_UNDEFINED;
663
+ if (!JS_IsFunction(ctx, then)) {
664
+ JS_FreeValue(ctx, then);
665
+ JSValue args[1] = {returned};
666
+ JSValue ignored = download_fulfilled(ctx, JS_UNDEFINED, 1, args);
667
+ JS_FreeValue(ctx, ignored);
668
+ JS_FreeValue(ctx, returned);
669
+ return promise;
670
+ }
671
+ JSValue on_ok = JS_NewCFunction(ctx, download_fulfilled, "onFulfilled", 1);
672
+ JSValue on_err = JS_NewCFunction(ctx, download_rejected, "onRejected", 1);
673
+ JSValue chain_args[2] = {on_ok, on_err};
674
+ JSValue chained = JS_Call(ctx, then, returned, 2, chain_args);
675
+ JS_FreeValue(ctx, chained);
676
+ JS_FreeValue(ctx, on_ok);
677
+ JS_FreeValue(ctx, on_err);
678
+ JS_FreeValue(ctx, then);
679
+ JS_FreeValue(ctx, returned);
680
+ return promise;
681
+ }
682
+
683
+ // ── config delivery ─────────────────────────────────────────────────────────
684
+ //
685
+ // The write side of config sync, for a client that received a document over its
686
+ // own transport. Where the slot policy lives is src/mik_ota_config.cpp, shared
687
+ // with the built-in client, so the two cannot disagree about the trial or the
688
+ // rollback baseline. What is here is the marshalling.
689
+
690
+ /* Copy a string field into a fixed buffer. False when it is the wrong type or
691
+ * too long to hold: a truncated rev never matches the one the registry issued,
692
+ * so the device would be served the same document forever. */
693
+ bool take_config_field(JSContext* ctx, JSValue obj, const char* key, char* out, size_t out_len,
694
+ bool* out_present) {
695
+ *out_present = false;
696
+ JSValue value = JS_GetPropertyStr(ctx, obj, key);
697
+ if (JS_IsUndefined(value) || JS_IsNull(value)) {
698
+ JS_FreeValue(ctx, value);
699
+ return true;
700
+ }
701
+ if (!JS_IsString(value)) {
702
+ JS_FreeValue(ctx, value);
703
+ return false;
704
+ }
705
+ const char* text = JS_ToCString(ctx, value);
706
+ JS_FreeValue(ctx, value);
707
+ if (!text) return false;
708
+ bool fits = strlen(text) < out_len;
709
+ if (fits) {
710
+ snprintf(out, out_len, "%s", text);
711
+ *out_present = text[0] != '\0';
712
+ }
713
+ JS_FreeCString(ctx, text);
714
+ return fits;
715
+ }
716
+
717
+ /* Validate a raw value into the fields a stored config carries. `*out_doc` is
718
+ * the document to store, or JS_UNDEFINED for the clear; the caller owns it. */
719
+ bool config_from_js(JSContext* ctx, JSValue raw, MIKOtaStoredConfig* out, JSValue* out_doc) {
720
+ *out_doc = JS_UNDEFINED;
721
+ if (!JS_IsObject(raw) || JS_IsArray(raw) || JS_IsFunction(ctx, raw)) return false;
722
+
723
+ /* The stamp is what says which release the document was computed for, and
724
+ * every read is decided by it. A document without one cannot be placed. */
725
+ bool has_version = false;
726
+ if (!take_config_field(ctx, raw, "version", out->version, sizeof(out->version),
727
+ &has_version)) {
728
+ return false;
729
+ }
730
+ if (!has_version) return false;
731
+
732
+ bool has_rev = false;
733
+ if (!take_config_field(ctx, raw, "rev", out->rev, sizeof(out->rev), &has_rev)) return false;
734
+
735
+ JSValue doc = JS_GetPropertyStr(ctx, raw, "doc");
736
+ if (JS_IsUndefined(doc) || JS_IsNull(doc)) {
737
+ /* An absent document is the clear, not a malformed config. */
738
+ JS_FreeValue(ctx, doc);
739
+ return true;
740
+ }
741
+ /* The document is spread over the manifest defaults, top level only.
742
+ * Anything that is not a plain object has no keys to spread, so storing one
743
+ * would read back as an empty overlay rather than as the error it is. */
744
+ if (!JS_IsObject(doc) || JS_IsArray(doc) || JS_IsFunction(ctx, doc)) {
745
+ JS_FreeValue(ctx, doc);
746
+ return false;
747
+ }
748
+ *out_doc = doc;
749
+ return true;
750
+ }
751
+
752
+ /* Encode a document to the CBOR the slots store. False for a value CBOR cannot
753
+ * carry (a function, a cycle, past the depth limit). */
754
+ bool encode_config_doc(JSContext* ctx, JSValue doc, std::vector<uint8_t>* out) {
755
+ /* Pass 1 sizes it against a zero-capacity buffer; the base pointer must be
756
+ * non-null because a zero-length append still reaches memcpy. */
757
+ static uint8_t measure_base;
758
+ nanocbor_encoder_t enc;
759
+ nanocbor_encoder_init(&enc, &measure_base, 0);
760
+ bool ok = mik__cbor_encode_value(ctx, &enc, doc, 0) >= 0;
761
+ size_t needed = nanocbor_encoded_len(&enc);
762
+ if (ok && needed > 0) {
763
+ out->resize(needed);
764
+ nanocbor_encoder_init(&enc, out->data(), needed);
765
+ ok = mik__cbor_encode_value(ctx, &enc, doc, 0) >= 0;
766
+ } else {
767
+ ok = false;
768
+ }
769
+ /* Property enumeration can throw on the way out, and an exception left on
770
+ * the context would surface at whatever ran next. */
771
+ if (JS_HasException(ctx)) JS_FreeValue(ctx, JS_GetException(ctx));
772
+ return ok;
773
+ }
774
+
775
+ /* The config delivery, cfg + {trialBoots} -> ConfigWrite string, for settle(). */
776
+ JSValue ota_apply_config(JSContext* ctx, JSValue, int argc, JSValue* argv) {
777
+ MIKOtaClientState* state = state_of(ctx);
778
+ CHECK_NOT_NULL(state);
779
+
780
+ MIKOtaStoredConfig cfg = {};
781
+ JSValue doc = JS_UNDEFINED;
782
+ if (argc < 1 || !config_from_js(ctx, argv[0], &cfg, &doc)) {
783
+ JS_FreeValue(ctx, doc);
784
+ return JS_NewString(ctx, "invalid");
785
+ }
786
+
787
+ /* Held until the write is done: the stored config's span points into it. */
788
+ std::vector<uint8_t> bytes;
789
+ if (!JS_IsUndefined(doc)) {
790
+ bool encoded = encode_config_doc(ctx, doc, &bytes);
791
+ JS_FreeValue(ctx, doc);
792
+ if (!encoded) return JS_NewString(ctx, "invalid");
793
+ cfg.doc_cbor = bytes.data();
794
+ cfg.doc_cbor_len = bytes.size();
795
+ }
796
+
797
+ MIKOtaCheckOptions defaults;
798
+ int trial_boots = defaults.trial_boots;
799
+ if (argc > 1 && JS_IsObject(argv[1])) {
800
+ trial_boots = (int)opt_u32(ctx, argv[1], "trialBoots", (uint32_t)trial_boots);
801
+ }
802
+ /* A budget of zero would roll the document back on the first read that
803
+ * serves it, which is never what an app meant by delivering one. */
804
+ if (trial_boots < 1) trial_boots = 1;
805
+
806
+ MIKOtaConfigWrite write = mikrojs::mik__ota_deliver_config(state->env, &cfg, trial_boots);
807
+ return JS_NewString(ctx, mikrojs::mik__ota_config_write_to_str(write));
808
+ }
809
+
810
+ /* Loads the rolled-back report and sets the echo rev on `obj` under `rev_key`.
811
+ * After a rollback the FAILED document's rev is the one to echo, not the
812
+ * restored one's: echoed-equals-held is what stops the registry serving the
813
+ * document that just failed, until an operator changes it. Returns whether a
814
+ * report stands, leaving it in *report for the caller to marshal. */
815
+ bool set_config_echo(JSContext* ctx, JSValue obj, const char* rev_key, const MIKOtaEnv* env,
816
+ MIKOtaConfigErrorReport* report) {
817
+ bool has_error = mikrojs::mik__ota_load_config_error(env, report);
818
+ mikrojs::MIKOtaLoadedConfig held = mikrojs::mik__ota_load_slot(env, MIK_OTA_CFG_CURRENT);
819
+ const char* rev = has_error ? report->rev : (held.present ? held.cfg.rev : "");
820
+ if (rev[0]) JS_SetPropertyStr(ctx, obj, rev_key, JS_NewString(ctx, rev));
821
+ return has_error;
822
+ }
823
+
824
+ // ── the check-in exchange, for a client with its own transport ──────────────
825
+ //
826
+ // report() and settle() are the two halves the built-in client runs around its
827
+ // HTTP call: the same facts gathering as BeginCheckIn (mik_ota_client.cpp) and
828
+ // the same completed-round handling as its response parse. Everything either
829
+ // touches is an existing policy call, so a client that goes through here and
830
+ // the built-in cannot disagree about what a round sends or settles.
831
+
832
+ /* decline(checksum, reason, detail?) — record why the last offered build was
833
+ * not taken, for the next report() to carry as lastDecline. The apply paths
834
+ * record their own outcomes; this is for a reason only the app can see, such
835
+ * as a download budget it keeps across wakes. The caps are the registry's: an
836
+ * oversized reason would have the whole check-in rejected, so it throws here,
837
+ * while detail is free text and is cut to fit instead. */
838
+ JSValue ota_decline(JSContext* ctx, JSValue, int argc, JSValue* argv) {
839
+ MIKOtaClientState* state = state_of(ctx);
840
+ CHECK_NOT_NULL(state);
841
+
842
+ const char* checksum =
843
+ argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(ctx, argv[0]) : nullptr;
844
+ if (!checksum || !is_wire_checksum(checksum)) {
845
+ if (checksum) JS_FreeCString(ctx, checksum);
846
+ return JS_ThrowTypeError(ctx, "decline(): checksum must be 64 lowercase hex characters");
847
+ }
848
+ const char* reason = argc > 1 && JS_IsString(argv[1]) ? JS_ToCString(ctx, argv[1]) : nullptr;
849
+ if (!reason || reason[0] == '\0' || strlen(reason) > 64) {
850
+ JS_FreeCString(ctx, checksum);
851
+ if (reason) JS_FreeCString(ctx, reason);
852
+ return JS_ThrowTypeError(ctx, "decline(): reason must be 1 to 64 characters");
853
+ }
854
+ const char* detail = nullptr;
855
+ if (argc > 2 && !JS_IsUndefined(argv[2])) {
856
+ detail = JS_IsString(argv[2]) ? JS_ToCString(ctx, argv[2]) : nullptr;
857
+ if (!detail) {
858
+ JS_FreeCString(ctx, checksum);
859
+ JS_FreeCString(ctx, reason);
860
+ return JS_ThrowTypeError(ctx, "decline(): detail must be a string");
861
+ }
862
+ }
863
+
864
+ note_decline(state->env, checksum, reason, detail ? detail : "");
865
+ JS_FreeCString(ctx, checksum);
866
+ JS_FreeCString(ctx, reason);
867
+ if (detail) JS_FreeCString(ctx, detail);
868
+ return JS_UNDEFINED;
869
+ }
870
+
871
+ /* report() -> the check-in body the device owes its registry, wire field
872
+ * shapes throughout so a proxy can forward fields verbatim. */
873
+ JSValue ota_report(JSContext* ctx, JSValue, int, JSValue*) {
874
+ MIKOtaClientState* state = state_of(ctx);
875
+ CHECK_NOT_NULL(state);
876
+ const MIKOtaEnv* env = state->env;
877
+
878
+ JSValue obj = JS_NewObject(ctx);
879
+
880
+ MIKDeviceIdentity identity = {};
881
+ if (env && env->identity) env->identity(env->opaque, &identity);
882
+ JS_SetPropertyStr(ctx, obj, "deviceId", JS_NewString(ctx, identity.device_id));
883
+ JS_SetPropertyStr(ctx, obj, "firmware", JS_NewString(ctx, identity.firmware_version));
884
+ JS_SetPropertyStr(ctx, obj, "firmwareHash", JS_NewString(ctx, identity.firmware_hash));
885
+ JS_SetPropertyStr(ctx, obj, "bytecode", JS_NewInt32(ctx, identity.bytecode_version));
886
+
887
+ JS_SetPropertyStr(ctx, obj, "running", ota_running(ctx, JS_UNDEFINED, 0, nullptr));
888
+
889
+ /* The name pair, sent every round so a lost response settles on the next
890
+ * check-in: [rev, name], or [rev] when never named or cleared. */
891
+ int name_rev = 0;
892
+ char name[64] = {};
893
+ bool has_name = env && env->get_device_name &&
894
+ env->get_device_name(env->opaque, &name_rev, name, sizeof(name));
895
+ JSValue pair = JS_NewArray(ctx);
896
+ JS_SetPropertyUint32(ctx, pair, 0, JS_NewInt32(ctx, name_rev));
897
+ if (has_name && name[0]) JS_SetPropertyUint32(ctx, pair, 1, JS_NewString(ctx, name));
898
+ JS_SetPropertyStr(ctx, obj, "name", pair);
899
+
900
+ size_t free_bytes = 0;
901
+ if (env && env->storage_free && env->storage_free(env->opaque, &free_bytes)) {
902
+ JS_SetPropertyStr(ctx, obj, "free", JS_NewInt64(ctx, (int64_t)free_bytes));
903
+ }
904
+
905
+ if (state->has_last_install) {
906
+ JSValue diag = JS_NewObject(ctx);
907
+ JS_SetPropertyStr(ctx, diag, "reason", JS_NewString(ctx, state->last_install.reason));
908
+ if (state->last_install.detail[0]) {
909
+ JS_SetPropertyStr(ctx, diag, "detail", JS_NewString(ctx, state->last_install.detail));
910
+ }
911
+ JS_SetPropertyStr(ctx, obj, "lastInstall", diag);
912
+ }
913
+
914
+ /* Why the last offered build was not taken, recorded by applyOffer or
915
+ * decline(). Without it a registry cannot tell a device still working
916
+ * through a download from one that has stopped. */
917
+ MIKOtaDeclineRecord declined;
918
+ state->decline_reported = mikrojs::MIKOtaStore(env).GetDecline(&declined);
919
+ if (state->decline_reported) {
920
+ JSValue last = JS_NewObject(ctx);
921
+ JS_SetPropertyStr(ctx, last, "checksum", JS_NewString(ctx, declined.checksum));
922
+ JS_SetPropertyStr(ctx, last, "reason", JS_NewString(ctx, declined.reason));
923
+ if (declined.detail[0]) {
924
+ JS_SetPropertyStr(ctx, last, "detail", JS_NewString(ctx, declined.detail));
925
+ }
926
+ JS_SetPropertyStr(ctx, obj, "lastDecline", last);
927
+ }
928
+
929
+ /* configRev / configError, through the same resolution as configState(). */
930
+ MIKOtaConfigErrorReport report = {};
931
+ if (set_config_echo(ctx, obj, "configRev", env, &report)) {
932
+ JSValue error = JS_NewObject(ctx);
933
+ JS_SetPropertyStr(ctx, error, "rev", JS_NewString(ctx, report.rev));
934
+ JS_SetPropertyStr(ctx, error, "message", JS_NewString(ctx, report.message));
935
+ JS_SetPropertyStr(ctx, obj, "configError", error);
936
+ }
937
+ return obj;
938
+ }
939
+
940
+ /* settle(raw, {trialBoots, allowInsecure}) -> {offer?, config?, renamed}
941
+ *
942
+ * Only for a COMPLETED check-in: the confirm below is the whole health signal
943
+ * requireConfirm waits for, so settling a failed round would keep exactly the
944
+ * build (or document) that rollback exists to catch. */
945
+ JSValue ota_settle(JSContext* ctx, JSValue, int argc, JSValue* argv) {
946
+ MIKOtaClientState* state = state_of(ctx);
947
+ CHECK_NOT_NULL(state);
948
+
949
+ JSValue raw = argc > 0 ? argv[0] : JS_UNDEFINED;
950
+ JSValue out = JS_NewObject(ctx);
951
+
952
+ /* Mirror the built-in's response guard (its DecodeFailed path): null or
953
+ * undefined is the registry's quiet round, and an object is a decoded
954
+ * response — but anything else is a body that never decoded (a captive
955
+ * portal's HTML, a proxy's error page). That is not a completed round, so
956
+ * nothing settles: no confirm, and the cached install report stays for
957
+ * the round that does complete. */
958
+ bool quiet = JS_IsUndefined(raw) || JS_IsNull(raw);
959
+ bool usable = JS_IsObject(raw) && !JS_IsArray(raw) && !JS_IsFunction(ctx, raw);
960
+ if (!quiet && !usable) {
961
+ JS_SetPropertyStr(ctx, out, "renamed", JS_FALSE);
962
+ return out;
963
+ }
964
+
965
+ /* Confirm before the deliveries, as the built-in does: it must settle the
966
+ * document held BEFORE this round, never the one about to be armed. */
967
+ mikrojs::mik__ota_policy_confirm(state->env);
968
+ /* The round completed, so the cached install report was delivered, and so
969
+ * was the stored decline record if report() carried it. */
970
+ state->has_last_install = false;
971
+ if (state->decline_reported) {
972
+ mikrojs::MIKOtaStore(state->env).ClearDecline();
973
+ state->decline_reported = false;
974
+ }
975
+
976
+ bool renamed = false;
977
+ if (usable) {
978
+ /* The name pair: [rev] or [rev, name]. No `name` key means "no change"
979
+ * and never "clear it"; junk in the pair is treated the same way. The
980
+ * adopt is unconditional — the registry only sends the key when its
981
+ * rev should win. */
982
+ JSValue pair = JS_GetPropertyStr(ctx, raw, "name");
983
+ if (JS_IsArray(pair)) {
984
+ JSValue rev_val = JS_GetPropertyUint32(ctx, pair, 0);
985
+ /* A rev is a non-negative int32, as the wire carries it; a
986
+ * fractional or oversized number is junk, not a truncation. */
987
+ double rev_num = -1;
988
+ bool rev_ok = JS_IsNumber(rev_val) && JS_ToFloat64(ctx, &rev_num, rev_val) == 0 &&
989
+ rev_num >= 0 && rev_num <= 2147483647.0 &&
990
+ rev_num == (double)(int32_t)rev_num;
991
+ int32_t rev = rev_ok ? (int32_t)rev_num : -1;
992
+ JS_FreeValue(ctx, rev_val);
993
+ if (rev_ok && state->env && state->env->set_device_name) {
994
+ JSValue name_val = JS_GetPropertyUint32(ctx, pair, 1);
995
+ const char* name = JS_IsString(name_val) ? JS_ToCString(ctx, name_val) : nullptr;
996
+ state->env->set_device_name(state->env->opaque, rev,
997
+ name && name[0] ? name : nullptr);
998
+ renamed = true;
999
+ if (name) JS_FreeCString(ctx, name);
1000
+ JS_FreeValue(ctx, name_val);
1001
+ }
1002
+ }
1003
+ JS_FreeValue(ctx, pair);
1004
+
1005
+ /* The config document goes through the applyConfig path unchanged, so
1006
+ * the two entrances cannot diverge on validation or placement. */
1007
+ JSValue cfg_raw = JS_GetPropertyStr(ctx, raw, "config");
1008
+ if (!JS_IsUndefined(cfg_raw) && !JS_IsNull(cfg_raw)) {
1009
+ JSValue args[2] = {cfg_raw, argc > 1 ? argv[1] : JS_UNDEFINED};
1010
+ JS_SetPropertyStr(ctx, out, "config", ota_apply_config(ctx, JS_UNDEFINED, 2, args));
1011
+ }
1012
+ JS_FreeValue(ctx, cfg_raw);
1013
+
1014
+ /* The offer fields are top-level in the response, so the whole body
1015
+ * goes to the offer parser. */
1016
+ bool allow_insecure = false;
1017
+ if (argc > 1 && JS_IsObject(argv[1])) {
1018
+ allow_insecure = opt_bool(ctx, argv[1], "allowInsecure", false);
1019
+ }
1020
+ MIKOtaOffer offer;
1021
+ if (mikrojs::mik__ota_parse_offer_js(ctx, raw, allow_insecure, &offer)) {
1022
+ JS_SetPropertyStr(ctx, out, "offer", offer_to_js(ctx, offer));
1023
+ }
1024
+ }
1025
+ JS_SetPropertyStr(ctx, out, "renamed", JS_NewBool(ctx, renamed));
1026
+ return out;
1027
+ }
1028
+
1029
+ int mik__ota_client_module_init(JSContext* ctx, JSModuleDef* m) {
1030
+ JS_SetModuleExport(ctx, m, "check", JS_NewCFunction(ctx, mik__ota_client_check, "check", 1));
1031
+ JS_SetModuleExport(ctx, m, "watch", JS_NewCFunction(ctx, mik__ota_client_watch, "watch", 1));
1032
+ JS_SetModuleExport(ctx, m, "config", JS_NewCFunction(ctx, mik__ota_client_config, "config", 0));
1033
+ JS_SetModuleExport(ctx, m, "reconcile", JS_NewCFunction(ctx, ota_reconcile, "reconcile", 0));
1034
+ JS_SetModuleExport(ctx, m, "confirm", JS_NewCFunction(ctx, ota_confirm, "confirm", 0));
1035
+ JS_SetModuleExport(ctx, m, "revert", JS_NewCFunction(ctx, ota_revert, "revert", 0));
1036
+ JS_SetModuleExport(ctx, m, "bearer", JS_NewCFunction(ctx, ota_bearer, "bearer", 0));
1037
+ JS_SetModuleExport(ctx, m, "registry", JS_NewCFunction(ctx, ota_registry, "registry", 0));
1038
+ JS_SetModuleExport(ctx, m, "applyOffer",
1039
+ JS_NewCFunction(ctx, ota_apply_offer, "applyOffer", 3));
1040
+ JS_SetModuleExport(ctx, m, "decline", JS_NewCFunction(ctx, ota_decline, "decline", 3));
1041
+ JS_SetModuleExport(ctx, m, "report", JS_NewCFunction(ctx, ota_report, "report", 0));
1042
+ JS_SetModuleExport(ctx, m, "settle", JS_NewCFunction(ctx, ota_settle, "settle", 2));
1043
+ return 0;
1044
+ }
1045
+
1046
+ } // namespace
1047
+
1048
+ JSModuleDef* mik__ota_client_init(JSContext* ctx) {
1049
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
1050
+ CHECK_NOT_NULL(mik_rt);
1051
+ if (mik__ota_client_slot < 0) mik__ota_client_slot = MIK_ReserveModuleSlot();
1052
+
1053
+ /* The bytecode version needs a context to derive (JS_WriteObject's first
1054
+ * byte), so it is read here and handed to the env, which has none. */
1055
+ size_t bc_len = 0;
1056
+ uint8_t* bc_buf = JS_WriteObject(ctx, &bc_len, JS_NULL, JS_WRITE_OBJ_BYTECODE);
1057
+ int bytecode_version = (bc_buf && bc_len > 0) ? bc_buf[0] : 0;
1058
+ if (bc_buf) js_free(ctx, bc_buf);
1059
+
1060
+ auto* state = new MIKOtaClientState();
1061
+ state->ctx = ctx;
1062
+ /* The client drives HTTP from C and never imports native:mikro/http, so
1063
+ * nothing else would bring the transport up. */
1064
+ mik__http_ensure_native(ctx);
1065
+
1066
+ const MIKOtaEnv* env = mik__ota_env_for(mik_rt, bytecode_version);
1067
+ state->env = env;
1068
+ state->config = std::make_unique<MIKOtaConfigReader>(env);
1069
+ state->client = std::make_unique<MIKOtaClient>(env);
1070
+ mik__ota_client_st(mik_rt) = state;
1071
+
1072
+ JSModuleDef* m = JS_NewCModule(ctx, "native:mikro/ota_client", mik__ota_client_module_init);
1073
+ if (!m) {
1074
+ /* The loop consumer is only registered when init returns a module. */
1075
+ delete state;
1076
+ mik__ota_client_st(mik_rt) = nullptr;
1077
+ return nullptr;
1078
+ }
1079
+ JS_AddModuleExport(ctx, m, "check");
1080
+ JS_AddModuleExport(ctx, m, "watch");
1081
+ JS_AddModuleExport(ctx, m, "config");
1082
+ JS_AddModuleExport(ctx, m, "reconcile");
1083
+ JS_AddModuleExport(ctx, m, "confirm");
1084
+ JS_AddModuleExport(ctx, m, "revert");
1085
+ JS_AddModuleExport(ctx, m, "bearer");
1086
+ JS_AddModuleExport(ctx, m, "registry");
1087
+ JS_AddModuleExport(ctx, m, "applyOffer");
1088
+ JS_AddModuleExport(ctx, m, "decline");
1089
+ JS_AddModuleExport(ctx, m, "report");
1090
+ JS_AddModuleExport(ctx, m, "settle");
1091
+ return m;
1092
+ }
1093
+
1094
+ void mik__ota_client_consume(JSContext* ctx) {
1095
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
1096
+ CHECK_NOT_NULL(mik_rt);
1097
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
1098
+ if (!state || !state->client) return;
1099
+
1100
+ state->client->Poll();
1101
+
1102
+ /* Drop settled checks. Done after Poll rather than inside the sink so the
1103
+ * vector is never mutated while the machine is walking it. */
1104
+ for (size_t i = state->pending.size(); i > 0; i--) {
1105
+ if (state->pending[i - 1]->settled) state->pending.erase(state->pending.begin() + (i - 1));
1106
+ }
1107
+ }
1108
+
1109
+ void mik__ota_client_destroy(JSContext* ctx) {
1110
+ MIKRuntime* mik_rt = MIK_GetRuntime(ctx);
1111
+ CHECK_NOT_NULL(mik_rt);
1112
+ MIKOtaClientState* state = mik__ota_client_st(mik_rt);
1113
+ if (!state) return;
1114
+
1115
+ if (state->client) state->client->StopWatch();
1116
+ /* Anything still waiting will never settle: free the promise values so
1117
+ * teardown does not leave JSValues behind. */
1118
+ for (auto& pending : state->pending) {
1119
+ if (!pending->settled) MIK_FreePromise(ctx, &pending->promise);
1120
+ }
1121
+ state->pending.clear();
1122
+ /* The client before the hooks: a round parked in beforeCheck or teardown
1123
+ * still holds the hook pointer, and the client's teardown is what lets it
1124
+ * go. */
1125
+ if (state->apply.active) {
1126
+ /* Nothing will settle it now; free the promise's values rather than
1127
+ * leaving them behind. */
1128
+ MIK_FreePromise(ctx, &state->apply.promise);
1129
+ state->apply.active = false;
1130
+ }
1131
+ state->client.reset();
1132
+ state->hooks.reset();
1133
+ JS_FreeValue(ctx, state->on_config);
1134
+ state->on_config = JS_UNDEFINED;
1135
+ /* Before the runtime: the reader holds the last document it served. */
1136
+ state->config.reset();
1137
+ delete state;
1138
+ mik__ota_client_st(mik_rt) = nullptr;
1139
+ }
1140
+
1141
+ MIK_REGISTER_MODULE(ota_client, "native:mikro/ota_client", mik__ota_client_init,
1142
+ mik__ota_client_consume, mik__ota_client_destroy)