Add ScriptBehavior DSL: data-driven, non-Turing-complete UGC scripting
Implements the DSL that docs/architecture/scripting_sandbox.md recommends
as the primary (and, for now, sufficient) approach in place of running
untrusted GDScript in-process: a fixed set of trigger/condition/action
verbs, expressed as plain JSON data, interpreted by trusted GDScript with
zero ability to reference engine singletons, call arbitrary methods, or
execute code.
- ScriptBehavior (scripts/scripting/script_behavior.gd): parses and
validates rules from JSON/Dictionary data. Every trigger, condition
type/op, and verb is checked against an explicit whitelist at parse
time; malformed or unknown entries are dropped and recorded in
rejected_rules, never partially executed. Carries an optional
content_flags passthrough so this data type isn't hostile to future
moderation-queue integration (docs/architecture/content_moderation.md).
- ScriptInterpreterNode (scripts/scripting/script_interpreter.gd): the
only code that executes rules. Triggers: on_interact (proximity +
"interact" input action), on_enter (edge-triggered Area3D overlap),
on_touch (continuous overlap), on_timer (physics-clocked Timer). Verbs:
give_item, play_sound, move, rotate, spawn_from_catalog, set_timer --
each a fixed, hand-written function; verb dispatch is an explicit
match(), never call()-by-name from data. move/rotate animate via Tween
rather than teleporting.
- PlayerInventory (scripts/scripting/player_inventory.gd): a small
per-player item-count stub for give_item to target, since no real
inventory/entity-state system exists yet (M9 Economy). Attached to
scenes/player.tscn as "Inventory".
- SpawnCatalog (scripts/scripting/spawn_catalog.gd): trusted catalog_id ->
asset_id lookup for spawn_from_catalog, mirroring the AvatarCatalog
data-driven-JSON convention. Rule data only ever supplies a catalog_id
key, never a resource path.
- Wired a real demo ("ScriptedChest") into scenes/worlds/test_level.tscn
with an on_interact rule (give_item + play_sound + rotate), plus an
"interact" input action (project.godot).
- scripts/smoke_test_script_behavior.gd: exercises every trigger type,
every verb, and every condition type against the real interpreter and
the wired demo scene, and proves unknown/malformed/unsafe rules
(unknown verb, unknown trigger, non-scalar smuggled arguments, etc.)
are rejected at parse time and never run -- 50/50 checks pass.
This commit is contained in:
@@ -0,0 +1,459 @@
|
||||
class_name ScriptInterpreterNode
|
||||
extends Node3D
|
||||
## Trusted interpreter for a [ScriptBehavior] attached to a world object.
|
||||
##
|
||||
## This is the **only** code that ever executes a ScriptBehavior's rules.
|
||||
## The rule data (ScriptBehavior / ScriptRule) is plain JSON-shaped
|
||||
## Dictionaries -- it is never handed to `eval`, never passed through
|
||||
## [Expression], and never used to call a method by a name that came from
|
||||
## the data. Every verb is dispatched through an explicit `match` in
|
||||
## [method _execute_action], and every argument reaches the engine only
|
||||
## after [ScriptBehavior] has validated it's a plain scalar / 3-vector and
|
||||
## this class has resolved it through a fixed, code-defined path (a
|
||||
## Dictionary lookup on a whitelisted catalog, a child node named
|
||||
## "Inventory", etc). There is no reachable path from rule data to
|
||||
## OS/FileAccess/networking/ClassDB/Callable. See
|
||||
## docs/architecture/scripting_sandbox.md §3.1 for the design rationale.
|
||||
##
|
||||
## ## Usage
|
||||
##
|
||||
## Attach this script directly to the Node3D that represents the object in
|
||||
## the scene (see the "ScriptedChest" node in scenes/worlds/test_level.tscn
|
||||
## for a worked example). Either set [member behavior_path] (loaded on
|
||||
## [method _ready]) or call [method set_behavior] directly with an
|
||||
## already-parsed [ScriptBehavior] (e.g. from tests).
|
||||
##
|
||||
## Triggers:
|
||||
## - `on_interact`: player presses the "interact" action while within
|
||||
## [member interact_radius] of this node.
|
||||
## - `on_enter`: fires once, edge-triggered, when a player's body starts
|
||||
## overlapping this node's trigger volume.
|
||||
## - `on_touch`: fires every physics frame while a player's body is
|
||||
## overlapping this node's trigger volume (continuous contact).
|
||||
## - `on_timer`: fires on a repeating interval regardless of any player,
|
||||
## via a dedicated [Timer] child per on_timer rule.
|
||||
|
||||
# Sibling scripting scripts are referenced via preload rather than by their
|
||||
# global class_name so this module parses correctly from a bare/cold
|
||||
# compile -- see the note in script_behavior.gd.
|
||||
const ScriptBehaviorClass := preload("res://scripts/scripting/script_behavior.gd")
|
||||
const SpawnCatalogClass := preload("res://scripts/scripting/spawn_catalog.gd")
|
||||
const PlayerInventoryClass := preload("res://scripts/scripting/player_inventory.gd")
|
||||
|
||||
## Emitted every time a verb actually executes, for observability/tests.
|
||||
## `args` is the normalized action Dictionary that was executed.
|
||||
signal verb_executed(verb: String, args: Dictionary)
|
||||
|
||||
## Emitted for every rule ScriptBehavior rejected at parse time (so callers
|
||||
## can surface this in an editor / moderation tool).
|
||||
signal rule_rejected(reason: String)
|
||||
|
||||
## JSON file to load the behavior from, if [member behavior] isn't set
|
||||
## directly before this node enters the tree.
|
||||
@export var behavior_path: String = ""
|
||||
|
||||
## How close (metres) a player must be for `on_interact` and to count as
|
||||
## "in range" for the interact input check.
|
||||
@export var interact_radius: float = 2.5
|
||||
|
||||
## Collision layer bit the player's body is on (see scenes/player.tscn --
|
||||
## Player.collision_layer = 2). Used as this node's trigger Area3D's
|
||||
## collision_mask so it only ever notices players, nothing else.
|
||||
@export var player_collision_mask: int = 2
|
||||
|
||||
## The parsed behavior this node interprets. Set directly (tests) or leave
|
||||
## null and set [member behavior_path] to load one on [method _ready].
|
||||
var behavior: ScriptBehaviorClass = null
|
||||
|
||||
var _area: Area3D = null
|
||||
var _players_in_range: Array[Node] = []
|
||||
var _entered_once: Dictionary = {} # body instance id (int) -> true
|
||||
|
||||
# Local, per-object whitelisted state store (see docs/architecture/
|
||||
# scripting_sandbox.md §4 open question re: static analysis of "what a
|
||||
# script can possibly do" -- flags/timers are always plain scalars here).
|
||||
var _flags: Dictionary = {} # name (String) -> scalar
|
||||
var _timers: Dictionary = {} # name (String) -> {"remaining": float, "active": bool}
|
||||
|
||||
var _timer_nodes: Array[Timer] = []
|
||||
var _spawn_catalog: SpawnCatalogClass = null
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func _ready() -> void:
|
||||
if behavior == null and not behavior_path.is_empty():
|
||||
behavior = ScriptBehaviorClass.load_from_file(behavior_path)
|
||||
_apply_loaded_behavior()
|
||||
|
||||
|
||||
## Assign an already-parsed behavior (e.g. from a test, or built inline
|
||||
## rather than loaded from a file). Safe to call before or after this node
|
||||
## enters the tree.
|
||||
func set_behavior(new_behavior: ScriptBehaviorClass) -> void:
|
||||
behavior = new_behavior
|
||||
if is_inside_tree():
|
||||
_apply_loaded_behavior()
|
||||
|
||||
|
||||
func _apply_loaded_behavior() -> void:
|
||||
if behavior == null:
|
||||
return
|
||||
for msg in behavior.rejected_rules:
|
||||
push_warning("ScriptInterpreterNode(%s): rejected rule -- %s" % [name, msg])
|
||||
rule_rejected.emit(msg)
|
||||
_setup_area()
|
||||
_setup_timers()
|
||||
|
||||
|
||||
func _setup_area() -> void:
|
||||
if _area != null:
|
||||
_area.queue_free()
|
||||
_area = null
|
||||
|
||||
_area = Area3D.new()
|
||||
_area.name = "_ScriptTriggerArea"
|
||||
_area.collision_layer = 0
|
||||
_area.collision_mask = player_collision_mask
|
||||
_area.monitoring = true
|
||||
_area.monitorable = false
|
||||
|
||||
var shape := CollisionShape3D.new()
|
||||
var sphere := SphereShape3D.new()
|
||||
sphere.radius = interact_radius
|
||||
shape.shape = sphere
|
||||
_area.add_child(shape)
|
||||
|
||||
add_child(_area)
|
||||
_area.body_entered.connect(_on_body_entered)
|
||||
_area.body_exited.connect(_on_body_exited)
|
||||
|
||||
|
||||
func _setup_timers() -> void:
|
||||
for t in _timer_nodes:
|
||||
if is_instance_valid(t):
|
||||
t.queue_free()
|
||||
_timer_nodes.clear()
|
||||
|
||||
if behavior == null:
|
||||
return
|
||||
for rule in behavior.rules:
|
||||
if rule.trigger_type != "on_timer":
|
||||
continue
|
||||
var timer := Timer.new()
|
||||
timer.wait_time = rule.trigger_interval
|
||||
timer.autostart = true
|
||||
timer.one_shot = false
|
||||
# Tied to the fixed physics step (not idle/process delta) so
|
||||
# on_timer fires deterministically off the simulation clock,
|
||||
# matching physics_ticks_per_second (see project.godot §physics)
|
||||
# rather than however fast the host happens to be rendering.
|
||||
timer.process_callback = Timer.TIMER_PROCESS_PHYSICS
|
||||
add_child(timer)
|
||||
timer.timeout.connect(_on_rule_timer_timeout.bind(rule))
|
||||
_timer_nodes.append(timer)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Trigger sources
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func _is_player_body(body: Node) -> bool:
|
||||
# Player carries a global class_name (scripts/player.gd); this stays a
|
||||
# plain `is` check against a known engine/script type, never a
|
||||
# data-driven dispatch.
|
||||
return body is CharacterBody3D and body.has_node("Inventory")
|
||||
|
||||
|
||||
func _on_body_entered(body: Node) -> void:
|
||||
if not _is_player_body(body):
|
||||
return
|
||||
if not _players_in_range.has(body):
|
||||
_players_in_range.append(body)
|
||||
var id := body.get_instance_id()
|
||||
if not _entered_once.has(id):
|
||||
_entered_once[id] = true
|
||||
fire("on_enter", body)
|
||||
|
||||
|
||||
func _on_body_exited(body: Node) -> void:
|
||||
_players_in_range.erase(body)
|
||||
_entered_once.erase(body.get_instance_id())
|
||||
|
||||
|
||||
func _unhandled_input(event: InputEvent) -> void:
|
||||
if _players_in_range.is_empty():
|
||||
return
|
||||
if event.is_action_pressed("interact") and not event.is_echo():
|
||||
fire("on_interact", _players_in_range[0])
|
||||
|
||||
|
||||
func _on_rule_timer_timeout(rule) -> void:
|
||||
_fire_rule(rule, null)
|
||||
|
||||
|
||||
func _physics_process(delta: float) -> void:
|
||||
# Continuous on_touch contact -- checked every physics frame while
|
||||
# overlapping, unlike the edge-triggered on_enter above.
|
||||
if behavior != null and _area != null:
|
||||
for body in _area.get_overlapping_bodies():
|
||||
if _is_player_body(body):
|
||||
fire("on_touch", body)
|
||||
|
||||
# Tick down local timers set via the set_timer verb.
|
||||
for t_name in _timers.keys():
|
||||
var t: Dictionary = _timers[t_name]
|
||||
if t.get("active", false):
|
||||
t["remaining"] = maxf(0.0, float(t.get("remaining", 0.0)) - delta)
|
||||
if t["remaining"] <= 0.0:
|
||||
t["active"] = false
|
||||
_timers[t_name] = t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public firing API -- this is what every trigger source above calls, and
|
||||
# what a test can call directly to exercise a rule deterministically.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
## Fire every rule of the given trigger type whose conditions currently
|
||||
## hold, in order. `player` is the entity that caused the trigger (may be
|
||||
## null for `on_timer`, which has no player context).
|
||||
func fire(trigger_type: String, player: Node) -> void:
|
||||
if behavior == null:
|
||||
return
|
||||
for rule in behavior.rules:
|
||||
if rule.trigger_type == trigger_type:
|
||||
_fire_rule(rule, player)
|
||||
|
||||
|
||||
func _fire_rule(rule, player: Node) -> void:
|
||||
if not _conditions_met(rule.conditions, player):
|
||||
return
|
||||
for action in rule.actions:
|
||||
_execute_action(action, player)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Condition evaluation -- reads only the small whitelisted state store
|
||||
# (item counts via a player's Inventory, local flags, local timer state).
|
||||
# No expression evaluation, no arbitrary field access.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func _conditions_met(conditions: Array[Dictionary], player: Node) -> bool:
|
||||
for cond in conditions:
|
||||
if not _eval_condition(cond, player):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
func _eval_condition(cond: Dictionary, player: Node) -> bool:
|
||||
var op: String = cond.get("op", "")
|
||||
var expected: Variant = cond.get("value")
|
||||
var actual: Variant = null
|
||||
|
||||
match cond.get("type", ""):
|
||||
"item_count":
|
||||
var inv := _get_inventory(player)
|
||||
if inv == null:
|
||||
return false
|
||||
actual = inv.get_count(cond.get("item_id", ""))
|
||||
"flag":
|
||||
actual = _flags.get(cond.get("name", ""), false)
|
||||
"timer_active":
|
||||
var t: Dictionary = _timers.get(cond.get("name", ""), {})
|
||||
actual = t.get("active", false)
|
||||
"timer_remaining":
|
||||
var tr: Dictionary = _timers.get(cond.get("name", ""), {})
|
||||
actual = tr.get("remaining", 0.0)
|
||||
_:
|
||||
return false
|
||||
|
||||
return _compare(actual, op, expected)
|
||||
|
||||
|
||||
func _compare(actual: Variant, op: String, expected: Variant) -> bool:
|
||||
match op:
|
||||
"==":
|
||||
return actual == expected
|
||||
"!=":
|
||||
return actual != expected
|
||||
"<", "<=", ">", ">=":
|
||||
if not ((actual is int or actual is float) and (expected is int or expected is float)):
|
||||
return false
|
||||
var a: float = float(actual)
|
||||
var b: float = float(expected)
|
||||
match op:
|
||||
"<":
|
||||
return a < b
|
||||
"<=":
|
||||
return a <= b
|
||||
">":
|
||||
return a > b
|
||||
">=":
|
||||
return a >= b
|
||||
return false
|
||||
|
||||
|
||||
## Set a local flag on this object's whitelisted state store. Not driven by
|
||||
## any ScriptBehavior verb yet (the verb list in the task spec has no
|
||||
## setter) -- exposed for forward compatibility / tests exercising `flag`
|
||||
## conditions without needing a real gameplay event to set one.
|
||||
func set_flag(flag_name: String, value: Variant) -> void:
|
||||
if not (value is String or value is int or value is float or value is bool):
|
||||
return
|
||||
_flags[flag_name] = value
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Verb dispatch -- the entire attack surface this system deliberately does
|
||||
# NOT have. Every branch is a fixed, hand-written function; nothing here is
|
||||
# ever `call()`-ed by a name that came from data.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func _execute_action(action: Dictionary, player: Node) -> void:
|
||||
match action.get("verb", ""):
|
||||
"give_item":
|
||||
_act_give_item(action, player)
|
||||
"play_sound":
|
||||
_act_play_sound(action, player)
|
||||
"move":
|
||||
_act_move(action, player)
|
||||
"rotate":
|
||||
_act_rotate(action, player)
|
||||
"spawn_from_catalog":
|
||||
_act_spawn_from_catalog(action, player)
|
||||
"set_timer":
|
||||
_act_set_timer(action, player)
|
||||
_:
|
||||
# Unreachable in practice -- ScriptBehavior rejects unknown
|
||||
# verbs at parse time, so this branch should never see a rule
|
||||
# at all. Fail safe (do nothing) if it somehow does.
|
||||
push_warning("ScriptInterpreterNode(%s): refused to run unknown verb '%s'" % [name, str(action.get("verb"))])
|
||||
|
||||
|
||||
func _resolve_target(target: String, player: Node) -> Node3D:
|
||||
match target:
|
||||
"self":
|
||||
return self
|
||||
"player":
|
||||
return player if player is Node3D else null
|
||||
return null
|
||||
|
||||
|
||||
func _get_inventory(player: Node) -> PlayerInventoryClass:
|
||||
if player == null:
|
||||
return null
|
||||
var inv: Node = player.get_node_or_null("Inventory")
|
||||
if inv is PlayerInventoryClass:
|
||||
return inv as PlayerInventoryClass
|
||||
return null
|
||||
|
||||
|
||||
func _act_give_item(action: Dictionary, player: Node) -> void:
|
||||
var inv := _get_inventory(player)
|
||||
if inv == null:
|
||||
push_warning("ScriptInterpreterNode(%s): give_item has no player Inventory to target" % name)
|
||||
return
|
||||
inv.give_item(action.get("item_id", ""), int(action.get("count", 0)))
|
||||
verb_executed.emit("give_item", action)
|
||||
|
||||
|
||||
func _act_play_sound(action: Dictionary, _player: Node) -> void:
|
||||
# No real audio asset catalog exists in this repo yet. The verb still
|
||||
# runs through a real, trusted playback path -- attempting to resolve
|
||||
# and play a stream when one is registered -- so it's not a no-op
|
||||
# pretending to be a verb; it's just that today's trusted sound table
|
||||
# is empty. `sound_id` is only ever used as a key into that trusted,
|
||||
# code-defined table below, never as a path handed to load() directly.
|
||||
var sound_id: String = action.get("sound_id", "")
|
||||
var stream_path: String = _TRUSTED_SOUND_TABLE.get(sound_id, "")
|
||||
if not stream_path.is_empty() and ResourceLoader.exists(stream_path):
|
||||
var stream: Resource = load(stream_path)
|
||||
if stream is AudioStream:
|
||||
var player_node := AudioStreamPlayer3D.new()
|
||||
player_node.stream = stream
|
||||
add_child(player_node)
|
||||
player_node.finished.connect(player_node.queue_free)
|
||||
player_node.play()
|
||||
verb_executed.emit("play_sound", action)
|
||||
|
||||
|
||||
## Trusted, code-defined mapping from sound_id -> resource path. Rule data
|
||||
## supplies only the key; this table (not the data) decides what actually
|
||||
## plays. Empty for now -- no sound assets exist in this repo yet.
|
||||
const _TRUSTED_SOUND_TABLE: Dictionary = {}
|
||||
|
||||
|
||||
func _act_move(action: Dictionary, player: Node) -> void:
|
||||
var target_node := _resolve_target(action.get("target", "self"), player)
|
||||
if target_node == null:
|
||||
push_warning("ScriptInterpreterNode(%s): move has no valid target" % name)
|
||||
return
|
||||
var offset: Vector3 = action.get("offset", Vector3.ZERO)
|
||||
var duration: float = float(action.get("duration", ScriptBehaviorClass.DEFAULT_MOVE_DURATION))
|
||||
var dest: Vector3 = target_node.global_position + offset
|
||||
var tween := target_node.create_tween()
|
||||
tween.tween_property(target_node, "global_position", dest, duration)
|
||||
verb_executed.emit("move", action)
|
||||
|
||||
|
||||
func _act_rotate(action: Dictionary, player: Node) -> void:
|
||||
var target_node := _resolve_target(action.get("target", "self"), player)
|
||||
if target_node == null:
|
||||
push_warning("ScriptInterpreterNode(%s): rotate has no valid target" % name)
|
||||
return
|
||||
var degrees: float = float(action.get("degrees", 0.0))
|
||||
var axis: String = action.get("axis", "y")
|
||||
var duration: float = float(action.get("duration", ScriptBehaviorClass.DEFAULT_MOVE_DURATION))
|
||||
var delta_rot := Vector3.ZERO
|
||||
match axis:
|
||||
"x":
|
||||
delta_rot.x = degrees
|
||||
"y":
|
||||
delta_rot.y = degrees
|
||||
"z":
|
||||
delta_rot.z = degrees
|
||||
var dest: Vector3 = target_node.rotation_degrees + delta_rot
|
||||
var tween := target_node.create_tween()
|
||||
tween.tween_property(target_node, "rotation_degrees", dest, duration)
|
||||
verb_executed.emit("rotate", action)
|
||||
|
||||
|
||||
func _act_spawn_from_catalog(action: Dictionary, _player: Node) -> void:
|
||||
if _spawn_catalog == null:
|
||||
_spawn_catalog = SpawnCatalogClass.new()
|
||||
_spawn_catalog.load_catalog()
|
||||
var catalog_id: String = action.get("catalog_id", "")
|
||||
var entry: Dictionary = _spawn_catalog.resolve(catalog_id)
|
||||
if entry.is_empty():
|
||||
push_warning("ScriptInterpreterNode(%s): spawn_from_catalog unknown catalog_id '%s'" % [name, catalog_id])
|
||||
return
|
||||
|
||||
var asset_id: String = entry.get("asset_id", "")
|
||||
var position: Vector3 = action.get("position", Vector3.ZERO)
|
||||
|
||||
# Both WorldObject and DynamicObjectNode carry a global class_name and
|
||||
# are already relied on elsewhere in the project (scripts/chunk_scene.gd)
|
||||
# without preloading -- consistent with that existing convention.
|
||||
var obj := WorldObject.new(
|
||||
"spawned_%d" % Time.get_ticks_usec(), "prop", asset_id,
|
||||
position, Vector4(0, 0, 0, 1), Vector3.ONE, {}, true
|
||||
)
|
||||
var node := DynamicObjectNode.new()
|
||||
node.world_object = obj
|
||||
node.position = position
|
||||
node.name = "spawned_%s" % obj.id
|
||||
|
||||
var host := get_parent() if get_parent() != null else get_tree().current_scene
|
||||
if host != null:
|
||||
host.add_child(node)
|
||||
verb_executed.emit("spawn_from_catalog", action)
|
||||
|
||||
|
||||
func _act_set_timer(action: Dictionary, _player: Node) -> void:
|
||||
var timer_name: String = action.get("name", "")
|
||||
var seconds: float = float(action.get("seconds", 0.0))
|
||||
_timers[timer_name] = {"remaining": seconds, "active": true}
|
||||
verb_executed.emit("set_timer", action)
|
||||
Reference in New Issue
Block a user