@native-sdk/cli 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,211 @@
1
+ //! Tier-2 record-store effect coverage: the public Zig surface remains inert
2
+ //! command data until Effects performs it, and every SQLite answer returns as
3
+ //! the same routed/journaled host-result message family used by TS cores.
4
+
5
+ const std = @import("std");
6
+ const effects_mod = @import("effects.zig");
7
+ const record_store = @import("record_store.zig");
8
+
9
+ const Msg = union(enum) { result: effects_mod.EffectHostResult };
10
+ const Fx = effects_mod.Effects(Msg);
11
+
12
+ fn takeResult(fx: *Fx) !effects_mod.EffectHostResult {
13
+ for (0..100_000) |_| {
14
+ if (fx.takeMsg()) |msg| return msg.result;
15
+ std.Thread.yield() catch {};
16
+ }
17
+ return error.TestExpectedMsg;
18
+ }
19
+
20
+ test "record-store effects round-trip CRUD and preserve empty versus missing" {
21
+ var store = try record_store.Store.openMemory(std.testing.allocator);
22
+ defer store.deinit();
23
+ var fx = Fx.init(std.testing.allocator);
24
+ defer fx.deinit();
25
+ fx.bindRecordStore(store.binding());
26
+
27
+ fx.storeSet(.{ .key = 1, .record_key = "doc/1", .bytes = "", .on_result = Fx.hostMsg(.result) });
28
+ const set = try takeResult(&fx);
29
+ try std.testing.expect(set.ok);
30
+ try std.testing.expectEqual(@as(usize, 0), set.bytes.len);
31
+
32
+ fx.storeGet(.{ .key = 2, .record_key = "doc/1", .on_result = Fx.hostMsg(.result) });
33
+ const hit = try takeResult(&fx);
34
+ try std.testing.expect(hit.ok);
35
+ try std.testing.expectEqualSlices(u8, &.{1}, hit.bytes);
36
+
37
+ fx.storeDelete(.{ .key = 3, .record_key = "doc/1", .on_result = Fx.hostMsg(.result) });
38
+ try std.testing.expect((try takeResult(&fx)).ok);
39
+ fx.storeGet(.{ .key = 4, .record_key = "doc/1", .on_result = Fx.hostMsg(.result) });
40
+ const miss = try takeResult(&fx);
41
+ try std.testing.expect(miss.ok);
42
+ try std.testing.expectEqualSlices(u8, &.{0}, miss.bytes);
43
+ }
44
+
45
+ test "record-store effects apply setMany atomically and page prefix scans" {
46
+ var store = try record_store.Store.openMemory(std.testing.allocator);
47
+ defer store.deinit();
48
+ var fx = Fx.init(std.testing.allocator);
49
+ defer fx.deinit();
50
+ fx.bindRecordStore(store.binding());
51
+
52
+ const entries = [_]Fx.StoreEntry{
53
+ .{ .key = "chat/1", .bytes = "one" },
54
+ .{ .key = "chat/2", .bytes = "two" },
55
+ .{ .key = "other/1", .bytes = "skip" },
56
+ };
57
+ fx.storeSetMany(.{ .key = 10, .entries = &entries, .on_result = Fx.hostMsg(.result) });
58
+ try std.testing.expect((try takeResult(&fx)).ok);
59
+
60
+ fx.storeScan(.{ .key = 11, .prefix = "chat/", .limit = 1, .on_result = Fx.hostMsg(.result) });
61
+ const page = try takeResult(&fx);
62
+ try std.testing.expect(page.ok);
63
+ var cursor: usize = 0;
64
+ try std.testing.expectEqual(@as(u32, 1), readU32(page.bytes, &cursor));
65
+ try std.testing.expectEqualStrings("chat/1", readField(page.bytes, &cursor));
66
+ try std.testing.expectEqualStrings("one", readField(page.bytes, &cursor));
67
+ try std.testing.expectEqualStrings("chat/1", readField(page.bytes, &cursor));
68
+ try std.testing.expectEqual(page.bytes.len, cursor);
69
+ }
70
+
71
+ test "a synchronous get in the same command walk observes the preceding write" {
72
+ var store = try record_store.Store.openMemory(std.testing.allocator);
73
+ defer store.deinit();
74
+ var fx = Fx.init(std.testing.allocator);
75
+ defer fx.deinit();
76
+ fx.bindRecordStore(store.binding());
77
+
78
+ fx.storeSet(.{ .key = 12, .record_key = "ordered/key", .bytes = "visible", .on_result = Fx.hostMsg(.result) });
79
+ fx.storeGet(.{ .key = 13, .record_key = "ordered/key", .on_result = Fx.hostMsg(.result) });
80
+
81
+ const first = try takeResult(&fx);
82
+ const second = try takeResult(&fx);
83
+ try std.testing.expect(first.ok);
84
+ try std.testing.expect(second.ok);
85
+ const read = if (first.key == 13) first else second;
86
+ try std.testing.expect(read.ok);
87
+ try std.testing.expectEqualSlices(u8, "visible", read.bytes[1..]);
88
+ }
89
+
90
+ test "record-store effects reject bounds and absent capability loudly" {
91
+ var fx = Fx.init(std.testing.allocator);
92
+ defer fx.deinit();
93
+ fx.storeGet(.{ .key = 20, .record_key = "missing", .on_result = Fx.hostMsg(.result) });
94
+ const absent = try takeResult(&fx);
95
+ try std.testing.expect(!absent.ok);
96
+ try std.testing.expectEqualStrings("rejected", absent.bytes);
97
+
98
+ var oversized_key: [record_store.max_key_bytes + 1]u8 = undefined;
99
+ @memset(&oversized_key, 'k');
100
+ fx.storeGet(.{ .key = 21, .record_key = &oversized_key, .on_result = Fx.hostMsg(.result) });
101
+ const bounded = try takeResult(&fx);
102
+ try std.testing.expect(!bounded.ok);
103
+ try std.testing.expectEqualStrings("bad_key", bounded.bytes);
104
+ }
105
+
106
+ test "record-store requests have capacity independent of generic effects" {
107
+ var fx = Fx.init(std.testing.allocator);
108
+ defer fx.deinit();
109
+ fx.executor = .fake;
110
+
111
+ for (0..effects_mod.max_effects) |index| {
112
+ fx.hostRequest(.{
113
+ .key = 100 + index,
114
+ .name = "fixture.request",
115
+ .on_result = Fx.hostMsg(.result),
116
+ });
117
+ }
118
+ for (0..effects_mod.max_store_effects) |index| {
119
+ fx.storeGet(.{
120
+ .key = 1_000 + index,
121
+ .record_key = "fixture/key",
122
+ .on_result = Fx.hostMsg(.result),
123
+ });
124
+ }
125
+ try std.testing.expectEqual(
126
+ effects_mod.max_effects + effects_mod.max_store_effects,
127
+ fx.pendingHostCount(),
128
+ );
129
+
130
+ fx.storeGet(.{
131
+ .key = 2_000,
132
+ .record_key = "fixture/overflow",
133
+ .on_result = Fx.hostMsg(.result),
134
+ });
135
+ const refused = try takeResult(&fx);
136
+ try std.testing.expect(!refused.ok);
137
+ try std.testing.expectEqualStrings("rejected", refused.bytes);
138
+ }
139
+
140
+ test "record-store keys replace on reissue and cancel silently" {
141
+ var fx = Fx.init(std.testing.allocator);
142
+ defer fx.deinit();
143
+ fx.executor = .fake;
144
+
145
+ fx.storeGet(.{ .key = 30, .record_key = "old/key", .on_result = Fx.hostMsg(.result) });
146
+ fx.storeGet(.{ .key = 30, .record_key = "new/key", .on_result = Fx.hostMsg(.result) });
147
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
148
+ const replacement = fx.pendingHostAt(0).?;
149
+ try std.testing.expectEqualStrings("core.store.get", replacement.name);
150
+ var payload_at: usize = 4;
151
+ try std.testing.expectEqualStrings("new/key", readField(replacement.payload, &payload_at));
152
+ try std.testing.expectEqual(replacement.payload.len, payload_at);
153
+ try fx.feedHostResult(30, true, &.{ 1, 'n', 'e', 'w' });
154
+ const result = try takeResult(&fx);
155
+ try std.testing.expectEqual(@as(u64, 30), result.key);
156
+ try std.testing.expectEqualSlices(u8, &.{ 1, 'n', 'e', 'w' }, result.bytes);
157
+
158
+ fx.storeScan(.{ .key = 31, .prefix = "chat/", .on_result = Fx.hostMsg(.result) });
159
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
160
+ fx.cancel(31);
161
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingHostCount());
162
+ try std.testing.expectError(error.EffectNotFound, fx.feedHostResult(31, true, &.{ 0, 0, 0, 0, 0, 0, 0, 0 }));
163
+ try std.testing.expect(fx.takeMsg() == null);
164
+ }
165
+
166
+ test "draining a store terminal retires a producer preempted after enqueue" {
167
+ var fx = Fx.init(std.testing.allocator);
168
+ defer fx.deinit();
169
+ fx.executor = .fake;
170
+
171
+ const key = 32;
172
+ fx.storeGet(.{ .key = key, .record_key = "doc/32", .on_result = Fx.hostMsg(.result) });
173
+ try fx.feedHostResult(key, true, &.{0});
174
+
175
+ // Reconstruct the real write worker's preemption window exactly:
176
+ // `storeWorkerMain` publishes the terminal entry, then stores
177
+ // `.draining`. A consumer can acquire the queue between those two
178
+ // operations and observe the queued result while the slot still says
179
+ // `.running`. The fake feed stores first, so rewind just that state.
180
+ for (&fx.slots) |*slot| {
181
+ if (slot.kind == .store and slot.key == key) slot.state.store(.running, .release);
182
+ }
183
+
184
+ const result = try takeResult(&fx);
185
+ try std.testing.expect(result.ok);
186
+ try std.testing.expectEqualSlices(u8, &.{0}, result.bytes);
187
+
188
+ // Delivery is the key-freeing instant. The drain must publish the
189
+ // terminal state itself rather than depending on the preempted worker
190
+ // to resume before update handles the result.
191
+ for (&fx.slots) |*slot| {
192
+ if (slot.kind != .store or slot.key != key) continue;
193
+ try std.testing.expectEqual(.draining, slot.state.load(.acquire));
194
+ try std.testing.expect(slot.fetch_buffer == null);
195
+ return;
196
+ }
197
+ return error.TestExpectedStoreSlot;
198
+ }
199
+
200
+ fn readU32(bytes: []const u8, cursor: *usize) u32 {
201
+ const value = std.mem.readInt(u32, bytes[cursor.*..][0..4], .little);
202
+ cursor.* += 4;
203
+ return value;
204
+ }
205
+
206
+ fn readField(bytes: []const u8, cursor: *usize) []const u8 {
207
+ const len: usize = @intCast(readU32(bytes, cursor));
208
+ const field = bytes[cursor.*..][0..len];
209
+ cursor.* += len;
210
+ return field;
211
+ }
@@ -0,0 +1,400 @@
1
+ //! Runtime policy for raw file effects.
2
+ //!
3
+ //! A manifest `filesystem` grant allows any process-visible path. Without
4
+ //! that grant, raw file effects are confined to the six directories the
5
+ //! app-dir resolver owns for this app. The check canonicalizes the existing
6
+ //! target, or the deepest existing parent for a target that will be created,
7
+ //! before comparing roots. Consequently an in-root symlink that points out
8
+ //! is not an app-directory exemption.
9
+
10
+ const std = @import("std");
11
+
12
+ pub const max_roots: usize = 6;
13
+
14
+ pub const Binding = struct {
15
+ roots: []const []const u8 = &.{},
16
+ permitted: bool = false,
17
+ /// The migration seam. Shipping runners set this true; embedders may use
18
+ /// false for one warning release while still exercising normalization.
19
+ enforce: bool = true,
20
+ };
21
+
22
+ pub const Decision = enum { allow, warn, reject };
23
+
24
+ pub const Resolved = struct {
25
+ path: []u8,
26
+ decision: Decision,
27
+ /// For an app-directory exemption, the already-open parent directory
28
+ /// capability the worker must use instead of reopening `path`. `basename`
29
+ /// points into `path`. Holding this handle across the worker handoff closes
30
+ /// the canonicalize-then-open race: every parent was opened first and its
31
+ /// handle-identity path verified inside the selected root.
32
+ parent: ?std.Io.Dir = null,
33
+ basename: []const u8 = "",
34
+ /// A read/stat/delete whose parent does not exist is authorized but absent. The
35
+ /// caller returns the operation's ordinary not-found shape without ever
36
+ /// reopening the unresolved pathname.
37
+ missing: bool = false,
38
+
39
+ pub fn deinit(self: *Resolved, allocator: std.mem.Allocator, io: std.Io) void {
40
+ if (self.parent) |parent| parent.close(io);
41
+ allocator.free(self.path);
42
+ self.* = undefined;
43
+ }
44
+ };
45
+
46
+ pub const ResolveOptions = struct {
47
+ create_parents: bool = false,
48
+ /// Authorize the fully resolved target, but hand the caller the resolved
49
+ /// parent plus the request's original final component. Deletion uses this
50
+ /// so removing a symlink unlinks that directory entry rather than the file
51
+ /// it names. Both paths must be inside an app root when no filesystem
52
+ /// permission is present.
53
+ preserve_final_component: bool = false,
54
+ };
55
+
56
+ /// Normalize first, then decide authority over that exact spelling. Most
57
+ /// callers perform I/O against the resolved target. Operations that preserve
58
+ /// the final component authorize both that target and the resolved directory
59
+ /// entry they hand to the worker.
60
+ pub fn resolve(
61
+ allocator: std.mem.Allocator,
62
+ io: std.Io,
63
+ binding: Binding,
64
+ requested_path: []const u8,
65
+ ) !Resolved {
66
+ return resolveForOperation(allocator, io, binding, requested_path, .{});
67
+ }
68
+
69
+ pub fn resolveForOperation(
70
+ allocator: std.mem.Allocator,
71
+ io: std.Io,
72
+ binding: Binding,
73
+ requested_path: []const u8,
74
+ options: ResolveOptions,
75
+ ) !Resolved {
76
+ if (requested_path.len == 0 or std.mem.indexOfScalar(u8, requested_path, 0) != null) return error.InvalidPath;
77
+ const canonical_target = try canonicalizeTarget(allocator, io, requested_path);
78
+ if (!options.preserve_final_component) {
79
+ return resolveCanonicalOperation(allocator, io, binding, canonical_target, canonical_target, options);
80
+ }
81
+
82
+ defer allocator.free(canonical_target);
83
+ const operation_path = try canonicalizeFinalEntry(allocator, io, requested_path);
84
+ return resolveCanonicalOperation(allocator, io, binding, canonical_target, operation_path, options);
85
+ }
86
+
87
+ fn resolveCanonicalOperation(
88
+ allocator: std.mem.Allocator,
89
+ io: std.Io,
90
+ binding: Binding,
91
+ canonical_target: []const u8,
92
+ operation_path: []u8,
93
+ options: ResolveOptions,
94
+ ) Resolved {
95
+ if (binding.permitted) return .{ .path = operation_path, .decision = .allow };
96
+ if (options.preserve_final_component and
97
+ !canonicalIsInsideAnyRoot(allocator, io, binding.roots, canonical_target))
98
+ {
99
+ return .{ .path = operation_path, .decision = if (binding.enforce) .reject else .warn };
100
+ }
101
+
102
+ for (binding.roots) |root| {
103
+ if (root.len == 0) continue;
104
+ const canonical_root = canonicalizeTarget(allocator, io, root) catch continue;
105
+ defer allocator.free(canonical_root);
106
+ var root_dir = openCanonicalDir(io, canonical_root, options.create_parents) catch {
107
+ // A missing root can only authorize an absent read/stat/delete. Compare
108
+ // canonical lexical spellings, then return the closed absence
109
+ // result; writes created the root above and never take this path.
110
+ if (!options.create_parents and pathIsWithin(canonical_root, operation_path)) {
111
+ return .{ .path = operation_path, .decision = .allow, .missing = true };
112
+ }
113
+ continue;
114
+ };
115
+
116
+ var root_real_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
117
+ const root_real_len = root_dir.realPath(io, &root_real_storage) catch {
118
+ root_dir.close(io);
119
+ continue;
120
+ };
121
+ const root_real = root_real_storage[0..root_real_len];
122
+ if (!pathIsWithin(root_real, operation_path)) {
123
+ root_dir.close(io);
124
+ continue;
125
+ }
126
+
127
+ const relative = relativeToRoot(root_real, operation_path) orelse {
128
+ root_dir.close(io);
129
+ continue;
130
+ };
131
+ const basename = std.fs.path.basename(relative);
132
+ if (basename.len == 0 or std.mem.eql(u8, basename, ".") or std.mem.eql(u8, basename, "..")) {
133
+ root_dir.close(io);
134
+ continue;
135
+ }
136
+ const parent_path = std.fs.path.dirname(relative) orelse "";
137
+ const parent = openVerifiedParent(io, root_dir, root_real, parent_path, options.create_parents) catch |err| switch (err) {
138
+ error.FileNotFound => return .{ .path = operation_path, .decision = .allow, .missing = true },
139
+ else => continue,
140
+ };
141
+ const basename_offset = @intFromPtr(basename.ptr) - @intFromPtr(relative.ptr) +
142
+ (@intFromPtr(relative.ptr) - @intFromPtr(operation_path.ptr));
143
+ return .{
144
+ .path = operation_path,
145
+ .decision = .allow,
146
+ .parent = parent,
147
+ .basename = operation_path[basename_offset .. basename_offset + basename.len],
148
+ };
149
+ }
150
+
151
+ return .{ .path = operation_path, .decision = if (binding.enforce) .reject else .warn };
152
+ }
153
+
154
+ /// Resolve every parent component but preserve the request's final directory
155
+ /// entry. Unlike `canonicalizeTarget`, this deliberately does not follow a
156
+ /// final symlink.
157
+ fn canonicalizeFinalEntry(allocator: std.mem.Allocator, io: std.Io, requested_path: []const u8) ![]u8 {
158
+ const basename = std.fs.path.basename(requested_path);
159
+ if (basename.len == 0 or
160
+ std.mem.eql(u8, basename, ".") or
161
+ std.mem.eql(u8, basename, "..") or
162
+ std.mem.indexOfAny(u8, basename, if (@import("builtin").os.tag == .windows) "/\\" else "/") != null)
163
+ {
164
+ return error.InvalidPath;
165
+ }
166
+ const parent_path = std.fs.path.dirname(requested_path) orelse ".";
167
+ const canonical_parent = try canonicalizeTarget(allocator, io, parent_path);
168
+ defer allocator.free(canonical_parent);
169
+ return std.fs.path.resolve(allocator, &.{ canonical_parent, basename });
170
+ }
171
+
172
+ fn openCanonicalDir(io: std.Io, canonical_path: []const u8, create: bool) !std.Io.Dir {
173
+ var components = std.fs.path.componentIterator(canonical_path);
174
+ const root = components.root() orelse return error.BadPathName;
175
+ var current = try std.Io.Dir.openDirAbsolute(io, root, .{ .follow_symlinks = false });
176
+ errdefer current.close(io);
177
+ while (components.next()) |component| {
178
+ const next = current.openDir(io, component.name, .{ .follow_symlinks = false }) catch |err| switch (err) {
179
+ error.FileNotFound => if (create) create_component: {
180
+ current.createDir(io, component.name, .default_dir) catch |create_err| switch (create_err) {
181
+ error.PathAlreadyExists => {},
182
+ else => return create_err,
183
+ };
184
+ break :create_component try current.openDir(io, component.name, .{ .follow_symlinks = false });
185
+ } else return error.FileNotFound,
186
+ else => return err,
187
+ };
188
+ current.close(io);
189
+ current = next;
190
+ }
191
+ return current;
192
+ }
193
+
194
+ pub fn decide(
195
+ allocator: std.mem.Allocator,
196
+ io: std.Io,
197
+ binding: Binding,
198
+ requested_path: []const u8,
199
+ ) Decision {
200
+ const resolved = resolve(allocator, io, binding, requested_path) catch return .reject;
201
+ var owned = resolved;
202
+ defer owned.deinit(allocator, io);
203
+ return resolved.decision;
204
+ }
205
+
206
+ fn relativeToRoot(root: []const u8, target: []const u8) ?[]const u8 {
207
+ if (!pathIsWithin(root, target) or pathsEqual(root, target)) return null;
208
+ var at = root.len;
209
+ while (at < target.len and isSeparator(target[at])) at += 1;
210
+ return target[at..];
211
+ }
212
+
213
+ fn openVerifiedParent(
214
+ io: std.Io,
215
+ root_dir: std.Io.Dir,
216
+ canonical_root: []const u8,
217
+ parent_path: []const u8,
218
+ create_parents: bool,
219
+ ) !std.Io.Dir {
220
+ var current = root_dir;
221
+ errdefer current.close(io);
222
+ var components = std.fs.path.componentIterator(parent_path);
223
+ while (components.next()) |component| {
224
+ var next = current.openDir(io, component.name, .{ .follow_symlinks = true }) catch |err| switch (err) {
225
+ error.FileNotFound => if (create_parents) create: {
226
+ current.createDir(io, component.name, .default_dir) catch |create_err| switch (create_err) {
227
+ error.PathAlreadyExists => {},
228
+ else => return create_err,
229
+ };
230
+ // A component we created must still be a directory, not a
231
+ // symlink substituted between create and open.
232
+ break :create try current.openDir(io, component.name, .{ .follow_symlinks = false });
233
+ } else return error.FileNotFound,
234
+ else => return err,
235
+ };
236
+ var next_real_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
237
+ const next_real_len = next.realPath(io, &next_real_storage) catch |err| {
238
+ next.close(io);
239
+ return err;
240
+ };
241
+ if (!pathIsWithin(canonical_root, next_real_storage[0..next_real_len])) {
242
+ next.close(io);
243
+ return error.AccessDenied;
244
+ }
245
+ current.close(io);
246
+ current = next;
247
+ }
248
+ return current;
249
+ }
250
+
251
+ /// Canonicalize the target when it exists. For a new target, walk upward to
252
+ /// the deepest existing parent, canonicalize that parent (resolving every
253
+ /// symlink in the chain), then append the missing lexical suffix. Root paths
254
+ /// are canonicalized independently so aliases such as macOS `/tmp` and
255
+ /// `/private/tmp` compare correctly.
256
+ pub fn isInsideAnyRoot(
257
+ allocator: std.mem.Allocator,
258
+ io: std.Io,
259
+ roots: []const []const u8,
260
+ requested_path: []const u8,
261
+ ) bool {
262
+ if (requested_path.len == 0 or roots.len == 0 or std.mem.indexOfScalar(u8, requested_path, 0) != null) return false;
263
+ const canonical_target = canonicalizeTarget(allocator, io, requested_path) catch return false;
264
+ defer allocator.free(canonical_target);
265
+ return canonicalIsInsideAnyRoot(allocator, io, roots, canonical_target);
266
+ }
267
+
268
+ fn canonicalIsInsideAnyRoot(allocator: std.mem.Allocator, io: std.Io, roots: []const []const u8, canonical_target: []const u8) bool {
269
+ for (roots) |root| {
270
+ if (root.len == 0) continue;
271
+ const canonical_root = canonicalizeTarget(allocator, io, root) catch continue;
272
+ defer allocator.free(canonical_root);
273
+ if (pathIsWithin(canonical_root, canonical_target)) return true;
274
+ }
275
+ return false;
276
+ }
277
+
278
+ fn canonicalizeTarget(allocator: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {
279
+ const cwd = std.Io.Dir.cwd();
280
+ if (cwd.realPathFileAlloc(io, path, allocator)) |resolved| {
281
+ defer allocator.free(resolved);
282
+ return allocator.dupe(u8, resolved);
283
+ } else |_| {}
284
+
285
+ // Preserve every missing component while searching for an existing
286
+ // ancestor. `std.fs.path.resolve` then normalizes `.`/`..` in the joined
287
+ // result, after the existing prefix has been resolved through symlinks.
288
+ var ancestor = path;
289
+ var suffix: std.ArrayList([]const u8) = .empty;
290
+ defer suffix.deinit(allocator);
291
+ while (true) {
292
+ const parent = std.fs.path.dirname(ancestor) orelse break;
293
+ const base = std.fs.path.basename(ancestor);
294
+ try suffix.append(allocator, base);
295
+ if (cwd.realPathFileAlloc(io, parent, allocator)) |resolved_parent| {
296
+ defer allocator.free(resolved_parent);
297
+ var parts: std.ArrayList([]const u8) = .empty;
298
+ defer parts.deinit(allocator);
299
+ try parts.append(allocator, resolved_parent);
300
+ var index = suffix.items.len;
301
+ while (index > 0) {
302
+ index -= 1;
303
+ try parts.append(allocator, suffix.items[index]);
304
+ }
305
+ return std.fs.path.resolve(allocator, parts.items);
306
+ } else |_| {}
307
+ if (std.mem.eql(u8, parent, ancestor)) break;
308
+ ancestor = parent;
309
+ }
310
+ // A completely missing relative tail still has one existing parent: cwd.
311
+ // Resolve it explicitly and append every requested component lexically.
312
+ if (!std.fs.path.isAbsolute(path)) {
313
+ const cwd_resolved = try cwd.realPathFileAlloc(io, ".", allocator);
314
+ defer allocator.free(cwd_resolved);
315
+ return std.fs.path.resolve(allocator, &.{ cwd_resolved, path });
316
+ }
317
+ return error.FileNotFound;
318
+ }
319
+
320
+ fn pathIsWithin(root: []const u8, target: []const u8) bool {
321
+ if (pathsEqual(root, target)) return true;
322
+ if (root.len == 0 or target.len <= root.len) return false;
323
+ if (!pathPrefixEqual(root, target[0..root.len])) return false;
324
+ return isSeparator(target[root.len]) or isSeparator(root[root.len - 1]);
325
+ }
326
+
327
+ fn pathsEqual(a: []const u8, b: []const u8) bool {
328
+ if (a.len != b.len) return false;
329
+ return pathPrefixEqual(a, b);
330
+ }
331
+
332
+ fn pathPrefixEqual(a: []const u8, b: []const u8) bool {
333
+ if (@import("builtin").os.tag != .windows) return std.mem.eql(u8, a, b);
334
+ return std.ascii.eqlIgnoreCase(a, b);
335
+ }
336
+
337
+ fn isSeparator(byte: u8) bool {
338
+ return byte == '/' or (@import("builtin").os.tag == .windows and byte == '\\');
339
+ }
340
+
341
+ test "canonical containment rejects lexical escapes and symlinks that point out" {
342
+ var tmp = std.testing.tmpDir(.{});
343
+ defer tmp.cleanup();
344
+ try tmp.dir.createDirPath(std.testing.io, "app/data");
345
+ try tmp.dir.createDirPath(std.testing.io, "outside");
346
+
347
+ var root_buffer: [256]u8 = undefined;
348
+ var inside_buffer: [256]u8 = undefined;
349
+ var escape_buffer: [256]u8 = undefined;
350
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
351
+ const inside = try std.fmt.bufPrint(&inside_buffer, "{s}/nested/new.bin", .{root});
352
+ const escaped = try std.fmt.bufPrint(&escape_buffer, "{s}/../../outside/new.bin", .{root});
353
+ try std.testing.expect(isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, inside));
354
+ try std.testing.expect(!isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, escaped));
355
+
356
+ if (@import("builtin").os.tag != .windows) {
357
+ try tmp.dir.symLink(std.testing.io, "../../outside", "app/data/link", .{ .is_directory = true });
358
+ var symlink_buffer: [256]u8 = undefined;
359
+ const through_symlink = try std.fmt.bufPrint(&symlink_buffer, "{s}/link/new.bin", .{root});
360
+ try std.testing.expect(!isInsideAnyRoot(std.testing.allocator, std.testing.io, &.{root}, through_symlink));
361
+ }
362
+ }
363
+
364
+ test "an authorized request retains the opened parent capability" {
365
+ var tmp = std.testing.tmpDir(.{});
366
+ defer tmp.cleanup();
367
+ try tmp.dir.createDirPath(std.testing.io, "app/data/nested");
368
+ var root_buffer: [256]u8 = undefined;
369
+ var target_buffer: [256]u8 = undefined;
370
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
371
+ const target = try std.fmt.bufPrint(&target_buffer, "{s}/nested/file.bin", .{root});
372
+ var resolved = try resolveForOperation(std.testing.allocator, std.testing.io, .{ .roots = &.{root} }, target, .{ .create_parents = true });
373
+ defer resolved.deinit(std.testing.allocator, std.testing.io);
374
+ try std.testing.expectEqual(Decision.allow, resolved.decision);
375
+ try std.testing.expect(resolved.parent != null);
376
+ try std.testing.expectEqualStrings("file.bin", resolved.basename);
377
+ }
378
+
379
+ test "a retained parent capability ignores a later pathname symlink swap" {
380
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
381
+ var tmp = std.testing.tmpDir(.{});
382
+ defer tmp.cleanup();
383
+ try tmp.dir.createDirPath(std.testing.io, "app/data/nested");
384
+ try tmp.dir.createDirPath(std.testing.io, "outside");
385
+ var root_buffer: [256]u8 = undefined;
386
+ var target_buffer: [256]u8 = undefined;
387
+ const root = try std.fmt.bufPrint(&root_buffer, ".zig-cache/tmp/{s}/app/data", .{tmp.sub_path[0..]});
388
+ const target = try std.fmt.bufPrint(&target_buffer, "{s}/nested/file.bin", .{root});
389
+ var resolved = try resolveForOperation(std.testing.allocator, std.testing.io, .{ .roots = &.{root} }, target, .{ .create_parents = true });
390
+ defer resolved.deinit(std.testing.allocator, std.testing.io);
391
+
392
+ try tmp.dir.rename("app/data/nested", tmp.dir, "app/data/retained", std.testing.io);
393
+ try tmp.dir.symLink(std.testing.io, "../../outside", "app/data/nested", .{ .is_directory = true });
394
+ try resolved.parent.?.writeFile(std.testing.io, .{ .sub_path = resolved.basename, .data = "safe" });
395
+
396
+ const retained = try tmp.dir.readFileAlloc(std.testing.io, "app/data/retained/file.bin", std.testing.allocator, .limited(16));
397
+ defer std.testing.allocator.free(retained);
398
+ try std.testing.expectEqualStrings("safe", retained);
399
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(std.testing.io, "outside/file.bin", .{}));
400
+ }
@@ -0,0 +1,28 @@
1
+ const std = @import("std");
2
+ const native_sdk = @import("native_sdk");
3
+
4
+ const Msg = union(enum) { file: native_sdk.EffectFileResult };
5
+ const Fx = native_sdk.Effects(Msg);
6
+
7
+ fn waitResult(fx: *Fx, io: std.Io) !native_sdk.EffectFileResult {
8
+ while (true) {
9
+ if (fx.takeMsg()) |msg| return msg.file;
10
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake);
11
+ }
12
+ }
13
+
14
+ pub fn main(init: std.process.Init) !void {
15
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
16
+ if (args.len != 3) return error.InvalidArguments;
17
+ const destination = args[1];
18
+ const ready = args[2];
19
+ var fx = Fx.init(init.gpa);
20
+ // Deliberately no deinit: the parent kills this process to model a hard
21
+ // crash after the temporary contains bytes but before atomic replace.
22
+ fx.writeFileStream(.{ .key = 1, .path = destination, .on_result = Fx.fileMsg(.file) });
23
+ if ((try waitResult(&fx, init.io)).outcome != .ok) return error.OpenFailed;
24
+ fx.writeFileChunk(.{ .key = 1, .bytes = "partial replacement that must never become visible", .on_result = Fx.fileMsg(.file) });
25
+ if ((try waitResult(&fx, init.io)).outcome != .ok) return error.ChunkFailed;
26
+ try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = ready, .data = "ready" });
27
+ while (true) try std.Io.sleep(init.io, std.Io.Duration.fromSeconds(60), .awake);
28
+ }
@@ -0,0 +1,37 @@
1
+ const std = @import("std");
2
+ const crash_options = @import("file_crash_options");
3
+
4
+ test "hard process death before streamed close leaves the installed file untouched" {
5
+ const io = std.testing.io;
6
+ var tmp = std.testing.tmpDir(.{});
7
+ defer tmp.cleanup();
8
+ try tmp.dir.writeFile(io, .{ .sub_path = "export.bin", .data = "previous complete generation" });
9
+
10
+ var destination_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
11
+ var ready_storage: [std.Io.Dir.max_path_bytes]u8 = undefined;
12
+ const destination = try std.fmt.bufPrint(&destination_storage, ".zig-cache/tmp/{s}/export.bin", .{tmp.sub_path[0..]});
13
+ const ready = try std.fmt.bufPrint(&ready_storage, ".zig-cache/tmp/{s}/ready", .{tmp.sub_path[0..]});
14
+ var child = try std.process.spawn(io, .{
15
+ .argv = &.{ crash_options.helper_executable, destination, ready },
16
+ .stdin = .ignore,
17
+ .stdout = .ignore,
18
+ .stderr = .inherit,
19
+ });
20
+ defer child.kill(io);
21
+
22
+ var waited_ms: usize = 0;
23
+ while (waited_ms < 20_000) : (waited_ms += 10) {
24
+ if (tmp.dir.openFile(io, "ready", .{})) |file_value| {
25
+ var file = file_value;
26
+ file.close(io);
27
+ break;
28
+ } else |_| {}
29
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
30
+ }
31
+ if (waited_ms == 20_000) return error.TestTimedOut;
32
+ child.kill(io);
33
+
34
+ const visible = try tmp.dir.readFileAlloc(io, "export.bin", std.testing.allocator, .limited(128));
35
+ defer std.testing.allocator.free(visible);
36
+ try std.testing.expectEqualStrings("previous complete generation", visible);
37
+ }