"""Typed state, named events and reusable action parts for local browser programs. This part receives an explicit program shape. It does not reinterpret unknown behavior as a table, run arbitrary code, or invent a missing event binding. """ import copy import hashlib import html import itertools import json import math import os from pathlib import Path import re import secrets import tempfile import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class ProgramError(ValueError): def __init__(self, message, status=400): super().__init__(message) self.status = status class _StateFileLock: """Reentrant in-process ownership plus an OS lock shared by app processes. The persistent lock file is never removed. Ownership belongs to the open handle, so termination releases it without guessing whether a PID is alive. """ def __init__(self, path): self.path = Path(path) self.thread = threading.RLock() self.depth = 0 self.handle = None def __enter__(self): self.thread.acquire() try: if self.depth == 0: self.path.parent.mkdir(parents=True, exist_ok=True) self.handle = open(self.path, 'a+b', buffering=0) if os.fstat(self.handle.fileno()).st_size == 0: self.handle.write(b'\0') deadline = time.monotonic() + 30 while True: try: self.handle.seek(0) if os.name == 'nt': import msvcrt msvcrt.locking(self.handle.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(self.handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) break except OSError: if time.monotonic() >= deadline: raise ProgramError('saved state is busy in another process; refresh before retrying', 409) time.sleep(0.01) self.depth += 1 return self except BaseException: if self.depth == 0 and self.handle is not None: self.handle.close(); self.handle = None self.thread.release() raise def __exit__(self, *exc): try: self.depth -= 1 if self.depth == 0: try: self.handle.seek(0) if os.name == 'nt': import msvcrt msvcrt.locking(self.handle.fileno(), msvcrt.LK_UNLCK, 1) else: import fcntl fcntl.flock(self.handle.fileno(), fcntl.LOCK_UN) finally: self.handle.close(); self.handle = None finally: self.thread.release() _STATE_LOCKS = {} _STATE_LOCKS_GUARD = threading.Lock() def _state_file_lock(state_path, root): lock_path = Path(str(state_path) + '.lock').resolve() if Path(root).resolve() not in lock_path.parents: raise ProgramError('program state lock must stay inside the project folder') key = os.path.normcase(str(lock_path)) with _STATE_LOCKS_GUARD: return _STATE_LOCKS.setdefault(key, _StateFileLock(lock_path)) def _keys(value, allowed, required=(), where='shape'): if not isinstance(value, dict): raise ProgramError('%s must be a named shape' % where) extra, missing = set(value) - set(allowed), set(required) - set(value) if extra or missing: raise ProgramError('%s: unknown fields %s; missing fields %s' % (where, sorted(extra), sorted(missing))) def _name(name): if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,63}', name): raise ProgramError('names must be 1–64 letters, digits or underscores, starting with a letter') def _schema(schema, where, initial=False, depth=0): _keys(schema, ('type', 'initial', 'min', 'max', 'enum', 'items', 'label'), ('type', 'initial') if initial else ('type',), where) typ = schema['type'] if typ not in ('integer', 'number', 'string', 'boolean', 'array'): raise ProgramError('%s: type %r has no part yet' % (where, typ)) if depth > 2: raise ProgramError('%s: nested arrays beyond depth 2 need an explicit part' % where) if typ == 'array': if 'items' not in schema: raise ProgramError('%s needs the type of its items' % where) _schema(schema['items'], where + '.items', depth=depth + 1) elif 'items' in schema: raise ProgramError('%s: items belongs to an array' % where) for bound in ('min', 'max'): if bound in schema: val = schema[bound] if typ == 'boolean' or isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(val): raise ProgramError('%s: invalid %s bound' % (where, bound)) if typ in ('array', 'string') and (not isinstance(val, int) or val < 0): raise ProgramError('%s: length bounds must be nonnegative integers' % where) if schema.get('min', -math.inf) > schema.get('max', math.inf): raise ProgramError('%s: minimum is greater than maximum' % where) if 'label' in schema and not isinstance(schema['label'], str): raise ProgramError('%s: label must be text' % where) if 'enum' in schema: if not isinstance(schema['enum'], list) or not schema['enum']: raise ProgramError('%s: enum must name at least one value' % where) plain = dict(schema); plain.pop('enum') for item in schema['enum']: _value(item, plain, where) if 'initial' in schema: _value(schema['initial'], schema, where) def _value(value, schema, where): typ = schema['type'] valid = {'integer': lambda: isinstance(value, int) and not isinstance(value, bool), 'number': lambda: isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value), 'string': lambda: isinstance(value, str), 'boolean': lambda: isinstance(value, bool), 'array': lambda: isinstance(value, list)}[typ]() if not valid: raise ProgramError('%s must be %s' % (where, typ)) size = len(value) if typ in ('array', 'string') else value if typ != 'boolean' and (size < schema.get('min', -math.inf) or size > schema.get('max', math.inf)): raise ProgramError('%s is outside its declared bounds' % where) if 'enum' in schema and value not in schema['enum']: raise ProgramError('%s must be one of %s' % (where, schema['enum'])) if typ == 'array': for i, item in enumerate(value): _value(item, schema['items'], '%s[%d]' % (where, i)) return copy.deepcopy(value) _OPS = {'add': (2, 2), 'subtract': (2, 2), 'multiply': (2, 2), 'divide': (2, 2), 'eq': (2, 2), 'ne': (2, 2), 'lt': (2, 2), 'le': (2, 2), 'gt': (2, 2), 'ge': (2, 2), 'and': (1, 16), 'or': (1, 16), 'not': (1, 1), 'concat': (1, 16), 'contains': (2, 2), 'length': (1, 1), 'if': (3, 3)} def _expr_shape(expr, fields, params, where, depth=0): if depth > 32: raise ProgramError('%s: expression exceeds 32 nested parts' % where) if not isinstance(expr, dict): if isinstance(expr, (str, bool, int, float)) or expr is None: if isinstance(expr, float) and not math.isfinite(expr): raise ProgramError('%s needs finite numbers' % where) return if isinstance(expr, list): for item in expr: _expr_shape(item, fields, params, where, depth + 1) return raise ProgramError('%s has an unknown expression' % where) if set(expr) in ({'state'}, {'param'}): kind = next(iter(expr)); names = fields if kind == 'state' else params if expr[kind] not in names: raise ProgramError('%s refers to undeclared %s %r' % (where, kind, expr[kind])) return _keys(expr, ('op', 'args'), ('op', 'args'), where) if expr['op'] not in _OPS or not isinstance(expr['args'], list): raise ProgramError('%s needs a declared expression part: %r' % (where, expr.get('op'))) low, high = _OPS[expr['op']] if not low <= len(expr['args']) <= high: raise ProgramError('%s: %s takes %s..%s arguments' % (where, expr['op'], low, high)) for arg in expr['args']: _expr_shape(arg, fields, params, where, depth + 1) def _bool(value): if not isinstance(value, bool): raise ProgramError('a condition must produce a boolean') return value def _number(value): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): raise ProgramError('arithmetic needs finite numbers') return value def expression(expr, state, params): if isinstance(expr, list): return [expression(x, state, params) for x in expr] if not isinstance(expr, dict): return expr if 'state' in expr: return copy.deepcopy(state[expr['state']]) if 'param' in expr: return copy.deepcopy(params[expr['param']]) op, args = expr['op'], expr['args'] if op == 'if': return expression(args[1] if _bool(expression(args[0], state, params)) else args[2], state, params) vals = [expression(x, state, params) for x in args] if op in ('add', 'subtract', 'multiply', 'divide'): a, b = map(_number, vals) if op == 'divide' and b == 0: raise ProgramError('division needs a nonzero denominator') result = {'add': lambda: a + b, 'subtract': lambda: a - b, 'multiply': lambda: a * b, 'divide': lambda: a / b}[op]() return _number(result) if op in ('eq', 'ne'): same = type(vals[0]) == type(vals[1]) and vals[0] == vals[1] return same if op == 'eq' else not same if op in ('lt', 'le', 'gt', 'ge'): a, b = map(_number, vals) return {'lt': lambda: a < b, 'le': lambda: a <= b, 'gt': lambda: a > b, 'ge': lambda: a >= b}[op]() if op in ('and', 'or'): conditions = [_bool(x) for x in vals] return all(conditions) if op == 'and' else any(conditions) if op == 'not': return not _bool(vals[0]) if op == 'concat': if any(not isinstance(x, str) for x in vals): raise ProgramError('concat needs text values') return ''.join(vals) if op == 'contains': if not isinstance(vals[0], (str, list)): raise ProgramError('contains needs a list or text') return vals[1] in vals[0] if op == 'length': if not isinstance(vals[0], (str, list)): raise ProgramError('length needs a list or text') return len(vals[0]) raise ProgramError('unknown expression part %s' % op) def _params(schema, supplied, where): _keys(supplied, schema, schema, where) return {name: _value(supplied[name], spec, where + '.' + name) for name, spec in schema.items()} def _action_shapes(actions, contract, params, where, calls, depth=0): if depth > 32: raise ProgramError('%s: actions exceed 32 nested parts' % where) if not isinstance(actions, list) or len(actions) > 128: raise ProgramError('%s needs at most 128 ordered actions' % where) for action in actions: if not isinstance(action, dict): raise ProgramError('%s needs a named action' % where) op = action.get('op') if op in ('set', 'append', 'remove'): _keys(action, ('op', 'field', 'value'), ('op', 'field', 'value'), where) if action['field'] not in contract['state']: raise ProgramError('%s targets undeclared state %r' % (where, action['field'])) if op != 'set' and contract['state'][action['field']]['type'] != 'array': raise ProgramError('%s requires an array field' % op) _expr_shape(action['value'], contract['state'], params, where) elif op == 'if': _keys(action, ('op', 'condition', 'then', 'else'), ('op', 'condition', 'then'), where) _expr_shape(action['condition'], contract['state'], params, where) for branch in ('then', 'else'): _action_shapes(action.get(branch, []), contract, params, where, calls, depth + 1) elif op == 'assert': _keys(action, ('op', 'condition', 'message'), ('op', 'condition', 'message'), where) if not isinstance(action['message'], str): raise ProgramError('an assertion needs a text message') _expr_shape(action['condition'], contract['state'], params, where) elif op == 'call': _keys(action, ('op', 'part', 'args'), ('op', 'part', 'args'), where) part = action['part'] if part not in contract['parts']: raise ProgramError('%s needs declared action part %r' % (where, part)) _keys(action['args'], contract['parts'][part]['params'], contract['parts'][part]['params'], where) for expr in action['args'].values(): _expr_shape(expr, contract['state'], params, where) calls.add(part) else: raise ProgramError('%s: action %r has no part yet' % (where, op)) def validate(contract): """Return the fully checked shape; never discard unknown requirements.""" c = copy.deepcopy(contract) _keys(c, ('version', 'title', 'state', 'events', 'parts', 'views', 'controls', 'checks'), ('version', 'title', 'state', 'events', 'views', 'controls'), 'program') if c['version'] != 1 or isinstance(c['version'], bool): raise ProgramError('program version must be 1') if not isinstance(c['title'], str) or not c['title'].strip(): raise ProgramError('program needs a title') c.setdefault('parts', {}); c.setdefault('checks', []) for group in ('state', 'events', 'parts'): if not isinstance(c[group], dict) or len(c[group]) > 128: raise ProgramError('%s needs at most 128 named members' % group) for name in c[group]: _name(name) if not c['state'] or not c['events']: raise ProgramError('program needs state and events') for name, schema in c['state'].items(): _schema(schema, 'state.' + name, initial=True) for group in ('events', 'parts'): for name, spec in c[group].items(): if not isinstance(spec, dict): raise ProgramError('%s.%s needs a named handler shape' % (group, name)) spec.setdefault('params', {}) calls = {} for group in ('events', 'parts'): for name, spec in c[group].items(): _keys(spec, ('params', 'actions', 'guard') if group == 'events' else ('params', 'actions'), ('actions',), group + '.' + name) spec.setdefault('params', {}) if not isinstance(spec['params'], dict): raise ProgramError('%s parameters must be named' % name) for param, schema in spec['params'].items(): _name(param); _schema(schema, name + '.' + param) if 'guard' in spec: _expr_shape(spec['guard'], c['state'], spec['params'], name) targets = set(); _action_shapes(spec['actions'], c, spec['params'], name, targets) if group == 'parts': calls[name] = targets def visit(name, active): if name in active: raise ProgramError('action parts form a cycle through %s' % name) for child in calls[name]: visit(child, active | {name}) for name in calls: visit(name, set()) if not isinstance(c['views'], list) or not isinstance(c['controls'], list): raise ProgramError('views and controls must be ordered lists') for view in c['views']: _keys(view, ('kind', 'label', 'value', 'visible'), ('kind', 'label', 'value'), 'view') if view['kind'] not in ('text', 'list') or not isinstance(view['label'], str): raise ProgramError('view needs a text/list kind and a text label') _expr_shape(view['value'], c['state'], {}, 'view') if 'visible' in view: _expr_shape(view['visible'], c['state'], {}, 'view visibility') for control in c['controls']: _keys(control, ('kind', 'label', 'event', 'args', 'visible'), ('kind', 'label', 'event'), 'control') if control['kind'] not in ('button', 'form') or control['event'] not in c['events'] or not isinstance(control['label'], str): raise ProgramError('control needs a button/form kind, declared event and text label') params = c['events'][control['event']]['params'] control.setdefault('args', {}) _keys(control['args'], params, params if control['kind'] == 'button' else (), 'control arguments') for expr in control['args'].values(): _expr_shape(expr, c['state'], {}, 'control argument') if 'visible' in control: _expr_shape(control['visible'], c['state'], {}, 'control visibility') if not isinstance(c['checks'], list): raise ProgramError('checks must be event trajectories') for check in c['checks']: _keys(check, ('events', 'state'), ('events', 'state'), 'check') if not isinstance(check['events'], list): raise ProgramError('check events must be a list') for event in check['events']: _keys(event, ('event', 'args'), ('event',), 'check event') if event['event'] not in c['events']: raise ProgramError('check names undeclared event %r' % event['event']) event.setdefault('args', {}) _params(c['events'][event['event']]['params'], event['args'], event['event']) _params(c['state'], check['state'], 'expected state') return c def initial_state(contract): return {name: copy.deepcopy(spec['initial']) for name, spec in contract['state'].items()} def transition(contract, state, event, args): """Apply one event atomically to a copied state, validating each assignment.""" if event not in contract['events']: raise ProgramError('event %r has no handler' % event) working = _params(contract['state'], state, 'state') spec = contract['events'][event] params = _params(spec['params'], args, event) if 'guard' in spec and not _bool(expression(spec['guard'], working, params)): raise ProgramError('event %s is not available in the current state' % event, 409) budget = [2048] def actions(items, values): for action in items: budget[0] -= 1 if budget[0] < 0: raise ProgramError('event exceeds its 2048 action budget') op = action['op'] if op in ('set', 'append', 'remove'): value = expression(action['value'], working, values); field = action['field'] if op == 'append': value = working[field] + [value] elif op == 'remove': value = [item for item in working[field] if item != value] working[field] = _value(value, contract['state'][field], field) elif op == 'if': actions(action.get('then' if _bool(expression(action['condition'], working, values)) else 'else', []), values) elif op == 'assert': if not _bool(expression(action['condition'], working, values)): raise ProgramError(action['message'], 409) elif op == 'call': part = contract['parts'][action['part']] supplied = {k: expression(v, working, values) for k, v in action['args'].items()} actions(part['actions'], _params(part['params'], supplied, action['part'])) actions(spec['actions'], params) return working def _encoded(value): return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode('utf-8') def _hash(value): return hashlib.sha256(value).hexdigest() def replay(contract, history, initial=None): state = initial_state(contract) if initial is None else _params(contract['state'], initial, 'epoch initial state') if not isinstance(history, list) or len(history) > 10000: raise ProgramError('event history must have at most 10000 events') for entry in history: _keys(entry, ('event', 'args', 'state_hash'), ('event', 'args', 'state_hash'), 'history event') state = transition(contract, state, entry['event'], entry['args']) if entry['state_hash'] != _hash(_encoded(state)): raise ProgramError('retained event history does not reproduce its state receipt', 409) return state def _same_state_schema(left, right): def shape(contract): return {name: {k: copy.deepcopy(v) for k, v in schema.items() if k not in ('initial', 'label')} for name, schema in contract['state'].items()} return shape(left) == shape(right) def _audit_document(doc, contract): """Replay each epoch under its own definition; never reinterpret old events.""" _keys(doc, ('contract', 'definition', 'state', 'history', 'base', 'epochs', 'source_sha256'), ('contract', 'state', 'history'), 'stored program') if doc['contract'] != _hash(_encoded(contract)): raise ProgramError('saved state belongs to a different program contract; name a migration before continuing', 409) if 'definition' in doc and validate(doc['definition']) != contract: raise ProgramError('saved definition does not match its contract receipt', 409) epochs = doc.get('epochs', []) if not isinstance(epochs, list) or len(epochs) > 128: raise ProgramError('saved program supports at most 128 checked revision epochs', 409) previous_state, previous_contract = None, None for epoch in epochs: _keys(epoch, ('contract', 'definition', 'base', 'history', 'state', 'state_hash', 'source_sha256', 'receipt_sha256'), ('contract', 'definition', 'base', 'history', 'state', 'state_hash', 'source_sha256', 'receipt_sha256'), 'revision epoch') definition = validate(epoch['definition']) if _hash(_encoded(definition)) != epoch['contract']: raise ProgramError('revision epoch definition does not match its contract receipt', 409) if previous_contract is None: if epoch['base'] != initial_state(definition): raise ProgramError('first revision epoch must start at its recorded initial state', 409) elif epoch['base'] != previous_state or not _same_state_schema(previous_contract, definition): raise ProgramError('revision epochs do not preserve compatible state continuously', 409) state = replay(definition, epoch['history'], epoch['base']) if state != epoch['state'] or _hash(_encoded(state)) != epoch['state_hash']: raise ProgramError('revision epoch does not reproduce its state receipt', 409) if not isinstance(epoch['receipt_sha256'], str) or not re.fullmatch('[0-9a-f]{64}', epoch['receipt_sha256']): raise ProgramError('revision epoch needs its prior saved-file receipt', 409) if epoch['source_sha256'] is not None and not re.fullmatch('[0-9a-f]{64}', str(epoch['source_sha256'])): raise ProgramError('revision epoch has an invalid source receipt', 409) previous_state, previous_contract = state, definition base = doc.get('base', initial_state(contract)) if epochs: if base != previous_state or not _same_state_schema(previous_contract, contract): raise ProgramError('current epoch does not continue the prior compatible state', 409) elif base != initial_state(contract): raise ProgramError('initial program state differs without a checked revision epoch', 409) if replay(contract, doc['history'], base) != doc['state']: raise ProgramError('saved state does not match replayed events', 409) _params(contract['state'], doc['state'], 'saved state') return doc class ProgramStore: def __init__(self, contract, root='.', filename='.oracle7/program-state.json', previous=None, source_sha256=None): self.contract = validate(contract); self.root = Path(root).resolve() self.path = (self.root / filename).resolve() if self.root not in self.path.parents: raise ProgramError('program state must stay inside the project folder') self.contract_hash = _hash(_encoded(self.contract)) self.previous = copy.deepcopy(previous or {}) self.source_sha256 = source_sha256 self.lock = _state_file_lock(self.path, self.root) def read(self): with self.lock: return self._read_locked() def _read_locked(self): if not self.path.exists(): return {'contract': self.contract_hash, 'definition': self.contract, 'state': initial_state(self.contract), 'history': [], 'base': initial_state(self.contract), 'epochs': [], 'source_sha256': self.source_sha256}, None data = self.path.read_bytes() try: doc = json.loads(data) if doc['contract'] != self.contract_hash: prior = self.previous.get(doc['contract']) if not prior: raise ProgramError('saved state belongs to a different program contract; name a migration before continuing', 409) old = validate(prior['contract']); _audit_document(doc, old) if not _same_state_schema(old, self.contract): raise ProgramError('saved state schema changed; name an explicit state migration before continuing', 409) _params(self.contract['state'], doc['state'], 'preserved state') epochs = copy.deepcopy(doc.get('epochs', [])) if len(epochs) >= 128: raise ProgramError('revision history reached 128 epochs; name an archival migration before continuing', 409) epochs.append({'contract': doc['contract'], 'definition': old, 'base': doc.get('base', initial_state(old)), 'history': copy.deepcopy(doc['history']), 'state': copy.deepcopy(doc['state']), 'state_hash': _hash(_encoded(doc['state'])), 'source_sha256': prior.get('source_sha256'), 'receipt_sha256': _hash(data)}) migrated = {'contract': self.contract_hash, 'definition': self.contract, 'state': copy.deepcopy(doc['state']), 'base': copy.deepcopy(doc['state']), 'history': [], 'epochs': epochs, 'source_sha256': self.source_sha256} _audit_document(migrated, self.contract) encoded = _encoded(migrated) self.snapshot(migrated, encoded) # new views must accept the preserved state before writing self._commit(encoded, data) return migrated, encoded _audit_document(doc, self.contract) return doc, data except (ValueError, TypeError, KeyError) as exc: if isinstance(exc, ProgramError): raise raise ProgramError('saved program state cannot be read: %s' % exc, 409) from exc def snapshot(self, doc=None, raw=None): if doc is None: doc, raw = self.read() state = doc['state']; views = []; controls = [] for view in self.contract['views']: if not _bool(expression(view.get('visible', True), state, {})): continue value = expression(view['value'], state, {}) if view['kind'] == 'list' and not isinstance(value, list): raise ProgramError('list view %s must produce a list' % view['label']) views.append({'kind': view['kind'], 'label': view['label'], 'value': value}) for i, control in enumerate(self.contract['controls']): if not _bool(expression(control.get('visible', True), state, {})): continue item = {k: control[k] for k in ('kind', 'label', 'event')} item['id'] = str(i); item['args'] = {k: expression(v, state, {}) for k, v in control['args'].items()} item['params'] = self.contract['events'][control['event']]['params']; controls.append(item) return {'title': self.contract['title'], 'version': _hash(raw if raw is not None else _encoded(doc)), 'state': copy.deepcopy(state), 'events': len(doc['history']) + sum(len(e['history']) for e in doc.get('epochs', [])), 'revision_epochs': len(doc.get('epochs', [])), 'views': views, 'controls': controls} def dispatch(self, payload): _keys(payload, ('version', 'event', 'args'), ('version', 'event', 'args'), 'event request') with self.lock: doc, before = self.read() if payload['version'] != self.snapshot(doc, before)['version']: raise ProgramError('state changed; refresh before sending this event again', 409) if len(doc['history']) >= 10000: raise ProgramError('event history reached 10000; a checkpoint part is needed', 409) state = transition(self.contract, doc['state'], payload['event'], payload['args']) next_doc = {'contract': self.contract_hash, 'definition': self.contract, 'state': state, 'base': doc.get('base', initial_state(self.contract)), 'epochs': doc.get('epochs', []), 'source_sha256': self.source_sha256, 'history': doc['history'] + [{'event': payload['event'], 'args': payload['args'], 'state_hash': _hash(_encoded(state))}]} encoded = _encoded(next_doc) result = self.snapshot(next_doc, encoded) # validate every view before any persistent change self._commit(encoded, before) return result def _commit(self, encoded, before): with self.lock: return self._commit_locked(encoded, before) def _commit_locked(self, encoded, before): self.path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix='.program-', dir=str(self.path.parent)) try: with os.fdopen(fd, 'wb') as handle: handle.write(encoded); handle.flush(); os.fsync(handle.fileno()) current = self.path.read_bytes() if self.path.exists() else None if current != before: raise ProgramError('saved state changed during this event or revision; refresh before retrying', 409) os.replace(tmp, self.path) finally: if os.path.exists(tmp): os.unlink(tmp) _PAGE = r'''