# LocalEnterprise (LE) 1.0.0

Spin-off of `sharedprotocol.c`. One C file, Linux only:
`gcc -O2 -Wall -Wextra -o localenterprise localenterprise.c -lpthread`

Kept from SP: the SPP v1.1 epoll engine (128k-peer design), SPP_RPC, the capability byte.
Removed: browser + bridge, SPCode, daemons, drivers, cron, relay, trace, SPMemory, JS forwarding.

## Quick start
    ./localenterprise --fse-root /srv/enterprise --state-dir /var/lib/le
    localenterprise> rpc server.token.add {"name":"alice","caps":"fsr,fsw","role":"dev"}     # secret shown once
    localenterprise> rpc policy.rule.add {"effect":"allow","who":"role:dev","action":"fse.*","resource":"/projects/**"}
    curl -H "Authorization: Bearer le_..." http://127.0.0.1:5223/files/projects/readme.txt

Default is deny: with no rules, no token or peer can do anything except identity / auth / own caps.
The terminal is the administrator and is never policy-checked. Use `--no-terminal` to run as a daemon.

## Capabilities (one byte, per token / SPP peer)
srv 0x01 routes+settings · kick 0x02 peers · tok 0x04 tokens · exec 0x08 fse.exec (+fsr) · logr 0x10 audit log + metrics ·
policy 0x20 rules/roles/grant · fsw 0x40 write ops · fsr 0x80 read ops.
Caps say which kinds of calls are possible; policy rules say which concrete calls are allowed. Both must pass.

## SPPLogE
`<state-dir>/audit.log`, mode 0600, one JSON line per action, hash-chained (`prev`, `hash` = SHA-256).
Logged: connection open/handshake/close, every non-ping SPP frame, every RPC (caller, method, redacted params,
ok/error, duration), every policy decision, auth ok/fail, token/rule/route/config changes, every HTTP request,
FSE operations (as RPC / http entries), start/stop. Params with token/secret/pass/key/content/data/auth/cookie/cred
keys are replaced with `***`; file contents are never logged.
Rotation at `--log-max-mb` keeps the chain across files. If the log cannot be written, all non-terminal calls are
denied (fail-closed; `--log-fail-open` to disable) and `/health` returns 503.
Verify: `rpc log.verify`, terminal `logverify`, or offline `localenterprise --verify-log f [--expect-head <hash>]`.
Editing, deleting or reordering lines is detected. Truncating the END is only detected against a head hash you saved
elsewhere (`loghead` / `rpc log.head`).

## SPPPolicyE
Rule = effect · who · action · resource · hours · days. who: `*`, `kind:peer|http|script`, `name:`, `role:`, `mention:`,
`ip:a.b.c.d/n`, `conn:N` joined with `&`. action globs over `rpc.<method>`, `fse.<op>`, `http.<METHOD>`;
resource globs over the FSE or HTTP path (`*` = one segment, `**` = anything, `/dir/**` also covers `/dir`).
Deny overrides allow; no match = `--policy-default` (deny). `hours` like 09:00-18:00 (wraps midnight), `days` like mon-fri.
Modes: `enforce` / `audit` (log would-be denials, allow). `policy.set {"lockdown":true}` denies all non-terminal calls.
Roles per connection: `policy.role.set`. `policy.eval` simulates a decision. Rules persist in `policy.db`.

## FSE (jailed to `--fse-root`)
fse.stat ls read hash · write touch mkdir rm mv cp chmod · exec · info. Paths are walked with openat(O_NOFOLLOW):
no symlink is ever followed, `..` is rejected, no existence is revealed before the policy check passes.
The FSE root must not contain (or be inside) the state/log directory. Reads ≤ 32 KB and writes ≤ 48 KB per SPP call
(use offset / append / patch; HTTP streams whole files). chmod refuses setuid/setgid/sticky.
`fse.exec` is OFF unless `--fse-exec`: runs a regular, executable file from the jail via fexecve with a clean env,
cwd = root, no stdin, merged output capped at 32 KB, timeout (default 10 s, max 60 s), rlimits (CPU, memory, file size,
fds), no_new_privs, own process group killed at the end, max 8 at once. It is NOT a sandbox: the program runs as the
LE user and can touch anything that user can. Run LE as an unprivileged user.

## SPPServer (HTTP/1.1, default 127.0.0.1:5223, no TLS: put a TLS proxy in front)
Pipeline: request id → conn/IP limits → rate limit → CORS → Bearer auth → route → policy → handler → audit log.
Built in: `GET /health` (public) · `GET /metrics` (logr) · `POST /rpc` {"method","params"} · `GET|HEAD|PUT|DELETE /files/<path>`
(Range, directory listing with a trailing `/`, `?mode=append|create`, `?parents=1`, `?recursive=1`).
User routes: `server.route.add {method,pattern,type:text|json|file|rpc|spce,target,public?,status?,content_type?}`;
patterns support `:param` and a trailing `/*`; file routes can mount a directory. Non-public routes need a token and
pass policy as `http.<METHOD>`. `server.config {rate,max_body,cors}`. Request smuggling guards: chunked bodies,
duplicate Content-Length, obsolete folding, oversized headers are rejected.

