-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodule_binding.zig
More file actions
1917 lines (1666 loc) · 67.5 KB
/
module_binding.zig
File metadata and controls
1917 lines (1666 loc) · 67.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Virtual Module Binding Specification
//!
//! A single comptime struct that captures every fact about a virtual module
//! needed by all consumers: resolver, type checker, verifier, bool checker,
//! contract builder, state manager, and trace/replay system.
//!
//! Built-in modules declare `pub const binding: ModuleBinding` alongside
//! their existing `exports` array. Third-party modules depend on zigttp-sdk
//! and write functions using ModuleFn (opaque handle) instead of NativeFn.
//!
//! The ModuleHandle opaque type provides a capability-based sandbox:
//! third-party modules cannot dereference the handle or access Context
//! internals. All interaction goes through free functions in this file.
const std = @import("std");
const object = @import("object.zig");
const value = @import("value.zig");
const context = @import("context.zig");
const compat = @import("compat.zig");
const file_io = @import("file_io.zig");
const sqlite_runtime = @import("sqlite.zig");
const resolver = @import("modules/internal/resolver.zig");
const security_events = @import("security_events.zig");
// Re-export EffectClass from resolver for backward compatibility
pub const EffectClass = resolver.EffectClass;
// -------------------------------------------------------------------------
// Opaque handle for third-party module sandbox
// -------------------------------------------------------------------------
/// Opaque handle passed to third-party module functions.
/// Cannot be dereferenced - modules interact with the runtime exclusively
/// through the free functions below. Internally this is a *Context, but
/// that fact is hidden from module authors.
pub const ModuleHandle = opaque {};
/// Function signature for third-party (sandboxed) module functions.
/// Receives an opaque handle instead of raw *anyopaque.
pub const ModuleFn = *const fn (
handle: *ModuleHandle,
this: value.JSValue,
args: []const value.JSValue,
) anyerror!value.JSValue;
const ActiveModuleContext = struct {
specifier: []const u8,
required_capabilities: []const ModuleCapability,
};
pub const ActiveModuleToken = struct {
previous: ?ActiveModuleContext,
};
threadlocal var active_module_context: ?ActiveModuleContext = null;
threadlocal var sdk_prng: ?std.Random.DefaultPrng = null;
/// Generate a NativeFn wrapper around a ModuleFn.
/// The wrapper casts *anyopaque to *ModuleHandle (a no-op pointer cast)
/// so the module receives the opaque handle it expects.
pub fn wrapModuleFn(comptime user_fn: ModuleFn) object.NativeFn {
return wrapModuleFnWithCapabilities(user_fn, "<sandboxed>", &.{});
}
pub fn wrapNativeFnWithCapabilities(
comptime user_fn: object.NativeFn,
comptime specifier: []const u8,
comptime required_capabilities: []const ModuleCapability,
) object.NativeFn {
return struct {
fn call(ctx_ptr: *anyopaque, this: value.JSValue, args: []const value.JSValue) anyerror!value.JSValue {
const token = pushActiveModuleContext(specifier, required_capabilities);
defer popActiveModuleContext(token);
return user_fn(ctx_ptr, this, args);
}
}.call;
}
pub fn wrapModuleFnWithCapabilities(
comptime user_fn: ModuleFn,
comptime specifier: []const u8,
comptime required_capabilities: []const ModuleCapability,
) object.NativeFn {
return struct {
fn call(ctx_ptr: *anyopaque, this: value.JSValue, args: []const value.JSValue) anyerror!value.JSValue {
const token = pushActiveModuleContext(specifier, required_capabilities);
defer popActiveModuleContext(token);
return user_fn(@ptrCast(ctx_ptr), this, args);
}
}.call;
}
// -------------------------------------------------------------------------
// ModuleHandle free functions (the sandbox API)
// -------------------------------------------------------------------------
/// Cast a ModuleHandle to the underlying Context. Internal use only -
/// this function is called by the SDK free functions below, never by
/// module authors directly.
pub fn handleToContext(handle: *ModuleHandle) *context.Context {
return @ptrCast(@alignCast(handle));
}
pub fn contextToHandle(ctx: *context.Context) *ModuleHandle {
return @ptrCast(ctx);
}
fn activeContextHasCapability(capability: ModuleCapability) bool {
const active = active_module_context orelse return false;
for (active.required_capabilities) |candidate| {
if (candidate == capability) return true;
}
return false;
}
pub fn hasCapability(handle: *ModuleHandle, capability: ModuleCapability) bool {
_ = handle;
return activeContextHasCapability(capability);
}
pub const ModuleCapabilityError = error{MissingModuleCapability};
pub fn requireCapability(_: *ModuleHandle, capability: ModuleCapability) ModuleCapabilityError!void {
if (activeContextHasCapability(capability)) return;
return error.MissingModuleCapability;
}
pub fn pushActiveModuleContext(
specifier: []const u8,
required_capabilities: []const ModuleCapability,
) ActiveModuleToken {
const prev = active_module_context;
active_module_context = .{
.specifier = specifier,
.required_capabilities = required_capabilities,
};
return .{ .previous = prev };
}
pub fn popActiveModuleContext(token: ActiveModuleToken) void {
active_module_context = token.previous;
}
/// Create a new JS string value. Ownership transfers to the GC.
pub fn createString(handle: *ModuleHandle, data: []const u8) !value.JSValue {
const ctx = handleToContext(handle);
return ctx.createString(data);
}
/// Extract a borrowed string slice from a JSValue.
/// The returned slice is valid only during the current function call.
pub fn extractString(val: value.JSValue) ?[]const u8 {
const str = val.toStringStruct() orelse return null;
return str.asSlice();
}
pub fn extractInt(val: value.JSValue) ?i32 {
return val.toInt();
}
pub fn extractFloat(val: value.JSValue) ?f64 {
return val.toFloat();
}
/// Create a Result object: { ok: true, value: payload }
pub fn resultOk(handle: *ModuleHandle, payload: value.JSValue) !value.JSValue {
const ctx = handleToContext(handle);
const util = @import("modules/internal/util.zig");
return util.createPlainResultOk(ctx, payload);
}
/// Create a Result object: { ok: false, error: message }
pub fn resultErr(handle: *ModuleHandle, message: []const u8) !value.JSValue {
const ctx = handleToContext(handle);
const util = @import("modules/internal/util.zig");
return util.createPlainResultErr(ctx, message);
}
/// Create a Result object: { ok: false, error: payload }
pub fn resultErrValue(handle: *ModuleHandle, payload: value.JSValue) !value.JSValue {
const ctx = handleToContext(handle);
const util = @import("modules/internal/util.zig");
return util.createPlainResultErrValue(ctx, payload);
}
/// Create a Result object: { ok: false, errors: payload }
pub fn resultErrs(handle: *ModuleHandle, payload: value.JSValue) !value.JSValue {
const ctx = handleToContext(handle);
const util = @import("modules/internal/util.zig");
return util.createPlainResultErrs(ctx, payload);
}
/// Throw a JS error. Sets ctx.exception and returns exception_val.
pub fn throwError(handle: *ModuleHandle, name: []const u8, message: []const u8) value.JSValue {
const ctx = handleToContext(handle);
const util = @import("modules/internal/util.zig");
return util.throwError(ctx, name, message);
}
/// Get typed module state from a slot. Returns null if not initialized.
pub fn getState(handle: *ModuleHandle, comptime T: type, slot: usize) ?*T {
const ctx = handleToContext(handle);
return ctx.getModuleState(T, slot);
}
/// Set module state in a slot with a cleanup callback.
pub fn setState(
handle: *ModuleHandle,
slot: usize,
ptr: *anyopaque,
deinit_fn: *const fn (*anyopaque, std.mem.Allocator) void,
) void {
const ctx = handleToContext(handle);
ctx.setModuleState(slot, ptr, deinit_fn);
}
/// Get the runtime allocator for persistent allocations.
pub fn getAllocator(handle: *ModuleHandle) std.mem.Allocator {
const ctx = handleToContext(handle);
return ctx.allocator;
}
pub const ActiveCapabilityError = ModuleCapabilityError || error{
ClockUnavailable,
StderrWriteFailed,
};
fn currentActiveModuleSpecifier() []const u8 {
return if (active_module_context) |active| active.specifier else "<no-active-module>";
}
fn requireActiveCapability(capability: ModuleCapability) ActiveCapabilityError!void {
if (activeContextHasCapability(capability)) return;
return error.MissingModuleCapability;
}
fn panicCapabilityError(err: ActiveCapabilityError, capability: ModuleCapability) noreturn {
const spec = currentActiveModuleSpecifier();
switch (err) {
error.MissingModuleCapability => std.debug.panic(
"module '{s}' used undeclared capability '{s}'",
.{ spec, @tagName(capability) },
),
error.ClockUnavailable => std.debug.panic(
"module '{s}' failed to access clock capability",
.{spec},
),
error.StderrWriteFailed => std.debug.panic(
"module '{s}' failed to write to stderr capability",
.{spec},
),
}
}
pub fn nowMsForActiveModule() ActiveCapabilityError!i64 {
try requireActiveCapability(.clock);
return compat.realtimeNowMs() catch error.ClockUnavailable;
}
pub fn nowNsForActiveModule() ActiveCapabilityError!u64 {
try requireActiveCapability(.clock);
return compat.realtimeNowNs() catch error.ClockUnavailable;
}
pub fn clockNowMsChecked() i64 {
return nowMsForActiveModule() catch |err| panicCapabilityError(err, .clock);
}
pub fn clockNowNsChecked() u64 {
return nowNsForActiveModule() catch |err| panicCapabilityError(err, .clock);
}
pub fn clockNowSecsChecked() i64 {
return @divTrunc(clockNowMsChecked(), 1000);
}
pub fn fillRandomForActiveModule(buf: []u8) ActiveCapabilityError!void {
try requireActiveCapability(.random);
if (buf.len == 0) return;
if (sdk_prng == null) {
const seed = std.hash.Wyhash.hash(0, currentActiveModuleSpecifier()) ^
@as(u64, @bitCast(nowNsForActiveModule() catch 0));
sdk_prng = std.Random.DefaultPrng.init(seed);
}
var rng = sdk_prng.?.random();
rng.bytes(buf);
}
pub fn fillRandomChecked(buf: []u8) void {
fillRandomForActiveModule(buf) catch |err| panicCapabilityError(err, .random);
}
pub fn writeStderrForActiveModule(buf: []const u8) ActiveCapabilityError!void {
try requireActiveCapability(.stderr);
if (buf.len == 0) return;
const written = std.c.write(std.c.STDERR_FILENO, buf.ptr, buf.len);
if (written != @as(isize, @intCast(buf.len))) return error.StderrWriteFailed;
}
pub fn writeStderrChecked(buf: []const u8) void {
writeStderrForActiveModule(buf) catch |err| panicCapabilityError(err, .stderr);
}
pub fn runtimeCallbackCapabilityChecked() void {
requireActiveCapability(.runtime_callback) catch |err| panicCapabilityError(err, .runtime_callback);
}
pub fn getRuntimeCallbackStateChecked(
ctx: *context.Context,
comptime T: type,
slot: usize,
) ?*T {
runtimeCallbackCapabilityChecked();
return ctx.getModuleState(T, slot);
}
pub fn readFileChecked(
allocator: std.mem.Allocator,
path: []const u8,
max_size: usize,
) ![]u8 {
requireActiveCapability(.filesystem) catch |err| panicCapabilityError(err, .filesystem);
return file_io.readFile(allocator, path, max_size);
}
pub fn readEnvForActiveModule(name_z: [:0]const u8) ActiveCapabilityError!?[]const u8 {
try requireActiveCapability(.env);
const result = std.c.getenv(name_z) orelse return null;
return std.mem.sliceTo(result, 0);
}
pub fn readEnvChecked(name_z: [:0]const u8) ?[]const u8 {
return readEnvForActiveModule(name_z) catch |err| panicCapabilityError(err, .env);
}
pub fn sqliteCapabilityChecked() void {
requireActiveCapability(.sqlite) catch |err| panicCapabilityError(err, .sqlite);
}
pub fn getSqliteStateChecked(
ctx: *context.Context,
comptime T: type,
slot: usize,
) ?*T {
sqliteCapabilityChecked();
return ctx.getModuleState(T, slot);
}
pub fn openSqliteDbChecked(
allocator: std.mem.Allocator,
path: []const u8,
) !sqlite_runtime.Db {
sqliteCapabilityChecked();
return sqlite_runtime.Db.openReadWriteCreate(allocator, path);
}
pub fn hmacSha256ForActiveModule(
out: *[std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8,
data: []const u8,
key: []const u8,
) ActiveCapabilityError!void {
try requireActiveCapability(.crypto);
std.crypto.auth.hmac.sha2.HmacSha256.create(out, data, key);
}
pub fn sha256ForActiveModule(
out: *[std.crypto.hash.sha2.Sha256.digest_length]u8,
data: []const u8,
) ActiveCapabilityError!void {
try requireActiveCapability(.crypto);
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
hasher.update(data);
out.* = hasher.finalResult();
}
pub fn sha256Checked(
out: *[std.crypto.hash.sha2.Sha256.digest_length]u8,
data: []const u8,
) void {
sha256ForActiveModule(out, data) catch |err| panicCapabilityError(err, .crypto);
}
pub fn hmacSha256Checked(
out: *[std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8,
data: []const u8,
key: []const u8,
) void {
hmacSha256ForActiveModule(out, data, key) catch |err| panicCapabilityError(err, .crypto);
}
fn emitPolicyDenial(kind: security_events.SecurityEventKind, name: []const u8) void {
security_events.emitGlobal(security_events.SecurityEvent.init(
kind,
currentActiveModuleSpecifier(),
name,
));
}
pub fn allowsCacheNamespaceForActiveModule(
ctx: *context.Context,
ns: []const u8,
) ActiveCapabilityError!bool {
try requireActiveCapability(.policy_check);
const allowed = ctx.capability_policy.allowsCacheNamespace(ns);
if (!allowed) emitPolicyDenial(.policy_denied_cache, ns);
return allowed;
}
pub fn allowsCacheNamespaceChecked(ctx: *context.Context, ns: []const u8) bool {
return allowsCacheNamespaceForActiveModule(ctx, ns) catch |err| panicCapabilityError(err, .policy_check);
}
pub fn allowsEnvForActiveModule(
ctx: *context.Context,
name: []const u8,
) ActiveCapabilityError!bool {
try requireActiveCapability(.policy_check);
const allowed = ctx.capability_policy.allowsEnv(name);
if (!allowed) emitPolicyDenial(.policy_denied_env, name);
return allowed;
}
pub fn allowsEnvChecked(ctx: *context.Context, name: []const u8) bool {
return allowsEnvForActiveModule(ctx, name) catch |err| panicCapabilityError(err, .policy_check);
}
pub fn allowsSqlQueryForActiveModule(
ctx: *context.Context,
name: []const u8,
) ActiveCapabilityError!bool {
try requireActiveCapability(.policy_check);
const allowed = ctx.capability_policy.allowsSqlQuery(name);
if (!allowed) emitPolicyDenial(.policy_denied_sql, name);
return allowed;
}
pub fn allowsSqlQueryChecked(ctx: *context.Context, name: []const u8) bool {
return allowsSqlQueryForActiveModule(ctx, name) catch |err| panicCapabilityError(err, .policy_check);
}
pub fn allowsSqlWriteForActiveModule(
ctx: *context.Context,
name: []const u8,
) ActiveCapabilityError!bool {
try requireActiveCapability(.policy_check);
const allowed = ctx.capability_policy.allowsSqlWrite(name);
if (!allowed) {
// Phase 1 dual-emit: legacy per-module event for existing JSONL
// consumers, generic policy_denied for spec section 12 shape.
// Phase 4 deprecates the legacy kinds once consumers migrate.
emitPolicyDenial(.policy_denied_sql, name);
const policy = @import("policy.zig");
policy.emitDenied(.{
.action = .db_write,
.resource = .{ .kind = policy.resource_kind_sql_query, .id = name },
}, .not_in_allowlist);
}
return allowed;
}
pub fn allowsSqlWriteChecked(ctx: *context.Context, name: []const u8) bool {
return allowsSqlWriteForActiveModule(ctx, name) catch |err| panicCapabilityError(err, .policy_check);
}
pub export fn zigttpSdkHasCapability(handle: *ModuleHandle, capability_tag: u8) bool {
if (capability_tag > @intFromEnum(ModuleCapability.websocket)) return false;
const capability: ModuleCapability = @enumFromInt(capability_tag);
return hasCapability(handle, capability);
}
pub export fn zigttpSdkNowMs(handle: *ModuleHandle, out_ms: *i64) bool {
_ = handle;
out_ms.* = nowMsForActiveModule() catch return false;
return true;
}
pub export fn zigttpSdkFillRandom(handle: *ModuleHandle, buf_ptr: [*]u8, len: usize) void {
_ = handle;
if (len == 0) return;
fillRandomForActiveModule(buf_ptr[0..len]) catch {};
}
pub export fn zigttpSdkWriteStderr(handle: *ModuleHandle, buf_ptr: [*]const u8, len: usize) bool {
_ = handle;
if (len == 0) return true;
writeStderrForActiveModule(buf_ptr[0..len]) catch return false;
return true;
}
// SDK bridge: handle-bound runtime operations. JSValue crosses the ABI
// directly because zigts's value.JSValue and sdk.JSValue are packed
// struct(u64) with layout equivalence verified in module_binding_adapter.
const util_mod = @import("modules/internal/util.zig");
pub export fn zigttpSdkExtractString(val: value.JSValue, out_ptr: *[*]const u8, out_len: *usize) bool {
const slice = util_mod.extractString(val) orelse return false;
out_ptr.* = slice.ptr;
out_len.* = slice.len;
return true;
}
pub export fn zigttpSdkCreateString(handle: *ModuleHandle, ptr: [*]const u8, len: usize, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
out.* = ctx.createString(ptr[0..len]) catch return false;
return true;
}
pub export fn zigttpSdkCreateObject(handle: *ModuleHandle, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
const obj = ctx.createObject(ctx.object_prototype) catch return false;
out.* = obj.toValue();
return true;
}
pub export fn zigttpSdkObjectSet(
handle: *ModuleHandle,
obj_val: value.JSValue,
key_ptr: [*]const u8,
key_len: usize,
val: value.JSValue,
) bool {
const ctx = handleToContext(handle);
if (!obj_val.isObject()) return false;
const obj = obj_val.toPtr(object.JSObject);
const atom = ctx.atoms.intern(key_ptr[0..key_len]) catch return false;
ctx.setPropertyChecked(obj, atom, val) catch return false;
return true;
}
pub export fn zigttpSdkObjectGet(
handle: *ModuleHandle,
obj_val: value.JSValue,
key_ptr: [*]const u8,
key_len: usize,
out: *value.JSValue,
) bool {
const ctx = handleToContext(handle);
if (!obj_val.isObject()) return false;
const obj = obj_val.toPtr(object.JSObject);
const atom = ctx.atoms.intern(key_ptr[0..key_len]) catch return false;
const pool = ctx.hidden_class_pool orelse return false;
out.* = obj.getProperty(pool, atom) orelse return false;
return true;
}
pub export fn zigttpSdkThrowError(
handle: *ModuleHandle,
name_ptr: [*]const u8,
name_len: usize,
msg_ptr: [*]const u8,
msg_len: usize,
) value.JSValue {
const ctx = handleToContext(handle);
return util_mod.throwError(ctx, name_ptr[0..name_len], msg_ptr[0..msg_len]);
}
pub export fn zigttpSdkResultOk(handle: *ModuleHandle, payload: value.JSValue, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
out.* = util_mod.createPlainResultOk(ctx, payload) catch return false;
return true;
}
pub export fn zigttpSdkResultErr(
handle: *ModuleHandle,
msg_ptr: [*]const u8,
msg_len: usize,
out: *value.JSValue,
) bool {
const ctx = handleToContext(handle);
out.* = util_mod.createPlainResultErr(ctx, msg_ptr[0..msg_len]) catch return false;
return true;
}
pub export fn zigttpSdkResultErrValue(handle: *ModuleHandle, payload: value.JSValue, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
out.* = util_mod.createPlainResultErrValue(ctx, payload);
return true;
}
pub export fn zigttpSdkResultErrs(handle: *ModuleHandle, payload: value.JSValue, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
out.* = util_mod.createPlainResultErrs(ctx, payload) catch return false;
return true;
}
pub export fn zigttpSdkGetAllocator(handle: *ModuleHandle) *const std.mem.Allocator {
const ctx = handleToContext(handle);
return &ctx.allocator;
}
pub export fn zigttpSdkSha256(
data_ptr: [*]const u8,
data_len: usize,
out: [*]u8,
) bool {
sha256ForActiveModule(@ptrCast(out[0..32]), data_ptr[0..data_len]) catch return false;
return true;
}
pub export fn zigttpSdkHmacSha256(
data_ptr: [*]const u8,
data_len: usize,
key_ptr: [*]const u8,
key_len: usize,
out: [*]u8,
) bool {
hmacSha256ForActiveModule(@ptrCast(out[0..32]), data_ptr[0..data_len], key_ptr[0..key_len]) catch return false;
return true;
}
pub export fn zigttpSdkParseJson(
handle: *ModuleHandle,
json_ptr: [*]const u8,
json_len: usize,
out: *value.JSValue,
) bool {
const ctx = handleToContext(handle);
const json = @import("builtins/json.zig");
out.* = json.parseJsonValue(ctx, json_ptr[0..json_len]) catch return false;
return true;
}
// SDK module-state envelope. The C-ABI deinit callback SDK modules provide
// takes only the state pointer (std.mem.Allocator is not C-ABI stable).
// Zigts wraps the envelope so the Context's internal deinit_fn signature
// stays unchanged; modules store their own allocator inside their state.
const SdkStateEnvelope = struct {
user_ptr: *anyopaque,
sdk_deinit: *const fn (*anyopaque) callconv(.c) void,
allocator: std.mem.Allocator,
fn envelopeDeinit(ptr: *anyopaque, _: std.mem.Allocator) void {
const env: *SdkStateEnvelope = @ptrCast(@alignCast(ptr));
env.sdk_deinit(env.user_ptr);
env.allocator.destroy(env);
}
};
pub export fn zigttpSdkGetModuleState(handle: *ModuleHandle, slot: usize) ?*anyopaque {
const ctx = handleToContext(handle);
return getSdkModuleStatePtr(ctx, slot);
}
pub export fn zigttpSdkSetModuleState(
handle: *ModuleHandle,
slot: usize,
user_ptr: *anyopaque,
sdk_deinit: *const fn (*anyopaque) callconv(.c) void,
) bool {
const ctx = handleToContext(handle);
installSdkModuleState(ctx, slot, user_ptr, sdk_deinit) catch return false;
return true;
}
/// Read an SDK-installed module state pointer from a slot. Returns the
/// user pointer stashed inside the envelope, or null if the slot is empty.
/// Use this from zigts-internal bootstrap code (e.g. `installStore`) that
/// needs to reach modules living in peer packages through the SDK boundary.
pub fn getSdkModuleStatePtr(ctx: *context.Context, slot: usize) ?*anyopaque {
const env = ctx.getModuleState(SdkStateEnvelope, slot) orelse return null;
return env.user_ptr;
}
/// Install an SDK-layout module state envelope from the zigts side of the
/// peer-package boundary. Required whenever the runtime pre-installs state
/// for a module that reads via the SDK's `getModuleState` (which unwraps an
/// `SdkStateEnvelope`); writing a bare pointer would leave the module
/// reading the envelope bytes as user state.
pub fn installSdkModuleState(
ctx: *context.Context,
slot: usize,
user_ptr: *anyopaque,
sdk_deinit: *const fn (*anyopaque) callconv(.c) void,
) !void {
const env = try ctx.allocator.create(SdkStateEnvelope);
env.* = .{ .user_ptr = user_ptr, .sdk_deinit = sdk_deinit, .allocator = ctx.allocator };
ctx.setModuleState(slot, env, SdkStateEnvelope.envelopeDeinit);
}
pub export fn zigttpSdkIsCallable(val: value.JSValue) bool {
return val.isCallable();
}
pub export fn zigttpSdkReadFile(
handle: *ModuleHandle,
path_ptr: [*]const u8,
path_len: usize,
max_size: usize,
out_ptr: *[*]u8,
out_len: *usize,
) bool {
const ctx = handleToContext(handle);
const buf = readFileChecked(ctx.allocator, path_ptr[0..path_len], max_size) catch return false;
out_ptr.* = buf.ptr;
out_len.* = buf.len;
return true;
}
pub export fn zigttpSdkIsString(val: value.JSValue) bool {
return val.isStringOrRope();
}
pub export fn zigttpSdkIsObject(val: value.JSValue) bool {
return val.isObject();
}
pub export fn zigttpSdkIsArray(val: value.JSValue) bool {
return val.isArray();
}
pub export fn zigttpSdkArrayLength(val: value.JSValue, out: *u32) bool {
if (!val.isArray()) return false;
const arr = val.toPtr(object.JSObject);
out.* = arr.getArrayLength();
return true;
}
pub export fn zigttpSdkArrayGet(handle: *ModuleHandle, arr_val: value.JSValue, index: u32, out: *value.JSValue) bool {
_ = handle;
if (!arr_val.isArray()) return false;
const arr = arr_val.toPtr(object.JSObject);
out.* = arr.getIndex(index) orelse return false;
return true;
}
pub export fn zigttpSdkArraySet(handle: *ModuleHandle, arr_val: value.JSValue, index: u32, val: value.JSValue) bool {
const ctx = handleToContext(handle);
if (!arr_val.isArray()) return false;
const arr = arr_val.toPtr(object.JSObject);
ctx.setIndexChecked(arr, index, val) catch return false;
return true;
}
pub export fn zigttpSdkCreateArray(handle: *ModuleHandle, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
const arr = ctx.createArray() catch return false;
out.* = arr.toValue();
return true;
}
pub export fn zigttpSdkStringify(handle: *ModuleHandle, val: value.JSValue, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
const http_mod = @import("http.zig");
const js_str = http_mod.valueToJsonString(ctx, val) catch return false;
out.* = value.JSValue.fromPtr(js_str);
return true;
}
pub export fn zigttpSdkObjectKeys(handle: *ModuleHandle, obj_val: value.JSValue, out: *value.JSValue) bool {
const ctx = handleToContext(handle);
if (!obj_val.isObject()) return false;
const obj = obj_val.toPtr(object.JSObject);
const pool = ctx.hidden_class_pool orelse return false;
const atoms = obj.getOwnEnumerableKeys(ctx.allocator, pool) catch return false;
defer ctx.allocator.free(atoms);
const arr = ctx.createArray() catch return false;
for (atoms, 0..) |atom, i| {
const name = util_mod.atomToString(atom, &ctx.atoms) orelse continue;
const name_val = ctx.createString(name) catch return false;
ctx.setIndexChecked(arr, @intCast(i), name_val) catch return false;
}
out.* = arr.toValue();
return true;
}
pub export fn zigttpSdkReadEnv(
handle: *ModuleHandle,
name_ptr: [*]const u8,
name_len: usize,
out_ptr: *[*]const u8,
out_len: *usize,
) bool {
_ = handle;
if (name_len >= 256) return false;
var buf: [256]u8 = undefined;
@memcpy(buf[0..name_len], name_ptr[0..name_len]);
buf[name_len] = 0;
const result = readEnvChecked(buf[0..name_len :0]) orelse return false;
out_ptr.* = result.ptr;
out_len.* = result.len;
return true;
}
pub export fn zigttpSdkAllowsEnv(
handle: *ModuleHandle,
name_ptr: [*]const u8,
name_len: usize,
) bool {
const ctx = handleToContext(handle);
return allowsEnvChecked(ctx, name_ptr[0..name_len]);
}
pub export fn zigttpSdkAllowsCacheNamespace(
handle: *ModuleHandle,
ns_ptr: [*]const u8,
ns_len: usize,
) bool {
const ctx = handleToContext(handle);
return allowsCacheNamespaceChecked(ctx, ns_ptr[0..ns_len]);
}
pub export fn zigttpSdkAllowsSqlQuery(
handle: *ModuleHandle,
name_ptr: [*]const u8,
name_len: usize,
) bool {
const ctx = handleToContext(handle);
return allowsSqlQueryChecked(ctx, name_ptr[0..name_len]);
}
pub export fn zigttpSdkAllowsSqlWrite(
handle: *ModuleHandle,
name_ptr: [*]const u8,
name_len: usize,
) bool {
const ctx = handleToContext(handle);
return allowsSqlWriteChecked(ctx, name_ptr[0..name_len]);
}
pub export fn zigttpSdkArrayPush(
handle: *ModuleHandle,
arr_val: value.JSValue,
val: value.JSValue,
) bool {
const ctx = handleToContext(handle);
if (!arr_val.isArray()) return false;
const arr = arr_val.toPtr(object.JSObject);
arr.arrayPush(ctx.allocator, val) catch return false;
return true;
}
// -------------------------------------------------------------------------
// SQLite bridge. Opaque handles are the raw sqlite3 / sqlite3_stmt
// pointers; the runtime owns their lifetime until close/finalize.
// -------------------------------------------------------------------------
const SdkSqliteDb = opaque {};
const SdkSqliteStmt = opaque {};
pub export fn zigttpSdkSqliteOpen(
handle: *ModuleHandle,
path_ptr: [*]const u8,
path_len: usize,
out: **SdkSqliteDb,
) bool {
const ctx = handleToContext(handle);
const db = openSqliteDbChecked(ctx.allocator, path_ptr[0..path_len]) catch return false;
out.* = @ptrCast(db.handle);
return true;
}
pub export fn zigttpSdkSqliteClose(opaque_db: *SdkSqliteDb) void {
const raw: *sqlite_runtime.c.sqlite3 = @ptrCast(@alignCast(opaque_db));
_ = sqlite_runtime.c.sqlite3_close(raw);
}
pub export fn zigttpSdkSqliteChanges(opaque_db: *SdkSqliteDb) i32 {
const raw: *sqlite_runtime.c.sqlite3 = @ptrCast(@alignCast(opaque_db));
return sqlite_runtime.c.sqlite3_changes(raw);
}
pub export fn zigttpSdkSqliteLastInsertRowId(opaque_db: *SdkSqliteDb) i64 {
const raw: *sqlite_runtime.c.sqlite3 = @ptrCast(@alignCast(opaque_db));
return sqlite_runtime.c.sqlite3_last_insert_rowid(raw);
}
pub export fn zigttpSdkSqliteErrmsg(
opaque_db: *SdkSqliteDb,
out_ptr: *[*]const u8,
out_len: *usize,
) void {
const raw: *sqlite_runtime.c.sqlite3 = @ptrCast(@alignCast(opaque_db));
const msg = std.mem.span(sqlite_runtime.c.sqlite3_errmsg(raw));
out_ptr.* = msg.ptr;
out_len.* = msg.len;
}
pub export fn zigttpSdkSqlitePrepare(
opaque_db: *SdkSqliteDb,
sql_ptr: [*]const u8,
sql_len: usize,
out: **SdkSqliteStmt,
) bool {
const raw_db: *sqlite_runtime.c.sqlite3 = @ptrCast(@alignCast(opaque_db));
var stmt: ?*sqlite_runtime.c.sqlite3_stmt = null;
const rc = sqlite_runtime.c.sqlite3_prepare_v2(raw_db, sql_ptr, @intCast(sql_len), &stmt, null);
if (rc != sqlite_runtime.c.SQLITE_OK or stmt == null) return false;
out.* = @ptrCast(stmt.?);
return true;
}
pub export fn zigttpSdkSqliteFinalize(opaque_stmt: *SdkSqliteStmt) void {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
_ = sqlite_runtime.c.sqlite3_finalize(raw);
}
pub export fn zigttpSdkSqliteStep(opaque_stmt: *SdkSqliteStmt) i32 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_step(raw);
}
pub export fn zigttpSdkSqliteReadonly(opaque_stmt: *SdkSqliteStmt) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_stmt_readonly(raw) != 0;
}
pub export fn zigttpSdkSqliteStmtErrmsg(
opaque_stmt: *SdkSqliteStmt,
out_ptr: *[*]const u8,
out_len: *usize,
) void {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
const db = sqlite_runtime.c.sqlite3_db_handle(raw);
const msg = std.mem.span(sqlite_runtime.c.sqlite3_errmsg(db));
out_ptr.* = msg.ptr;
out_len.* = msg.len;
}
pub export fn zigttpSdkSqliteParamCount(opaque_stmt: *SdkSqliteStmt) u32 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return @intCast(sqlite_runtime.c.sqlite3_bind_parameter_count(raw));
}
pub export fn zigttpSdkSqliteParamName(
opaque_stmt: *SdkSqliteStmt,
index: u32,
out_ptr: *[*]const u8,
out_len: *usize,
) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
const c_name = sqlite_runtime.c.sqlite3_bind_parameter_name(raw, @intCast(index));
const normalized = sqlite_runtime.normalizeParamName(c_name) orelse return false;
out_ptr.* = normalized.ptr;
out_len.* = normalized.len;
return true;
}
pub export fn zigttpSdkSqliteBindNull(opaque_stmt: *SdkSqliteStmt, index: u32) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_bind_null(raw, @intCast(index)) == sqlite_runtime.c.SQLITE_OK;
}
pub export fn zigttpSdkSqliteBindInt64(opaque_stmt: *SdkSqliteStmt, index: u32, v: i64) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_bind_int64(raw, @intCast(index), v) == sqlite_runtime.c.SQLITE_OK;
}
pub export fn zigttpSdkSqliteBindDouble(opaque_stmt: *SdkSqliteStmt, index: u32, v: f64) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_bind_double(raw, @intCast(index), v) == sqlite_runtime.c.SQLITE_OK;
}
pub export fn zigttpSdkSqliteBindText(
opaque_stmt: *SdkSqliteStmt,
index: u32,
ptr: [*]const u8,
len: usize,
) bool {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_bind_text(raw, @intCast(index), ptr, @intCast(len), null) == sqlite_runtime.c.SQLITE_OK;
}
pub export fn zigttpSdkSqliteColumnCount(opaque_stmt: *SdkSqliteStmt) u32 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return @intCast(sqlite_runtime.c.sqlite3_column_count(raw));
}
pub export fn zigttpSdkSqliteColumnName(
opaque_stmt: *SdkSqliteStmt,
index: u32,
out_ptr: *[*]const u8,
out_len: *usize,
) void {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
const c_name = sqlite_runtime.c.sqlite3_column_name(raw, @intCast(index));
const name = if (c_name) |p| std.mem.span(p) else "";
out_ptr.* = name.ptr;
out_len.* = name.len;
}
pub export fn zigttpSdkSqliteColumnType(opaque_stmt: *SdkSqliteStmt, index: u32) i32 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_column_type(raw, @intCast(index));
}
pub export fn zigttpSdkSqliteColumnInt64(opaque_stmt: *SdkSqliteStmt, index: u32) i64 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_column_int64(raw, @intCast(index));
}
pub export fn zigttpSdkSqliteColumnDouble(opaque_stmt: *SdkSqliteStmt, index: u32) f64 {
const raw: *sqlite_runtime.c.sqlite3_stmt = @ptrCast(@alignCast(opaque_stmt));
return sqlite_runtime.c.sqlite3_column_double(raw, @intCast(index));
}