Zoo

staging

← back to the zoo

25. Change an app by asking

A model in your workbench changes your app and shows it running on the preview address; staging and live change only when you ship.

The workbench (apps, Open the workbench): your own OpenCode at code.<domain>, every app of yours a project, the model on your ai ledger. Ask; it works on a branch, pushes it and previews it (ratcloud preview); you ship from apps when it is right. A robot's workbench key never pushes main or staging.

This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit 55c71513c5 (staging). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e25_change_by_asking.odin sha256 f51d892c9867 · raw

1package main
2
3// Exhibit 25. A model changes an app on request and shows it on the preview address; staging and live
4// change only when the creator ships.
5//
6// The workbench: each creator's own OpenCode at code.<domain>, every app of theirs a project, reached
7// through apps (apps.<domain>/api/work wakes it and hands a two-minute link that becomes code's
8// cookie). Once a day the `workbench` job drives it as the zoo's robot, exactly as a browser would:
9// sign in at account and apps, wake the robot's workbench at zoo-scratch's session, and prompt it
10// through OpenCode's own API on code.<domain>: make /ping answer a fresh word on a new branch, push
11// the branch, `ratcloud preview` it, then push main once. The robot's workbench key pushes any branch
12// but main and staging (`rc work robot zoo-robot on`), so that last push is refused, and the card
13// shows it. From outside: the preview answers the word, staging and live do not, zoo-scratch's main
14// did not move. It needs zoo-scratch to be the robot's (`rc creator transfer zoo-scratch johannes
15// zoo-robot`) and the robot's workbench key kept to its branches: both root's.
16//
17// Staging has no workbench (apps-staging's /api/work is a 404): the staging zoo checks that refusal.
18//
19// A run takes many minutes; the job that runs it waits for the workbench in steps, each inside the
20// job's own time (30 minutes, its interval).
21
22import "core:encoding/json"
23import "core:fmt"
24import "core:strings"
25import "core:time"
26import "ratcloud:rc"
27
28E25_APP :: "zoo-scratch"
29// A run gets 18 minutes (several times a normal run); the job runs every 30
30// minutes and is stopped at 30, so a run that hangs is stopped before the next one starts.
31E25_RUN_SECS :: 1080
32// A daily run, so its verdict is at most a day and a bit old; older than this, the runs stopped.
33E25_FRESH :: 26 * 3600
34// A red run is tried again after this (each try is a model run on the robot's ledger).
35E25_RETRY :: 3 * 3600
36
37WORDS := [?]string{"otter", "heron", "badger", "lynx", "marten", "plover", "vole", "wren"}
38fresh_word :: proc() -> string {return fmt.tprintf("%s-%s", WORDS[random_int(0, 7)], random_hex(3))}
39
40e25_host :: proc(env_: string) -> string {
41	h_ := domain_host(rc.app_url(E25_APP))
42	dot := strings.index_byte(h_, '.')
43	label := strings.trim_suffix(h_[:dot], "-staging")
44	return cat(label if env_ == "live" else cat(label, "-", env_), h_[dot:])
45}
46
47Ping :: struct {
48	url:      string `json:"url"`,
49	status:   int `json:"status"`,
50	body:     string `json:"body"`,
51	has_word: bool `json:"has_word"`,
52}
53e25_ping :: proc(env_: string) -> Ping {
54	url := fmt.tprintf("https://%s/ping", e25_host(env_))
55	r := rc.fetch({url = url, timeout_ms = 15_000})
56	return {url = url, status = r.status, body = clip(strings.trim_space(string(r.body)), 120)}
57}
58
59// Whether the workbench path can run, and why not. Read as the robot, on apps, as any creator sees it.
60e25_ready :: proc() -> (bool, string) {
61	if env().env != "live" do return false, "staging has no workbench"
62	b, err := robot_at("apps")
63	if err != "" do return false, err
64	apps := rc.app_url("apps")
65	if get(b, fmt.tprintf("%s/api/app/%s", apps, E25_APP)).status != 200 do return false, fmt.tprintf("%s is not the robot's yet (root: rc creator transfer %s johannes %s)", E25_APP, E25_APP, CREATOR)
66	j := get(b, cat(apps, "/api/apps")).j
67	wb: json.Value
68	for k in jarr(j, "machines") do if jbool(k, "workbench") {wb = k; break}
69	if wb == nil do return false, fmt.tprintf("the robot has no workbench key yet (root: rc work robot %s on)", CREATOR)
70	if jstr(wb, "refs") != "branches" do return false, fmt.tprintf("the robot's workbench key may still push main (root: rc work robot %s on)", CREATOR)
71	if !jbool(wb, "on") do return false, "the robot's workbench key was removed on apps"
72	return true, ""
73}
74
75// zoo-scratch's main as apps shows it to its creator.
76e25_main :: proc(b: ^Browser) -> string {
77	for br in jarr(get(b, fmt.tprintf("%s/api/app/%s", rc.app_url("apps"), E25_APP)).j, "branches") do if jstr(br, "name") == "main" do return jstr(br, "commit")
78	return ""
79}
80
81Main_Push :: struct {
82	refused: bool `json:"refused"`,
83	said:    string `json:"said"`,
84	tried:   bool `json:"tried"`,
85}
86E25_Run :: struct {
87	path:        string `json:"path"`,
88	at:          string `json:"at"`,
89	request:     string `json:"request,omitempty"`,
90	word:        string `json:"word,omitempty"`,
91	branch:      string `json:"branch,omitempty"`,
92	main_before: string `json:"main_before,omitempty"`,
93	main_after:  string `json:"main_after,omitempty"`,
94	session:     string `json:"session,omitempty"`,
95	messages:    int `json:"messages"`,
96	answer:      string `json:"answer,omitempty"`,
97	preview:     Ping `json:"preview"`,
98	staging:     Ping `json:"staging"`,
99	live:        Ping `json:"live"`,
100	main_push:   Main_Push `json:"main_push"`,
101	seconds:     i64 `json:"seconds"`,
102	ok:          bool `json:"ok"`,
103	detail:      string `json:"detail"`,
104	said:        string `json:"said,omitempty"`,
105	why:         string `json:"why,omitempty"`,
106}
107
108// The run on the robot's workbench (the `workbench` job). busy: both of the worker's workbench slots
109// are taken (no attempt: the next half hour tries again).
110e25_work_round :: proc() -> (out: E25_Run, busy: string) {
111	t0 := now()
112	b, err := robot_at("apps")
113	if err != "" do return {path = "workbench", at = iso(t0), detail = err}, ""
114	apps := rc.app_url("apps")
115	word := fresh_word()
116	branch := cat("ping-", word)
117	pv := e25_host("preview")
118	out = {path = "workbench", at = iso(t0), word = word, branch = branch}
119	out.request = fmt.tprintf("Make GET /ping answer with exactly the text \"%s\" (plain text, status 200), in `handle` in main.odin (an Odin app on wasm), keeping everything else as it is. Do it on a new branch named `%s` made from main: commit, and push that branch with `git push origin %s` (not main). Then run `ratcloud preview %s` and check with `curl -s https://%s/ping` that the preview answers it. Last, run `git push origin HEAD:main` once and tell me exactly what the server answered: it should refuse, and that refusal is what I want to see, so do not retry it or work around it. Do not ask me anything: nobody is watching.", word, branch, branch, branch, pv)
120	failing :: proc(out: ^E25_Run, t0: i64, why: string) -> E25_Run {
121		out.ok, out.detail, out.seconds = false, why, now() - t0
122		return out^
123	}
124	out.main_before = e25_main(b)
125
126	// Wake the robot's workbench at zoo-scratch's session: apps's /api/work, as the page polls it.
127	link, state := "", ""
128	for i := 0; i < 120; i += 1 {
129		r := get(b, fmt.tprintf("%s/api/work?app=%s", apps, E25_APP))
130		state = fmt.tprintf("%s: %s", jstr(r.j, "state") or_else "?", jstr(r.j, "message")) if r.j != nil else fmt.tprintf("HTTP %d", r.status)
131		if r.status == 200 && jstr(r.j, "link") != "" {link = jstr(r.j, "link"); break}
132		st := jstr(r.j, "state")
133		if r.status != 200 || st == "failed" || st == "refused" || st == "signin" do return failing(&out, t0, cat("apps would not wake the robot's workbench: ", state)), ""
134		rc.sleep(2000)
135	}
136	if link == "" {
137		if strings.has_prefix(state, "busy") do return {}, state
138		return failing(&out, t0, cat("the robot's workbench did not wake in 4 minutes: ", state)), ""
139	}
140	origin := link[:8 + (strings.index_byte(link[8:], '/') if strings.index_byte(link[8:], '/') >= 0 else len(link) - 8)]
141	lr := get(b, link) // the two-minute link becomes code's cookie, then a 303 to the session
142	if lr.status != 303 && lr.status != 302 do return failing(&out, t0, fmt.tprintf("code's link answered %d, not a way in", lr.status)), ""
143	sid := ""
144	if i := strings.index(lr.location, "/session/ses_"); i >= 0 {
145		rest := lr.location[i + 9:]
146		n := 4
147		for n < len(rest) && is_alnum(rest[n]) do n += 1
148		sid = rest[:n]
149	}
150	accept := make(map[string]string)
151	accept["Accept"] = "application/json"
152	if sid == "" {
153		for s in jarr(go(b, "GET", cat(origin, "/api/session?limit=200"), extra = accept).j, "data") do if strings.has_suffix(jstr(s, "location", "directory"), cat("/", E25_APP)) do sid = jstr(s, "id")
154	}
155	if sid == "" do return failing(&out, t0, cat("no ", E25_APP, " session in the robot's workbench")), ""
156	out.session = sid
157
158	// The prompt, through OpenCode's own API behind apps's gate; then wait for the turn to end.
159	b.timeout_ms = 30_000
160	pr := go(b, "POST", fmt.tprintf("%s/api/session/%s/prompt", origin, sid), fmt.tprintf(`{{"text":%s}}`, jq(out.request)), "application/json", accept)
161	b.timeout_ms = 15_000
162	if pr.status != 200 do return failing(&out, t0, fmt.tprintf("the workbench took no prompt (HTTP %d)", pr.status)), ""
163	seen, idle := false, false
164	for now() < t0 + E25_RUN_SECS {
165		rc.sleep(3000)
166		a := go(b, "GET", cat(origin, "/api/session/active"), extra = accept)
167		busy_ := true
168		if a.status == 200 && a.j != nil do busy_ = jhas(a.j, "data", sid)
169		if busy_ do seen = true
170		if !busy_ && (seen || now() - t0 > 30) {idle = true; break}
171	}
172	msgs := go(b, "GET", fmt.tprintf("%s/api/session/%s/message?limit=30", origin, sid), extra = accept)
173	said := msgs.body
174	out.messages = len(jarr(msgs.j, "data"))
175	last := ""
176	for m in jarr(msgs.j, "data") do for p in jarr(m, "content") do if jstr(p, "type") == "text" do last = strings.trim_space(jstr(p, "text"))
177	out.answer = clip(last, 400)
178
179	// From outside: the preview has the word, staging and live do not, main did not move.
180	out.preview, out.staging, out.live = e25_ping("preview"), e25_ping("staging"), e25_ping("live")
181	for p in ([]^Ping{&out.preview, &out.staging, &out.live}) do p.has_word = strings.contains(p.body, word)
182	out.main_after = e25_main(b)
183	REFUSAL :: "a robot's workbench key may not push refs/heads/main"
184	refusal := ""
185	if i := strings.index(said, REFUSAL); i >= 0 {
186		end := i + len(REFUSAL)
187		for end < len(said) && said[end] != '"' && said[end] != '\\' do end += 1
188		refusal = said[i:end]
189	}
190	out.main_push = {refusal != "" && out.main_after == out.main_before, refusal, strings.contains(said, "HEAD:main")}
191	bad := make([dynamic]string)
192	if !idle do append(&bad, fmt.tprintf("the workbench was still at work after %d minutes", E25_RUN_SECS / 60))
193	if !out.preview.has_word do append(&bad, cat("the preview's /ping does not answer ", word))
194	if out.staging.has_word do append(&bad, "staging answers the word")
195	if out.live.has_word do append(&bad, "live answers the word")
196	if out.main_after != out.main_before do append(&bad, fmt.tprintf("zoo-scratch's main MOVED (%s to %s)", short(out.main_before, 7), short(out.main_after, 7)))
197	else if refusal == "" do append(&bad, "the workbench's push to main shows no refusal" if out.main_push.tried else "the workbench did not try to push main")
198	out.seconds = now() - t0
199	out.ok = len(bad) == 0
200	out.detail = strings.join(bad[:], "; ") if len(bad) > 0 else fmt.tprintf(`the robot's workbench made /ping answer %s on %s and previewed it: the preview answers it, staging and live do not, and its key pushing main was refused ("%s"), %d s`, word, branch, refusal, out.seconds)
201	return out, ""
202}
203
204// The `workbench` job, every 30 minutes: a run when one is due. What it did, in words.
205e25_job :: proc() -> (string, bool) {
206	if env().env != "live" do return "", false
207	hour, _, _ := time.clock(time.now())
208	v, has := meta("e25.work")
209	w: E25_Run
210	if has do json.unmarshal_string(v, &w)
211	at := parse_time(w.at)
212	due := !has || v == "" || (w.ok && ymd(at) < ymd(now()) && hour >= 5) || (!w.ok && now() - at >= E25_RETRY)
213	if !due do return "", false
214	if ready, _ := e25_ready(); !ready do return "", false
215	r, busy := e25_work_round()
216	if busy != "" do return fmt.tprintf("exhibit 25: the worker's workbench slots are both in use (%s); the next half hour tries again", busy), true
217	meta_set("e25.work", to_json(r))
218	return fmt.tprintf("exhibit 25 %s (workbench): %s", "ok" if r.ok else "FAILED", r.detail), true
219}
220
221e25 :: proc() -> Exhibit {
222	return {
223		n = 25, wing = "Building",
224		title = "Change an app by asking",
225		promise = "A model in your workbench changes your app and shows it running on the preview address; staging and live change only when you ship.",
226		block = "The workbench (apps, Open the workbench): your own OpenCode at code.<domain>, every app of yours a project, the model on your ai ledger. Ask; it works on a branch, pushes it and previews it (ratcloud preview); you ship from apps when it is right. A robot's workbench key never pushes main or staging.",
227		src = {"e25_change_by_asking.odin", #load("e25_change_by_asking.odin", string)},
228		files = srcs({"robot.odin", #load("robot.odin", string)}),
229		show = proc(me: ^rc.User) -> string {
230			p, _, found := stored_data(25, E25_Run)
231			apps := rc.app_url("apps")
232			live := apps
233			if i := strings.index(apps, "-staging."); i >= 0 do live = cat(apps[:i], apps[i + 8:]) // the workbench is live's alone
234			yours := fmt.tprintf(`<p class="muted">Yours: <a href="%s/workbench">Open the workbench</a> on apps (creators, on live).</p>`, h(live))
235			if !found || p.path == "" do return cat("<p>Not checked yet.</p>", yours)
236			if p.path == "staging" do return fmt.tprintf(`<p>This is staging: it has no workbench (%s). The live zoo runs this exhibit in its robot's workbench.</p>`, h(p.said))
237			line :: proc(x: Ping, label: string) -> string {
238				return fmt.tprintf(`<li>%s: <a href="%s"><code>/ping</code></a> answered %d <code>%s</code>%s</li>`, label, h(x.url), x.status, h(clip(x.body, 40)), " (has the word)" if x.has_word else " (without it)")
239			}
240			lines := cat(line(p.preview, "preview"), line(p.staging, "staging"), line(p.live, "live"))
241			if p.path == "workbench" {
242				return cat(fmt.tprintf(`<p>The zoo's robot asked its own workbench (OpenCode at code.%s, through apps), %s, in <code>%s</code>:</p><blockquote>%s</blockquote><ul>`, h(env().domain), ago(parse_time(p.at)), E25_APP, h(p.request)), lines,
243					`<li>the robot's workbench key pushing <code>main</code>: `, cat("refused: <code>", h(p.main_push.said), "</code>") if p.main_push.refused else "<b>not refused</b>", "</li></ul>",
244					fmt.tprintf(`<p class="muted">%d messages in the session, %d s, on the robot's ai ledger (app apps). Path: the robot's workbench.</p>`, p.messages, p.seconds), yours)
245			}
246			return cat(fmt.tprintf(`<p>Not running: %s.</p>`, h(p.why if p.why != "" else p.detail)), yours)
247		},
248		check = proc() -> Check {
249			if env().env != "live" {
250				r := get(new_browser(), cat(rc.app_url("apps"), "/api/work"))
251				said := jstr(r.j, "error")
252				if r.status == 404 do return pass(fmt.tprintf(`staging has no workbench (apps-staging: "%s"); the live zoo runs this exhibit in its robot's workbench`, said), E25_Run{path = "staging", said = said, at = iso(now())})
253				return fail(fmt.tprintf("staging's apps answered %d for a workbench (it has none)", r.status), E25_Run{path = "staging", at = iso(now())})
254			}
255			ready, why := e25_ready()
256			if v, has := meta("e25.work"); ready && has && v != "" {
257				w: E25_Run
258				json.unmarshal_string(v, &w)
259				age := now() - parse_time(w.at)
260				if age > E25_FRESH do return fail(fmt.tprintf("the robot's workbench last ran this %d h ago: the daily runs stopped", age / 3600), w)
261				if !w.ok do return fail(cat("the robot's workbench: ", w.detail), w)
262				for e in ([]string{"staging", "live"}) do if strings.contains(e25_ping(e).body, w.word) do return fail(cat(e, " answers the workbench's word: a change reached ", e, " without a ship"), w)
263				return pass(cat("the robot's workbench: ", w.detail), w)
264			}
265			if ready do why = "ready; its first run comes within half an hour"
266			return fail(cat("the robot's workbench: ", why), E25_Run{path = "waiting", why = why, at = iso(now())})
267		},
268	}
269}

robot.odin sha256 4cfbb96b4503 · raw

1package main
2
3// The zoo's robot: a real account, `zoo-robot`, visible in the directory like anyone, that the
4// self-check signs in as. Its passkey is a software key kept in robot.json (the zoo's own data;
5// nothing of root's or account's). It signs in exactly as a person does: a WebAuthn assertion to
6// account, then the silent upgrade into each app it visits.
7//
8// Live and staging each have their own account, so each environment has its own robot. One sign-in
9// per instance (a request or a job run); robot_done() signs it out again at the end, so robot
10// sessions never pile up.
11
12import "core:crypto/ecdsa"
13import "core:crypto/hash"
14import "core:encoding/base64"
15import "core:encoding/json"
16import "core:fmt"
17import "core:strings"
18import "ratcloud:rc"
19
20ROBOT_NAME :: "zoo-robot"
21
22Robot_File :: struct {
23	username: string `json:"username"`,
24	id:       i64 `json:"id"`,
25	cred:     string `json:"cred"`, // the credential id, base64url
26	key:      string `json:"key"`, // the private key, PEM
27	count:    i64 `json:"count"`,
28}
29
30b64u :: proc(b: []u8) -> string {
31	s := base64.encode(b)
32	out := strings.builder_make()
33	for ch in transmute([]u8)s {
34		switch ch {
35		case '+': strings.write_byte(&out, '-')
36		case '/': strings.write_byte(&out, '_')
37		case '=':
38		case: strings.write_byte(&out, ch)
39		}
40	}
41	return strings.to_string(out)
42}
43b64 :: proc(b: []u8) -> string {return base64.encode(b)}
44unb64 :: proc(s: string) -> ([]u8, bool) {
45	t := strings.builder_make()
46	for ch in transmute([]u8)s {
47		switch ch {
48		case '-': strings.write_byte(&t, '+')
49		case '_': strings.write_byte(&t, '/')
50		case ' ', '\n', '\r', '\t':
51		case: strings.write_byte(&t, ch)
52		}
53	}
54	for strings.builder_len(t) % 4 != 0 do strings.write_byte(&t, '=')
55	b, err := base64.decode(strings.to_string(t))
56	return b, err == nil
57}
58sha256 :: proc(b: []u8) -> []u8 {
59	out := make([]u8, 32)
60	hash.hash_bytes_to_buffer(.SHA256, b, out)
61	return out
62}
63sha256s :: proc(s: string) -> []u8 {return sha256(transmute([]u8)s)}
64bytes_of :: proc(s: string) -> []u8 {return transmute([]u8)s}
65join :: proc(parts: ..[]u8) -> []u8 {
66	n := 0
67	for p in parts do n += len(p)
68	out := make([]u8, n)
69	o := 0
70	for p in parts {copy(out[o:], p); o += len(p)}
71	return out
72}
73be32 :: proc(n: u32) -> []u8 {return bs(u8(n >> 24), u8(n >> 16), u8(n >> 8), u8(n))}
74be16 :: proc(n: u16) -> []u8 {return bs(u8(n >> 8), u8(n))}
75// A slice of these bytes that outlives the call.
76bs :: proc(xs: ..u8) -> []u8 {
77	out := make([]u8, len(xs))
78	copy(out, xs)
79	return out
80}
81
82// ---- P-256 keys as PEM: the 32-byte scalar inside SEC 1 or PKCS #8 ----------------------------------
83
84// The private scalar d of a P-256 key in PEM (SEC 1 "EC PRIVATE KEY" or PKCS #8 "PRIVATE KEY", as
85// openssl writes them): the OCTET STRING after ECPrivateKey's version 1.
86pem_scalar :: proc(pem: string) -> ([]u8, bool) {
87	body := strings.builder_make()
88	for line in strings.split_lines(pem) {
89		if strings.has_prefix(line, "-----") do continue
90		strings.write_string(&body, strings.trim_space(line))
91	}
92	der, ok := unb64(strings.to_string(body))
93	if !ok do return nil, false
94	for i in 0 ..< len(der) - 37 {
95		if der[i] == 0x02 && der[i + 1] == 0x01 && der[i + 2] == 0x01 && der[i + 3] == 0x04 && der[i + 4] == 0x20 do return der[i + 5:i + 37], true
96	}
97	return nil, false
98}
99
100// SEC 1 PEM of a P-256 key: d and its public point.
101pem_of :: proc(d, pub: []u8) -> string {
102	der := join({0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20}, d, {0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00}, pub)
103	s := base64.encode(der)
104	b := strings.builder_make()
105	label := cat("EC PRIV", "ATE KEY") // split, so exhibit 14's search for a key's shape does not find this line
106	strings.write_string(&b, cat("-----BEGIN ", label, "-----\n"))
107	for i := 0; i < len(s); i += 64 {strings.write_string(&b, s[i:min(i + 64, len(s))]); strings.write_byte(&b, '\n')}
108	strings.write_string(&b, cat("-----END ", label, "-----\n"))
109	return strings.to_string(b)
110}
111
112// An ES256 signature (DER, as WebAuthn wants) over msg with the key in pem.
113es256_sign :: proc(pem: string, msg: []u8) -> ([]u8, bool) {
114	d, ok := pem_scalar(pem)
115	if !ok do return nil, false
116	k: ecdsa.Private_Key
117	if !ecdsa.private_key_set_bytes(&k, .SECP256R1, d) do return nil, false
118	return ecdsa.sign_asn1(&k, .SHA256, msg, context.allocator)
119}
120
121// ---- CBOR, just enough for a COSE key and an attestation object -------------------------------------
122
123cbor_head :: proc(major: u8, n: int) -> []u8 {
124	if n < 24 do return bs(major << 5 | u8(n))
125	if n < 256 do return bs(major << 5 | 24, u8(n))
126	return bs(major << 5 | 25, u8(n >> 8), u8(n))
127}
128cbor_int :: proc(n: int) -> []u8 {return cbor_head(0, n) if n >= 0 else cbor_head(1, -1 - n)}
129cbor_bytes :: proc(b: []u8) -> []u8 {return join(cbor_head(2, len(b)), b)}
130cbor_text :: proc(s: string) -> []u8 {return join(cbor_head(3, len(s)), transmute([]u8)s)}
131
132// ---- the robot -----------------------------------------------------------------------------------
133
134ROBOT_FILE :: "robot.json"
135
136robot_file :: proc() -> (r: Robot_File, ok: bool) {
137	b, err := rc.read_file(ROBOT_FILE)
138	if err != 0 || len(b) == 0 do return {}, false
139	// unmarshal first: a return's values are read left to right, so `return r, unmarshal(&r)` returns the empty r
140	ok = json.unmarshal(b, &r) == nil && r.key != ""
141	return r, ok
142}
143
144// The robot's passkey and counter, written whole or not at all (the host writes a temp file and
145// renames it): a half-written file would read as "no robot", the next run would register
146// zoo-robot-1, and the real robot's name would be stranded.
147robot_save :: proc(r: Robot_File) {
148	if rc.write_file(ROBOT_FILE, transmute([]u8)to_json(r)) != 0 do panic("could not save the robot's state")
149}
150
151rp_id :: proc() -> string {return domain_host(env().accounts)}
152domain_host :: proc(url: string) -> string {
153	s := strings.trim_prefix(strings.trim_prefix(url, "https://"), "http://")
154	if i := strings.index_byte(s, '/'); i >= 0 do s = s[:i]
155	return s
156}
157
158account_api :: proc(b: ^Browser, name: string, in_ := "{}") -> (int, json.Value) {
159	r := post(b, cat(env().accounts, "/api/", name), in_)
160	return r.status, r.j
161}
162
163// Make the robot's account (once per environment) and give it a picture.
164robot_register :: proc(b: ^Browser) -> (Robot_File, string) {
165	k: ecdsa.Private_Key
166	if !ecdsa.private_key_generate(&k, .SECP256R1) do return {}, "could not make a key"
167	d := make([]u8, 32)
168	ecdsa.private_key_bytes(&k, d)
169	pub := make([]u8, 65)
170	ecdsa.private_key_public_bytes(&k, pub)
171	cred := random_bytes(16)
172	// If a previous robot.json was lost, its name is retired for good: take the next free one.
173	code: int
174	o: json.Value
175	for i in 0 ..< 5 {
176		name := ROBOT_NAME if i == 0 else fmt.tprintf("%s-%d", ROBOT_NAME, i)
177		code, o = account_api(b, "register-start", fmt.tprintf(`{{"username":%s}}`, jq(name)))
178		if code == 200 do break
179	}
180	if code != 200 do return {}, cat("account would not register a robot: ", to_json(o))
181	cose := join(cbor_head(5, 5), cbor_int(1), cbor_int(2), cbor_int(3), cbor_int(-7), cbor_int(-1), cbor_int(1), cbor_int(-2), cbor_bytes(pub[1:33]), cbor_int(-3), cbor_bytes(pub[33:65]))
182	ad := join(sha256s(rp_id()), {0x45}, be32(0), make([]u8, 16), be16(16), cred, cose)
183	att := join(cbor_head(5, 3), cbor_text("fmt"), cbor_text("none"), cbor_text("attStmt"), cbor_head(5, 0), cbor_text("authData"), cbor_bytes(ad))
184	cdj := fmt.tprintf(`{{"type":"webauthn.create","challenge":%s,"origin":%s,"crossOrigin":false}}`, jq(jstr(o, "challenge")), jq(env().accounts))
185	code2, j := account_api(b, "register-finish", fmt.tprintf(`{{"clientDataJSON":%s,"attestationObject":%s}}`, jq(b64u(bytes_of(cdj))), jq(b64u(att))))
186	if code2 != 200 do return {}, cat("robot registration failed: ", to_json(j))
187	r := Robot_File{username = jstr(j, "user", "username"), id = jint(j, "user", "id"), cred = b64u(cred), key = pem_of(d, pub), count = 0}
188	robot_save(r)
189	account_api(b, "profile", `{"name":"Zoo Robot"}`)
190	account_api(b, "picture", fmt.tprintf(`{{"image":%s}}`, jq(b64(robot_picture()))))
191	return r, ""
192}
193
194g_robot: ^Browser
195g_robot_at: map[string]bool
196
197// A WebAuthn assertion with the robot's passkey over this challenge: the counter goes up first,
198// under the robot's lock (one counter value per signature). The fields account's *-finish wants.
199@(private = "file")
200robot_assert :: proc(challenge: string) -> (string, string) {
201	r, ok := robot_file()
202	if !ok do return "", "the robot's robot.json is gone"
203	// The signature counter must go up every time. Time does, even after a restore from backup.
204	r.count = max(r.count + 1, now())
205	ad := join(sha256s(rp_id()), {0x05}, be32(u32(r.count)))
206	cdj := fmt.tprintf(`{{"type":"webauthn.get","challenge":%s,"origin":%s}}`, jq(challenge), jq(env().accounts))
207	sig, sok := es256_sign(r.key, join(ad, sha256s(cdj)))
208	if !sok do return "", "the robot's key did not sign"
209	robot_save(r)
210	return fmt.tprintf(`{{"id":%s,"clientDataJSON":%s,"authenticatorData":%s,"signature":%s}}`, jq(r.cred), jq(b64u(bytes_of(cdj))), jq(b64u(ad)), jq(b64u(sig))), ""
211}
212
213// A browser signed in as the robot at account, or why not. One sign-in per instance.
214robot :: proc() -> (^Browser, string) {
215	if g_robot != nil do return g_robot, ""
216	lk := lock_open("robot.json.lock")
217	defer lock_close(lk)
218	lock_wait(lk, 30_000) // the job's check and a web check never sign in with one counter value
219	b := new_browser()
220	if _, ok := robot_file(); !ok {
221		if _, err := robot_register(b); err != "" do return nil, err
222	}
223	account_api(b, "signout") // registering signed it in; start clean either way
224	code, o := account_api(b, "login-start")
225	if code != 200 do return nil, fmt.tprintf("account login-start answered %d", code)
226	fin, err := robot_assert(jstr(o, "challenge"))
227	if err != "" do return nil, err
228	code2, j := account_api(b, "login-finish", fin)
229	if code2 != 200 do return nil, fmt.tprintf("the robot could not sign in at account (%d): %s", code2, jstr(j, "error"))
230	g_robot = b
231	g_robot_at = make(map[string]bool)
232	return b, ""
233}
234
235// At the end of the instance: sign the robot out at account, if it signed in.
236robot_done :: proc() {
237	if g_robot != nil do account_api(g_robot, "signout")
238	g_robot = nil
239}
240
241Robot_User :: struct {
242	id:       i64,
243	username: string,
244}
245robot_user :: proc() -> Robot_User {
246	r, _ := robot_file()
247	return {r.id, r.username}
248}
249
250// The robot's browser after a page load at app (default: the zoo), so its token is there too.
251robot_at :: proc(app := "") -> (^Browser, string) {
252	b, err := robot()
253	if err != "" do return nil, err
254	if !g_robot_at[app] {
255		url := self_url() if app == "" else cat(rc.app_url(app), "/")
256		r := visit(b, url)
257		if r.status != 200 do return nil, fmt.tprintf("%s answered the robot with %d", "the zoo" if app == "" else app, r.status)
258		g_robot_at[app] = true
259	}
260	return b, ""
261}
262
263// A passkey approval of exactly this action and params, as the robot (account README, "Approvals"):
264// the same two calls account's /approve page makes, signed with the robot's software passkey, for
265// app to file with aud (root). The approval, or why not.
266robot_approve :: proc(app, action, params_json: string, aud := "root") -> (string, string) {
267	b, err := robot()
268	if err != "" do return "", err
269	lk := lock_open("robot.json.lock")
270	defer lock_close(lk)
271	lock_wait(lk, 30_000) // one counter value per signature, as at sign-in
272	code, o := account_api(b, "approve-start", fmt.tprintf(`{{"app":%s,"aud":%s,"action":%s,"params":%s}}`, jq(app), jq(aud), jq(action), params_json))
273	if code != 200 || jstr(o, "challenge") == "" do return "", fmt.tprintf("account would not start an approval of %s (%d): %s", action, code, jstr(o, "error"))
274	fin, ferr := robot_assert(jstr(o, "challenge"))
275	if ferr != "" do return "", ferr
276	code2, j := account_api(b, "approve-finish", fin)
277	if code2 != 200 || jstr(j, "approval") == "" do return "", fmt.tprintf("account would not sign the approval of %s (%d): %s", action, code2, jstr(j, "error"))
278	return jstr(j, "approval"), ""
279}
280
281// A little robot face, drawn here so the guestbook has a picture to show.
282robot_picture :: proc() -> []u8 {
283	im := image_new(128, 128, {{46, 125, 90}, {240, 240, 230}, {30, 30, 30}})
284	fill_rect(&im, 24, 34, 104, 100, 1)
285	fill_ellipse(&im, 48, 60, 8, 2)
286	fill_ellipse(&im, 80, 60, 8, 2)
287	fill_rect(&im, 46, 82, 82, 88, 2)
288	fill_rect(&im, 61, 18, 67, 34, 1)
289	return png_encode(&im)
290}