## SPP
Same framing as SP (26-byte header, CRC32). Only SPP_RPC is served. `auth.login {token}` gives the connection the
token's caps/name/role (five failures drop it); revoking or expiring a token cuts live sessions.

## SPCodeE (`.spce` scripts, v1.1)
A small language for rules and workflows. A script can only reach three things: **RPC** (every `fse.*` call included),
**SPPServer** (`server.respond`, the `server.*` RPCs) and **the audit log**. Scripts live in `<state>/spce/<name>.spce`
(0600, loaded at start). Manage them with `spce.load {name,source,enable?}` · `spce.source` · `spce.list` · `spce.enable
{name,enabled}` · `spce.remove` (need the policy cap) and `spce.run {name,workflow?,args?}` (policy action `spce.run`,
resource `name/workflow`). Names: lowercase letters, digits, `-` `_`, up to 34. Source up to 256 KB.

```
caps fsr, fsw                      # what the script may ask for: fsr fsw exec srv logr (never policy, tok, kick)
rule big_write on "fse.write" when len(rpc.params.content) > 1000 do
  log "large write", rpc.params.path, "by", rpc.caller.name
  deny "too large"                 # refuses the call that fired the rule
end
workflow main do
  let data = fse.read({path: "/report.json"})      # same as rpc("fse.read", {...})
  let doc = parse(data.data)
  if doc.total > 100 do
    server.respond(200, {big: true})               # only inside an HTTP route
  end
  return doc.total
end
```
**Values**: null, true/false, numbers, strings, lists, maps (lists and maps are shared by reference). **Statements**:
`let` `set x = / x.f = / x[i] =` `if … do … else … end` `for x in list|map do … end` `while … do … end` `log a, b` `deny msg`
(rules only) `return`. **Operators**: `+ - * / %`, `== != < <= > >=`, `and or not`. Comparing `<`/`>` across types is an
error (rule errors **fail closed**: the call that fired the rule is refused), so test with `has(m, "k")` or `type(x)` first.
**Builtins**: len str num type keys has contains starts ends upper lower trim substr split join replace push range
json parse abs floor round min max now date iso hash · `rpc(method, params)` (aborts the run on failure) · `try_rpc`
(returns `{ok, result|error}`) · `run(workflow, args)` · `server.respond(status, body[, content_type])`.
Any RPC method also works as `a.b({params})`. Scripts cannot call `spce.*` or `auth.*`.

**Run a script directly.** No server needed:
```
localenterprise --spce-run report.spce [workflow] [--spce-args '{"n":3}']   # runs once, prints the result, exits (0 ok, 1 error)
localenterprise --spce-check report.spce                                     # compile only: caps, rules, workflows
localenterprise> spce run report.spce [workflow] [json-args]                 # same, from the running terminal
localenterprise> spce check report.spce
```
The workflow defaults to `main`; the script's name is the file name (lowercased, `.spce` removed). The file is run once and
not installed, saved or enabled, so its `rule`s do **not** become active (use `spce.load` for that). Nothing else changes: it acts
as `spce:<name>` with its declared caps, policy decides each call it makes (default deny, so give `name:spce:<name>` a rule or start
with `--policy-default allow` for a test), rules of already-installed scripts still guard its calls, and `spce.load`
(source `run`, with the SHA-256 and path), `spce.run.start|end` and every RPC it makes go to the audit log. `--spce-run` opens no
ports and uses the same `--state-dir`, `--fse-root` and `--log-file` options as a normal start.

**Rules** fire before the RPC they match runs (SPP, HTTP `/rpc` and HTTP `/files`, which looks like `fse.read|write|rm` with
`path`, `mode`, `size`, `content`); never for the terminal. Variables: `rpc.method`, `rpc.params`, `rpc.caller{kind,name,role,ip}`.
Rules fired by an SPP peer run on the network thread, so they get 100 ms, 20000 steps and 5 RPC calls and cannot use
`fse.exec` / `fse.cp`. **Workflows** get `args` and `caller`. **HTTP routes**: `server.route.add {type:"spce",target:"script/workflow"}`;
the workflow gets `req{method,path,query,body,json,caller}`. No `server.respond` and a return value → 200 JSON; no value → 204.

**Identity and policy**: a script acts as principal `spce:<name>` (kind `script`, role `script`) with the caps it declared.
Caps AND policy must both allow every call (default deny: add rules for `name:spce:<name>`). A loader cannot give a script
caps it does not hold. **Forced logging**: every RPC a script makes is an `rpc` event under its principal, plus
`spce.load` (source SHA-256), `spce.run.start|end`, `spce.rule`, `spce.log` (secrets redacted), `spce.respond`, `spce.kill`,
`spce.enable`, `spce.remove`. A script cannot switch this off; it cannot act while the audit log is failing.
**Limits per run**: 200000 steps, 5 s, 100 RPC calls, 16 MB, workflow depth 8, 500 log lines.
**The kill rule**: a rule that fires because of a script's own action is an *automatic* run. The 5th automatic run of the
same script in an unbroken chain (no outside request or manual run in between) is refused and the script is stopped
(disabled; stays disabled across restarts until `spce.enable`). The request that started the chain is refused too.
Manual runs and separate outside requests never count. `--spce-no-limit` removes only this kill; the chain depth cap
(16) and all per-run limits stay, and the startup event records that the limit is off.
