Zoo

← back to the zoo

11. Private streams stay private

A live stream meant for one person can't be read by someone who guesses its name.

Add `auth` to a channel in ratcloud.conf, and the app decides who may listen: nginx asks it first (rc.serve's channel_auth gets the channel and its id).

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 (live). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e11_private_streams.odin sha256 a5e0bb62c569 · raw

1package main
2
3// Exhibit 11. A channel declared with `auth` (`channels = mine auth`) makes nginx ask the app before
4// anyone may listen: the host runs the app with the channel's name and id (rc.serve's channel_auth,
5// main.odin), and the app says yes or no. The names are guessable on purpose ("u" + your user id):
6// the gate, not the name, keeps them private.
7
8import "core:encoding/json"
9import "core:fmt"
10import "core:strings"
11import "core:time"
12import "ratcloud:rc"
13
14e11 :: proc() -> Exhibit {
15	return {
16		n = 11, wing = "Realtime",
17		title = "Private streams stay private",
18		promise = "A live stream meant for one person can't be read by someone who guesses its name.",
19		block = "Add `auth` to a channel in ratcloud.conf, and the app decides who may listen: nginx asks it first (rc.serve's channel_auth gets the channel and its id).",
20		src = {"e11_private_streams.odin", #load("e11_private_streams.odin", string)},
21		files = srcs(SELF_SRC, {"robot.odin", #load("robot.odin", string)}),
22		script = {"web/e11.js", #load("web/e11.js", string)},
23		channel = proc(name, id: string, me: ^rc.User) -> (bool, bool) {
24			if name != "mine" do return false, false
25			return me != nil && id == fmt.tprintf("u%d", me.id), true
26		},
27		show = proc(me: ^rc.User) -> string {
28			own := signin_line("to get a stream of your own.")
29			if me != nil do own = fmt.tprintf(`<p>Your stream is <code>mine/u%d</code>. <button id="ping">Send myself a ping</button></p><ul class="list" id="pings"></ul>`, me.id)
30			guess := me.id + 1 if me != nil else 1
31			return cat(own, fmt.tprintf(`<p><button id="eavesdrop" data-guess="u%d">Listen to someone else's (mine/u%d)</button> <span class="out" id="eaves-out"></span></p>`, guess, guess))
32		},
33		api = proc(a: ^Api) -> bool {
34			if a.do_ != "ping" || !a.post do return false
35			if a.me == nil {reply_err(a, 401, "sign in to have a stream"); return true}
36			ok := publish("mine", fmt.tprintf("u%d", a.me.id), fmt.tprintf(`{{"text":%s,"at":%s}}`, jq(cat("ping for @", a.me.username)), jq(iso(now()))))
37			reply_raw(a, fmt.tprintf(`{{"published":%v}}`, ok))
38			return true
39		},
40		// The robot hears its own stream; nobody else, signed in or not, may listen to it.
41		check = proc() -> Check {
42			b, err := robot_at()
43			if err != "" do return fail(err)
44			id := fmt.tprintf("u%d", robot_user().id)
45			l := listen_open(b, {self_url(cat("/rc/sub/mine/", id))}, 2000)
46			defer listen_close(&l)
47			if l.status[0] != 200 do return fail(fmt.tprintf("the robot was refused its own stream (%d)", l.status[0]))
48			t0 := time.tick_now()
49			post(b, self_url("/api/11/ping"))
50			want :: proc(v: json.Value, arg: rawptr) -> bool {return strings.has_prefix(jstr(v, "text"), "ping")}
51			seen, ms := listen_wait(&l, t0, want, nil)
52			if seen == 0 do return fail("the robot's own stream opened but its ping never came")
53			Try :: struct {
54				who: string,
55				b:   ^Browser,
56				url: string,
57			}
58			tries := []Try {
59				{"a visitor, on the robot's stream", new_browser(), self_url(cat("/rc/sub/mine/", id))},
60				{"the robot, on someone else's", b, self_url(fmt.tprintf("/rc/sub/mine/u%d", robot_user().id + 1))},
61				{"the robot, on a stream with no name", b, self_url("/rc/sub/mine")},
62			}
63			for t in tries {
64				x := listen_open(t.b, {t.url}, 0)
65				listen_close(&x)
66				if x.status[0] != 403 do return fail(fmt.tprintf("%s: answered %d, not refused", t.who, x.status[0]))
67			}
68			return pass(fmt.tprintf("the robot heard its own ping (%dms); a visitor and the robot on someone else's stream were refused (403)", ms))
69		},
70	}
71}

main.odin sha256 0eb573c11997 · raw

1package main
2
3// The zoo: every promise in ZOO.md as an exhibit, working live, with a light. Odin on the wasm
4// runtime: one fresh instance per request and per job run.
5//
6//   /                    every exhibit and its light
7//   /api/<n>/<do>        an exhibit's JSON (check: run its check now; seen: "this worked for me")
8//   /how/<n>             the exhibit's source, the bytes this very program was built from (exhibit 19)
9//   /lights.json         every light, for tests and anyone curious
10//   /index.txt           one line per exhibit (promise and building block), for a model's brief
11//   /how/<n>.txt         exhibit n's files as plain text
12//   /platform.md         what an app gets: root's PLATFORM.md, the running version, for anyone
13//
14// nginx also asks whether a browser may listen on an `auth` channel (channel_ok); and the host runs
15// the jobs of ratcloud.conf's `cron` (job): tick, selfcheck, nightly, workbench.
16
17import "core:encoding/json"
18import "core:fmt"
19import "core:strings"
20import "core:time"
21import "ratcloud:rc"
22
23main :: proc() {
24	rc.serve(handle, channel_ok, job)
25}
26
27SELF_SRC :: Src{"main.odin", #load("main.odin", string)}
28
29channel_ok :: proc(r: ^rc.Request, channel, id: string) -> bool {
30	u, signed := rc.me()
31	me := &u if signed else nil
32	for &e in exhibits() {
33		if e.channel == nil do continue
34		if allow, mine := e.channel(channel, id, me); mine do return allow
35	}
36	return false
37}
38
39g_req: ^rc.Request
40
41handle :: proc(r: ^rc.Request, w: ^rc.Response) {
42	g_req = r
43	defer robot_done()
44	u, signed := rc.me()
45	me := &u if signed else nil
46	path := r.path
47
48	if strings.has_prefix(path, "/api/") {
49		api(r, w, me)
50		return
51	}
52	if strings.has_prefix(path, "/how/") {
53		rest := path[5:]
54		if strings.has_suffix(rest, ".txt") {how_txt(w, int(atoi(rest[:len(rest) - 4]))); return}
55		how_page(r, w, int(atoi(rest)), me)
56		return
57	}
58	switch path {
59	case "/": page(w, me); return
60	case "/lights.json": lights_json(w); return
61	case "/index.txt":
62		// A model's brief lists the exhibits, one line each.
63		rc.set_header(w, "Content-Type", "text/plain; charset=utf-8")
64		rc.set_header(w, "Cache-Control", "max-age=300")
65		for e in exhibits() do rc.write(w, fmt.tprintf("%d. %s (%s%s): %s\n", e.n, e.title, e.wing, ", not built yet" if e.kind == "waiting" else "", e.block))
66		return
67	case "/platform.md":
68		// Root publishes PLATFORM.md into every app's facts; the zoo, being the documentation, serves
69		// its copy so a model working in a clone (no facts there) reads the version that is running.
70		doc, ok := rc.fact("PLATFORM.md")
71		rc.status(w, 200 if ok else 404)
72		rc.set_header(w, "Content-Type", "text/markdown; charset=utf-8")
73		rc.set_header(w, "Cache-Control", "max-age=300")
74		rc.write(w, doc if ok else "PLATFORM.md is not published here yet.\n")
75		return
76	}
77	rc.status(w, 404)
78	rc.set_header(w, "Cache-Control", "no-store")
79	rc.render(w, NOT_FOUND_HTML, {{"head", rc.raw(rc_head())}, {"header", rc.raw(rc_header("Zoo", me, "/api/3/signout", false))}})
80}
81
82NOT_FOUND_HTML :: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Not found · Zoo</title>{{head}}</head><body>{{header}}<main class="rc-main"><div class="rc-empty"><b>Nothing here</b><p>The zoo has no page at this address.</p><a class="button primary" href="/">Go to the zoo</a></div></main></body></html>`
83
84// ---- /api/<n>/<do> ----
85
86Api :: struct {
87	r:    ^rc.Request,
88	w:    ^rc.Response,
89	do_:  string,
90	me:   ^rc.User,
91	post: bool,
92	in_:  json.Value, // the POST's JSON body, or the query as an object of strings
93}
94
95reply :: proc(a: ^Api, v: any, status := 200) {
96	rc.status(a.w, status)
97	rc.set_header(a.w, "Cache-Control", "no-store")
98	rc.set_header(a.w, "Content-Type", "application/json")
99	rc.write(a.w, to_json(v))
100	rc.write(a.w, "\n")
101}
102reply_raw :: proc(a: ^Api, json_text: string, status := 200) {
103	rc.status(a.w, status)
104	rc.set_header(a.w, "Cache-Control", "no-store")
105	rc.set_header(a.w, "Content-Type", "application/json")
106	rc.write(a.w, json_text)
107	rc.write(a.w, "\n")
108}
109reply_err :: proc(a: ^Api, status: int, msg: string) {
110	reply_raw(a, fmt.tprintf(`{{"error":%s}}`, jq(msg)), status)
111}
112in_str :: proc(a: ^Api, k: string) -> string {return jstr(a.in_, k)}
113in_int :: proc(a: ^Api, k: string) -> i64 {return jint(a.in_, k)}
114
115api :: proc(r: ^rc.Request, w: ^rc.Response, me: ^rc.User) {
116	a := Api{r = r, w = w, me = me, post = r.method == "POST"}
117	rest := r.path[5:]
118	slash := strings.index_byte(rest, '/')
119	if slash < 0 {reply_err(&a, 404, "no such exhibit"); return}
120	n := int(atoi(rest[:slash]))
121	a.do_ = rest[slash + 1:]
122	e, ok := exhibit(n)
123	if !ok || itoa(i64(n)) != rest[:slash] {reply_err(&a, 404, "no such exhibit"); return}
124	if !rc.csrf_ok(r) {reply_err(&a, 403, "refused: not from the zoo's own page"); return}
125	if a.post {
126		body, _ := rc.body(r)
127		if v, err := json.parse(body, parse_integers = true); err == nil do a.in_ = v
128	} else {
129		o := make(json.Object)
130		for k, v in rc.query(r) do o[k] = json.String(v)
131		a.in_ = o
132	}
133	if a.do_ == "check" && e.check != nil {
134		// POST runs it now, unless it ran (or started) in the last 15 seconds: anyone can press this,
135		// and a run costs a robot sign-in, a model call, B2 and push. The slot is taken atomically, so
136		// a burst runs it once. GET (an <img> anywhere) only reads the light.
137		if a.post && claim_check(e.n, 15) do run_check(e)
138		s, found := stored(e.n)
139		if !found {
140			reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":false,"detail":"not checked yet","at":null,"data":null}}`, e.n, jq(e.title)))
141			return
142		}
143		reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":%v,"detail":%s,"at":%s,"data":%s}}`, e.n, jq(e.title), s.ok, jq(s.detail), jq(iso(s.at)), s.data if s.data != "" else "null"))
144		return
145	}
146	if a.do_ == "seen" && a.post && e.kind == "human" {
147		if me == nil {reply_err(&a, 401, "sign in first, so the zoo can say who saw it work"); return}
148		seen(e.n, me.id)
149		l := light(e)
150		reply_raw(&a, fmt.tprintf(`{{"ok":true,"light":{{"color":%s,"text":%s}}}}`, jq(l.color), jq(l.text)))
151		return
152	}
153	if e.api != nil && e.api(&a) do return
154	reply_err(&a, 404, fmt.tprintf("exhibit %d has no '%s'", e.n, a.do_))
155}
156
157// ---- /lights.json ----
158
159lights_json :: proc(w: ^rc.Response) {
160	b := strings.builder_make()
161	checked := meta_int("checked_at")
162	fmt.sbprintf(&b, `{{"env":%s,"checked":%s,"lights":[`, jq(env().env), jq(iso(checked)) if checked > 0 else "null")
163	for &e, i in exhibits() {
164		l := light(&e)
165		if i > 0 do strings.write_byte(&b, ',')
166		fmt.sbprintf(&b, `{{"n":%d,"title":%s,"kind":%s,"color":%s,"text":%s,"at":%s}}`, e.n, jq(e.title), jq(e.kind), jq(l.color), jq(l.text), jq(iso(l.at)) if l.at > 0 else "null")
167	}
168	strings.write_string(&b, `],"alerts":[`)
169	for x, i in alerts_recent(10) {
170		if i > 0 do strings.write_byte(&b, ',')
171		fmt.sbprintf(&b, `{{"at":%s,"kind":%s,"title":%s,"body":%s,"results":%s}}`, jq(iso(x.at)), jq(x.kind), jq(x.title), jq(x.body), x.results)
172	}
173	strings.write_string(&b, "]}\n")
174	rc.set_header(w, "Content-Type", "application/json")
175	rc.set_header(w, "Cache-Control", "no-store")
176	rc.write(w, strings.to_string(b))
177}
178
179// ---- the jobs (ratcloud.conf `cron`): the host runs each in a fresh instance on its schedule ----
180
181job :: proc(name: string, w: ^rc.Response) {
182	defer robot_done()
183	switch name {
184	case "tick":
185		// Exhibit 21: write the time. That is all.
186		meta_set("last_tick", itoa(now()))
187	case "selfcheck":
188		selfcheck(w)
189	case "nightly":
190		// Exhibit 8's upkeep: if a valid push replaced zoo-broken's deliberate typo, put it back.
191		res := broken_reassert()
192		res.at = now()
193		meta_set("broken.nightly", to_json(res))
194		rc.write(w, fmt.tprintf("exhibit 8 upkeep (%s): %s: %s\n", res.branch, res.result, res.detail))
195		if res.result != "still refused" && res.result != "put back" do rc.status(w, 500)
196	case "workbench":
197		// Exhibit 25's run in the robot's workbench: at most once a day, live only.
198		if said, did := e25_job(); did {
199			rc.write(w, said)
200			rc.write(w, "\n")
201			if strings.contains(said, "FAILED") do rc.status(w, 500)
202		}
203	case:
204		rc.status(w, 404)
205		rc.write(w, fmt.tprintf("no job %q\n", name))
206	}
207}
208
209// Exhibit 22's job: every five minutes, run every self-running exhibit's check and store the results
210// as lights. Exhibit 22 runs last, since it judges the others.
211selfcheck :: proc(w: ^rc.Response) {
212	t0 := time.tick_now()
213	g_in_job = true
214	last: ^Exhibit
215	for &e in exhibits() {
216		if e.n == 22 {last = &e; continue}
217		if e.check == nil || e.kind != "self" do continue
218		r := run_check(&e)
219		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
220	}
221	if last != nil {
222		r := run_check(last)
223		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
224	}
225	alerts_run(w)
226	meta_set("checked_at", itoa(now()))
227	meta_set("checked_ms", itoa(i64(time.duration_milliseconds(time.tick_since(t0)))))
228	rc.write(w, fmt.tprintf("checked in %d ms, memory %d KiB\n", i64(time.duration_milliseconds(time.tick_since(t0))), rc.bump_top() / 1024))
229}
230
231// The five-minute job, not a "check now" from the page (PHP's PHP_SAPI === "cli"): the rounds that
232// take minutes (18, 29, 30) start only here, where the job's own time allows them.
233g_in_job: bool

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}

web/e11.js sha256 0dc7e1e40305 · raw

1(() => {
2  const list = document.getElementById("pings");
3  if (list && zoo.me) {
4    const es = new EventSource("/rc/sub/mine/u" + zoo.me);
5    es.onmessage = (m) => { const j = JSON.parse(m.data); list.insertAdjacentHTML("afterbegin", "<li>" + zoo.esc(j.text) + " · " + zoo.ago(j.at) + "</li>"); };
6    document.getElementById("ping").addEventListener("click", () => zoo.call("/api/11/ping", {}));
7  }
8  document.getElementById("eavesdrop")?.addEventListener("click", async (ev) => {
9    const out = document.getElementById("eaves-out");
10    const ctl = new AbortController();
11    try {
12      const r = await fetch("/rc/sub/mine/" + ev.target.dataset.guess, { headers: { Accept: "text/event-stream" }, signal: ctl.signal });
13      out.innerHTML = r.status === 403 ? '<span class="tag refused">refused</span>' : '<span class="tag opened">connected (' + r.status + ')</span>';
14    } catch (e) { out.textContent = "error: " + e.message; }
15    ctl.abort();
16  });
17})();