Zoo

← back to the zoo

26. Sealed means sealed

A file an app seals for you opens on your devices and nowhere else; the server keeps only what it cannot read.

storage's sealing block: rc-crypt.js and rc-seal.js (https://storage.<domain>/seal/v1/) seal in the browser with a key only your devices and your recovery key open; the app's server forwards keyring calls and stores envelopes it cannot read.

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.

e26_sealed.odin sha256 179547cf42ef · raw

1package main
2
3// Exhibit 26. The zoo seals a postcard the way any app would with storage's sealing block: the page
4// loads rc-crypt.js and rc-seal.js from storage (pinned by hash), the key is made and kept in the
5// browser (wrapped to the root storage's window hands over, never this server), the words are sealed
6// there into an envelope, and the envelope goes through the public paths: app/begin, a PUT straight
7// to B2, app/commit, app/urls. This server only forwards (/api/26/storage, below) and never sees a
8// key. The self-check plays the person's browser in Odin (robotseal.odin, seal.odin).
9
10import "core:encoding/json"
11import "core:fmt"
12import "core:strings"
13import "ratcloud:rc"
14
15// storage's scripts, by hash: a page that runs whatever storage serves would run whatever storage's
16// server says; pinned, a changed file is refused and this card says so.
17SEAL_JS := [2][2]string {
18	{"rc-crypt.js", "sha384-bC+ArqaU/QjwcbSzAMUu6nMqClMDFOG4cHed3KFtzzYt052HX2z+hJ0Timbw2yoX"},
19	{"rc-seal.js", "sha384-9iwPEKMkzo7FSo5YaKL+wOCJSA+zaGiotVBJcMkzBnGex/wljIj/v1Nkz5mHu2rF"},
20}
21POSTCARD_MAX :: 65536 // the zoo seals postcards of words, nothing bigger, into a person's storage
22
23E26_Data :: struct {
24	id:        i64 `json:"id"`,
25	size:      int `json:"size"`,
26	at:        i64 `json:"at"`,
27	head:      string `json:"head"`,
28	words:     int `json:"words"`,
29	sealcheck: json.Value `json:"sealcheck"`,
30	amber:     bool `json:"amber,omitempty"`,
31}
32
33e26 :: proc() -> Exhibit {
34	return {
35		n = 26, try_ = "seal a postcard", wing = "Sealed",
36		title = "Sealed means sealed",
37		promise = "A file an app seals for you opens on your devices and nowhere else; the server keeps only what it cannot read.",
38		block = "storage's sealing block: rc-crypt.js and rc-seal.js (https://storage.<domain>/seal/v1/) seal in the browser with a key only your devices and your recovery key open; the app's server forwards keyring calls and stores envelopes it cannot read.",
39		src = {"e26_sealed.odin", #load("e26_sealed.odin", string)},
40		files = srcs({"bulk.odin", #load("bulk.odin", string)}, {"robotseal.odin", #load("robotseal.odin", string)}, {"seal.odin", #load("seal.odin", string)}),
41		script = {"web/e26.js", #load("web/e26.js", string)},
42		show = proc(me: ^rc.User) -> string {
43			d, s, found := stored_data(26, E26_Data)
44			last := ""
45			if found && s.ok do last = fmt.tprintf(`<p class="muted small">The self-check seals a fresh postcard for the robot each time, %s: %d bytes in the bucket, none of them its words.</p>`, ago(s.at), d.size)
46			if me == nil do return cat(signin_line("to seal a postcard only your devices can open."), last)
47			tags := strings.builder_make()
48			for f in SEAL_JS do rc.render_to(&tags, `<script src="{{1}}/seal/v1/{{2}}" integrity="{{3}}" crossorigin="anonymous"></script>`, {{"1", rc.app_url("storage")}, {"2", f[0]}, {"3", f[1]}})
49			return cat(strings.to_string(tags), fmt.tprintf(`<div id="seal26" class="sealed" data-user="%d"><p class="muted">Loading…</p></div>`, me.id), last)
50		},
51		// The app's own route to storage for its page: keyring calls as they are; begin only for the
52		// postcard, sealed; commit and urls as they are. Storage checks the person and the folder.
53		api = proc(a: ^Api) -> bool {
54			if a.do_ != "storage" || !a.post do return false
55			if a.me == nil {reply_err(a, 401, "sign in first"); return true}
56			op := in_str(a, "op")
57			body := jget(a.in_, "body")
58			if _, isobj := body.(json.Object); !isobj do body = json.Object{}
59			switch op {
60			case "keyring", "commit":
61			case "begin":
62				f := jarr(body, "files")
63				if len(f) != 1 || jstr(f[0], "path") != POSTCARD || jstr(f[0], "type") != ENV_TYPE || jint(f[0], "size") > POSTCARD_MAX {reply_err(a, 400, "the zoo saves one sealed postcard, at most 64 KB"); return true}
64			case "urls":
65				body = parse(fmt.tprintf(`{{"paths":[%s]}}`, jq(POSTCARD)))
66			case:
67				reply_err(a, 400, "no such call")
68				return true
69			}
70			s, r := storage_call(op, to_json(body))
71			// storage's answer as it is, with its status
72			reply_raw(a, to_json(r), s if s != 0 else 502)
73			return true
74		},
75		check = proc() -> Check {
76			s, err := robot_sealing()
77			if err != "" do return fail(err)
78			k, kr, kerr := robot_zoo_key(&s)
79			if kerr != "" do return fail(kerr)
80			words := postcard_words()
81			file, env_, perr := robot_seal_postcard(k, words)
82			if perr != "" do return fail(perr)
83			_, held, berr := robot_postcard_bytes()
84			if berr != "" do return fail(berr)
85			sp := strings.last_index_byte(words, ' ')
86			word := words[sp + 1:len(words) - 1]
87			if !eq_bytes(held, env_) do return fail("the bucket holds other bytes than the robot sealed")
88			if string(held[:4]) != "RCE1" do return fail("the stored object does not start with an envelope header")
89			if strings.contains(string(held), word) || strings.contains(string(held), "robot") do return fail("the stored bytes contain the words")
90			Keys :: struct {
91				id: string,
92				k:  []u8,
93			}
94			ks := Keys{kr.mk_id, k}
95			key_for :: proc(id: string, arg: rawptr) -> []u8 {x := (^Keys)(arg); return x.k if id == x.id else nil}
96			back, oerr := envelope_open(key_for, &ks, held)
97			if oerr != "" do return fail(cat("the robot's own device cannot open what it sealed: ", oerr))
98			if string(back) != words do return fail("the robot's device opened other words than it sealed")
99			wrong := Keys{kr.mk_id, random_bytes(32)}
100			if _, werr := envelope_open(key_for, &wrong, held); werr == "" do return fail("a key that is not the robot's opened the postcard")
101			// Back of house (ST-2): last night's sample of sealed objects, each starting with an envelope header.
102			scr := rc.fetch({url = cat(rc.app_url("storage"), "/sealcheck.json"), timeout_ms = 10_000})
103			sc := parse(string(scr.body))
104			night := "the nightly header check has not run yet"
105			ran := jhas(sc, "at") && jbool(sc, "at")
106			if ran do night = fmt.tprintf("last night's header check: %d of %d sealed objects sampled, every one an envelope", jint(sc, "sampled"), jint(sc, "sealed")) if jbool(sc, "ok") else fmt.tprintf("last night's header check found %d sealed object(s) without an envelope header", jint(sc, "bad"))
107			data := E26_Data{jint(file, "id"), len(held), jint(file, "updated"), hex(held[:24]), len(words), sc, false}
108			if ran && !jbool(sc, "ok") do return fail(night, data)
109			if ran && now() - jint(sc, "at") > 26 * 3600 do data.amber = true
110			return pass(fmt.tprintf("sealed %d characters for the robot into a %d-byte envelope (Apps/Zoo/sealed/postcard.rce, file %d): the bucket's bytes hold none of the words and open only with the robot's key; %s", len(words), len(held), jint(file, "id"), night), data)
111		},
112	}
113}

bulk.odin sha256 ffb0f70ced2f · raw

1package main
2
3// Storage in bulk, the way any app calls it (storage's README, "For an app: in bulk"): a JSON call to
4// storage with rc.app_headers("storage", true), and the bytes straight to B2 and back on the
5// presigned URLs it hands out. No storage key, and no byte passes through storage's own code.
6//
7//     storage_call("begin", `{"files":[{"path":"postcards/a.png","size":812,"type":"image/png"}]}`)
8//     // files[0]: {id, url, type, size, expires}; PUT the bytes to url with that Content-Type
9//     storage_call("commit", `{"ids":[...]}`)       // one B2 listing for the whole begin
10//     storage_call("urls", `{"ids":[...]}`)         // presigned GETs, five minutes each
11//     storage_call("list", `{"after":0,"limit":1000}`)   // what the zoo saved for this person
12
13import "core:encoding/json"
14import "core:fmt"
15import "ratcloud:rc"
16
17storage_call :: proc(op: string, in_json: string) -> (int, json.Value) {
18	a := call_app("storage", cat("/app/", op), true, "POST", in_json, "application/json")
19	if v := parse(a.body); v != nil do return a.status, v
20	return a.status, parse(fmt.tprintf(`{{"error":%s}}`, jq(fmt.tprintf("storage answered %d: %s %s", a.status, clip(a.body, 160), a.err))))
21}
22
23Put :: struct {
24	url, type: string,
25	body:      []u8,
26}
27
28// At most this many calls at once: the host lets one request hold 16 open calls.
29MANY :: 15
30
31// PUT many bodies to their presigned URLs, MANY at a time: their statuses, in order. B2 answers a
32// PUT now and then with 500 or 503 and asks clients to send it again (as storage does with its own
33// B2 calls); a dropped connection (0) is sent again too. Twice more at most: the URL is the same, so
34// a PUT that did arrive is simply replaced by the same bytes.
35put_many :: proc(jobs: []Put) -> []int {
36	out := make([]int, len(jobs))
37	todo := make([dynamic]int)
38	for i in 0 ..< len(jobs) do append(&todo, i)
39	for try in 0 ..< 3 {
40		if try > 0 do rc.sleep(500)
41		for start := 0; start < len(todo); start += MANY {
42			chunk := todo[start:min(start + MANY, len(todo))]
43			calls := make([]rc.Fetch_Call, len(chunk))
44			for i, k in chunk {
45				hs := make(map[string]string)
46				hs["Content-Type"] = jobs[i].type
47				calls[k] = rc.fetch_start({method = "PUT", url = jobs[i].url, headers = hs, body = jobs[i].body, timeout_ms = 30_000})
48			}
49			buf: [4096]u8
50			for &c, k in calls {
51				out[chunk[k]] = rc.fetch_status(&c)
52				for rc.fetch_read(&c, buf[:]) > 0 {}
53				rc.fetch_close(&c)
54			}
55		}
56		again := make([dynamic]int)
57		for i in todo do if out[i] == 0 || out[i] == 500 || out[i] == 503 do append(&again, i)
58		if len(again) == 0 do break
59		todo = again
60	}
61	return out
62}
63
64Got :: struct {
65	status: int,
66	body:   []u8,
67}
68
69// GET many presigned URLs, MANY at a time: status and body, in order.
70get_many :: proc(urls: []string) -> []Got {
71	out := make([]Got, len(urls))
72	for start := 0; start < len(urls); start += MANY {
73		end := min(start + MANY, len(urls))
74		calls := make([]rc.Fetch_Call, end - start)
75		for k in 0 ..< len(calls) do calls[k] = rc.fetch_start({url = urls[start + k], timeout_ms = 30_000})
76		buf := make([]u8, 16 * 1024)
77		for &c, k in calls {
78			st := rc.fetch_status(&c)
79			body := make([dynamic]u8)
80			for {
81				n := rc.fetch_read(&c, buf)
82				if n <= 0 do break
83				append(&body, ..buf[:n])
84			}
85			rc.fetch_close(&c)
86			out[start + k] = {st, body[:]}
87		}
88	}
89	return out
90}

robotseal.odin sha256 d4dab5c5e496 · raw

1package main
2
3// The robot's sealing, for the self-checks of exhibits 26 and 27. The robot plays a person's browsers
4// the way rc-crypt.js and rc-seal.js do in a real one (seal.odin has the same bytes): at storage
5// (/api/seal, with its storage sign-in), and at the zoo, whose server forwards to storage like any
6// app's (/api/26/storage). It holds what a person holds: each device's private key and the recovery
7// key, in robot-seal.json (the zoo's own data, like the robot's passkey), never a key that opens a
8// file; those are unwrapped again at every check.
9
10import "core:encoding/json"
11import "core:fmt"
12import "core:strings"
13import "ratcloud:rc"
14
15Rdev :: struct {
16	id:    string `json:"id"`,
17	pem:   string `json:"pem"`,
18	pub:   string `json:"pub"`,
19	pin:   string `json:"pin"`,
20	epoch: i64 `json:"epoch"`,
21}
22Rseal :: struct {
23	user:        string `json:"user"`,
24	storage_dev: Rdev `json:"storage_dev"`,
25	zoo_dev:     Rdev `json:"zoo_dev"`,
26	phrase:      string `json:"phrase"`,
27	made:        i64 `json:"made"`,
28}
29
30RSEAL_FILE :: "robot-seal.json"
31POSTCARD :: "sealed/postcard.rce"
32
33rseal_save :: proc(s: Rseal) -> string {
34	if rc.write_file(RSEAL_FILE, transmute([]u8)to_json(s)) != 0 do return "could not save the robot's sealing state"
35	return ""
36}
37
38robot_at_storage :: proc() -> (^Browser, string) {return robot_at("storage")}
39
40// Storage's own page API, as the robot's browser at storage.
41robot_storage_seal :: proc(in_json: string) -> (json.Value, string) {
42	b, err := robot_at_storage()
43	if err != "" do return nil, err
44	r := post(b, cat(rc.app_url("storage"), "/api/seal"), in_json)
45	if r.status != 200 do return nil, fmt.tprintf("storage's /api/seal answered %d: %s", r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120))
46	return r.j, ""
47}
48// The zoo's own route to storage, as the zoo's page calls it.
49robot_zoo_storage :: proc(op, body: string) -> (json.Value, string) {
50	b, err := robot_at()
51	if err != "" do return nil, err
52	r := post(b, self_url("/api/26/storage"), fmt.tprintf(`{{"op":%s,"body":%s}}`, jq(op), body))
53	if r.status != 200 do return nil, fmt.tprintf("the zoo's /api/26/storage (%s) answered %d: %s", op, r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120))
54	return r.j, ""
55}
56
57rdev :: proc(d: Rdev) -> (Dev, bool) {
58	k, ok := ec_load(d.pem)
59	return {id = d.id, priv = k, pub = d.pub, pin = d.pin, epoch = d.epoch}, ok
60}
61new_rdev :: proc() -> Rdev {
62	k := ec_new()
63	return {id = b64u(random_bytes(18)), pem = pem_of(k.d, k.pub), pub = b64(k.pub)}
64}
65rdev_entry :: proc(d: Rdev, k: []u8, via, name: string) -> Kr_Device {
66	w, _ := wrap_for_device(d.pub, k)
67	return {id = d.id, name = name, pub = d.pub, wrap = w, created = now(), via = via}
68}
69
70g_keyring_err: string
71keyring_of :: proc(v: json.Value) -> (kr: Keyring, ok: bool) {
72	if v == nil do return {}, false
73	if _, null := v.(json.Null); null do return {}, false
74	// core:encoding/json does not unmarshal into a pointer: the recovery entry goes in by hand
75	o, isobj := v.(json.Object)
76	if !isobj do return {}, false
77	rec := o["recovery"]
78	delete_key(&o, "recovery")
79	err := json.unmarshal_string(to_json(o), &kr)
80	o["recovery"] = rec
81	if jhas(rec) {
82		r := new(Recovery)
83		if json.unmarshal_string(to_json(rec), r) == nil do kr.recovery = r
84	}
85	if err != nil do g_keyring_err = fmt.tprintf("%v", err)
86	return kr, err == nil
87}
88
89// The robot's devices, set up once per environment: a storage device holding its root (and the
90// recovery key), and a zoo device holding the zoo's key for it.
91robot_sealing :: proc() -> (Rseal, string) {
92	uid := itoa(robot_user().id)
93	s: Rseal
94	if b, err := rc.read_file(RSEAL_FILE); err == 0 && json.unmarshal(b, &s) == nil && s.user == uid && uid != "0" do return s, ""
95	if _, err := robot_at_storage(); err != "" do return {}, err
96	uid = itoa(robot_user().id)
97	have, err := robot_storage_seal(`{"op":"get","fresh":true}`)
98	if err != "" do return {}, err
99	if jhas(have, "keyring") do return {}, "the robot has a keyring at storage but not its devices (robot-seal.json was lost): its sealed postcard cannot be opened"
100	root := random_bytes(32)
101	rb, phrase := new_recovery_key()
102	sd := new_rdev()
103	e := new_root_wrap_key(root)
104	rec := recovery_wrap(rb, root)
105	kr := Keyring{v = 2, mk_id = mk_id(root), epoch = 1, root = e, recovery = &rec, devices = {rdev_entry(sd, root, "created", "Zoo robot")}, older = {}}
106	kr.mac = keyring_mac(root, kr, uid, "-")
107	if _, err2 := robot_storage_seal(fmt.tprintf(`{{"op":"put","keyring":%s,"newproof":%s}}`, to_json(kr), jq(mk_proof(root)))); err2 != "" do return {}, err2
108	sd.pin, sd.epoch = kr.mk_id, 1
109	// The zoo's key, wrapped to the root's public half: the robot holds the root here, so it opens the
110	// entry and the public half it wraps to is the root's own (in a browser: storage's window).
111	if _, rerr := open_root_wrap_key(root, e); rerr != "" do return {}, rerr
112	app := random_bytes(32)
113	zd := new_rdev()
114	akr := Keyring{v = 2, mk_id = mk_id(app), epoch = 1, root = wrap_for_root(e.id, e.pub, "zoo", app), devices = {rdev_entry(zd, app, "created", "Zoo robot")}, older = {}}
115	akr.mac = keyring_mac(app, akr, uid, "zoo")
116	if _, err3 := robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"put","keyring":%s,"newproof":%s}}`, to_json(akr), jq(mk_proof(app)))); err3 != "" do return {}, err3
117	zd.pin, zd.epoch = akr.mk_id, 1
118	s = {user = uid, storage_dev = sd, zoo_dev = zd, phrase = phrase, made = now()}
119	return s, rseal_save(s)
120}
121
122// The zoo's key for the robot, as its zoo device opens it (rc-seal.js's trust()).
123robot_zoo_key :: proc(s: ^Rseal) -> ([]u8, Keyring, string) {
124	j, err := robot_zoo_storage("keyring", `{"op":"get","fresh":true}`)
125	if err != "" do return nil, {}, err
126	kr, ok := keyring_of(jget(j, "keyring"))
127	if !ok do return nil, {}, "the zoo has no keyring for the robot at storage"
128	dev, dok := rdev(s.zoo_dev)
129	if !dok do return nil, {}, "the robot's zoo device key does not load"
130	k, terr := trust_keyring(kr, dev, s.user, "zoo")
131	if terr != "" do return nil, {}, terr
132	s.zoo_dev.pin, s.zoo_dev.epoch = kr.mk_id, kr.epoch
133	if e := rseal_save(s^); e != "" do return nil, {}, e
134	return k, kr, ""
135}
136
137// A keyring the robot changes: one more epoch, its MAC, the proof of the key it holds.
138robot_zoo_write :: proc(s: ^Rseal, k: []u8, kr: Keyring, devices: []Kr_Device) -> (Keyring, string) {
139	next := kr
140	next.epoch = kr.epoch + 1
141	next.devices = devices
142	if next.older == nil do next.older = make([]Kr_Older, 0)
143	next.mac = ""
144	next.mac = keyring_mac(k, next, s.user, "zoo")
145	j, err := robot_zoo_storage("keyring", fmt.tprintf(`{{"op":"put","keyring":%s,"proof":%s}}`, to_json(next), jq(mk_proof(k))))
146	if err != "" do return {}, err
147	out, ok := keyring_of(jget(j, "keyring"))
148	if !ok do return {}, "storage did not hand the keyring back"
149	s.zoo_dev.epoch = out.epoch
150	return out, rseal_save(s^)
151}
152
153// Seal words under the zoo's key and save them as the robot's postcard, through the public paths:
154// begin, the bytes straight to B2, commit. The file and the envelope's bytes.
155robot_seal_postcard :: proc(k: []u8, words: string) -> (json.Value, []u8, string) {
156	env_ := envelope_seal(k, bytes_of(words), "postcard.txt", "text/plain")
157	j, err := robot_zoo_storage("begin", fmt.tprintf(`{{"files":[{{"path":%s,"size":%d,"type":%s}}]}}`, jq(POSTCARD), len(env_), jq(ENV_TYPE)))
158	if err != "" do return nil, nil, err
159	f := jarr(j, "files")
160	if len(f) == 0 || jstr(f[0], "url") == "" do return nil, nil, cat("storage would not begin the postcard: ", to_json(j))
161	put := put_many({{jstr(f[0], "url"), jstr(f[0], "type"), env_}})[0]
162	if put != 200 do return nil, nil, fmt.tprintf("B2 answered the PUT with %d", put)
163	c, cerr := robot_zoo_storage("commit", fmt.tprintf(`{{"ids":[%d]}}`, jint(f[0], "id")))
164	if cerr != "" do return nil, nil, cerr
165	cf := jarr(c, "files")
166	if len(cf) == 0 || !jhas(cf[0], "file") do return nil, nil, cat("storage would not commit the postcard: ", to_json(c))
167	return jget(cf[0], "file"), env_, ""
168}
169
170// The robot's postcard as the bucket holds it (a presigned GET, like a browser's).
171robot_postcard_bytes :: proc() -> (json.Value, []u8, string) {
172	j, err := robot_zoo_storage("urls", fmt.tprintf(`{{"paths":[%s]}}`, jq(POSTCARD)))
173	if err != "" do return nil, nil, err
174	f := jarr(j, "files")
175	if len(f) == 0 || jstr(f[0], "url") == "" do return nil, nil, cat("storage has no postcard for the robot: ", to_json(j))
176	g := get_many({jstr(f[0], "url")})[0]
177	if g.status != 200 do return nil, nil, fmt.tprintf("the bucket answered %d", g.status)
178	return f[0], g.body, ""
179}
180
181POSTCARD_WORDS := [?]string{"otter", "lantern", "harbour", "juniper", "comet", "pebble", "meadow", "falcon", "teacup", "glacier", "cinnamon", "lighthouse"}
182postcard_words :: proc() -> string {
183	return fmt.tprintf("Sealed at %s UTC by the zoo's robot. Today's word: %s-%s.", hm(now()), POSTCARD_WORDS[random_int(0, len(POSTCARD_WORDS) - 1)], random_hex(3))
184}
185
186_ :: strings

seal.odin sha256 e6ef86895cb2 · raw

1package main
2
3// seal: rc-crypt.js's formats, byte for byte (storage's seal/v1/rc-crypt.js is the spec), for the
4// zoo's robot. A person's browser does all of this in rc-crypt.js; the self-checks of exhibits 26 and
5// 27 play that browser (and, to show what is refused, the server), so they need the same bytes.
6//
7// P-256 (public halves as the 65-byte uncompressed point, base64), AES-256-GCM as ciphertext ||
8// 16-byte tag (WebCrypto's layout), HKDF-SHA256, all from core:crypto.
9
10import "core:crypto/aead"
11import "core:crypto/ecdh"
12import "core:crypto/hkdf"
13import "core:crypto/hmac"
14import "core:encoding/base64"
15import "core:encoding/json"
16import "core:fmt"
17import "core:strings"
18
19Seal_Error :: string // "" = fine
20
21s_unb64 :: proc(s: string) -> []u8 {
22	b, err := base64.decode(s)
23	if err != nil do return nil
24	return b
25}
26
27s_hkdf :: proc(ikm, salt: []u8, info: string) -> []u8 {
28	out := make([]u8, 32)
29	hkdf.extract_and_expand(.SHA256, salt, ikm, transmute([]u8)info, out)
30	return out
31}
32s_hmac :: proc(key, msg: []u8) -> []u8 {
33	out := make([]u8, 32)
34	hmac.sum(.SHA256, out, msg, key)
35	return out
36}
37s_seal :: proc(key, iv, pt: []u8, aad: []u8 = nil) -> []u8 {
38	out := make([]u8, len(pt) + 16)
39	aead.seal_oneshot(.AES_GCM_256, out[:len(pt)], out[len(pt):], key, iv, aad, pt)
40	return out
41}
42s_open :: proc(key, iv, ct: []u8, aad: []u8 = nil) -> ([]u8, bool) {
43	if len(ct) < 16 || len(key) != 32 || len(iv) != 12 do return nil, false
44	out := make([]u8, len(ct) - 16)
45	ok := aead.open_oneshot(.AES_GCM_256, out, key, iv, aad, ct[:len(ct) - 16], ct[len(ct) - 16:])
46	return out, ok
47}
48eq_bytes :: proc(a, b: []u8) -> bool {
49	if len(a) != len(b) do return false
50	x: u8 = 0
51	for i in 0 ..< len(a) do x |= a[i] ~ b[i]
52	return x == 0
53}
54
55// ---- P-256 ----
56
57Ec :: struct {
58	d:   []u8, // the private scalar
59	pub: []u8, // 65 bytes
60}
61
62ec_new :: proc() -> Ec {
63	k: ecdh.Private_Key
64	if !ecdh.private_key_generate(&k, .SECP256R1) do panic("no P-256 key")
65	return ec_of(&k)
66}
67@(private = "file")
68ec_of :: proc(k: ^ecdh.Private_Key) -> Ec {
69	d := make([]u8, 32)
70	ecdh.private_key_bytes(k, d)
71	pub := make([]u8, 65)
72	ecdh.private_key_public_bytes(k, pub)
73	return {d, pub}
74}
75ec_from_d :: proc(d: []u8) -> (Ec, bool) {
76	k: ecdh.Private_Key
77	if len(d) != 32 || !ecdh.private_key_set_bytes(&k, .SECP256R1, d) do return {}, false
78	return ec_of(&k), true
79}
80ec_load :: proc(pem: string) -> (Ec, bool) {
81	d, ok := pem_scalar(pem)
82	if !ok do return {}, false
83	return ec_from_d(d)
84}
85ec_dh :: proc(priv: Ec, pub_raw: []u8) -> ([]u8, bool) {
86	k: ecdh.Private_Key
87	p: ecdh.Public_Key
88	if len(pub_raw) != 65 || pub_raw[0] != 4 do return nil, false
89	if !ecdh.private_key_set_bytes(&k, .SECP256R1, priv.d) || !ecdh.public_key_set_bytes(&p, .SECP256R1, pub_raw) do return nil, false
90	z := make([]u8, 32)
91	if !ecdh.ecdh(&k, &p, z) do return nil, false
92	return z, true
93}
94
95// ---- master keys ----
96
97mk_id :: proc(k: []u8) -> string {return hex(sha256(join(bytes_of("rc-storage mk-id v1"), k)))[:32]}
98mk_proof :: proc(k: []u8) -> string {return b64(s_hmac(k, bytes_of("rc-storage proof v1")))}
99unhex :: proc(s: string) -> []u8 {
100	out := make([]u8, len(s) / 2)
101	v :: proc(c: u8) -> u8 {return c - '0' if c <= '9' else (c | 0x20) - 'a' + 10}
102	for i in 0 ..< len(out) do out[i] = v(s[2 * i]) << 4 | v(s[2 * i + 1])
103	return out
104}
105
106// DEVICE WRAP
107Wrap :: struct {
108	eph: string `json:"eph"`,
109	iv:  string `json:"iv"`,
110	ct:  string `json:"ct"`,
111}
112
113wrap_for_device :: proc(pub_b64: string, k: []u8) -> (Wrap, bool) {
114	dpub := s_unb64(pub_b64)
115	eph := ec_new()
116	z, ok := ec_dh(eph, dpub)
117	if !ok do return {}, false
118	key := s_hkdf(z, join(eph.pub, dpub), "rc-storage device-wrap v1")
119	iv := random_bytes(12)
120	return {b64(eph.pub), b64(iv), b64(s_seal(key, iv, k))}, true
121}
122unwrap_for_device :: proc(priv: Ec, pub_b64: string, w: Wrap) -> ([]u8, bool) {
123	eph := s_unb64(w.eph)
124	z, ok := ec_dh(priv, eph)
125	if !ok do return nil, false
126	key := s_hkdf(z, join(eph, s_unb64(pub_b64)), "rc-storage device-wrap v1")
127	return s_open(key, s_unb64(w.iv), s_unb64(w.ct))
128}
129
130// RECOVERY (Crockford base32, 20 bytes as 32 characters)
131B32 := "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
132b32norm :: proc(s: string) -> string {
133	b := strings.builder_make()
134	for ch in transmute([]u8)strings.to_upper(s) {
135		switch ch {
136		case ' ', '\t', '\n', '\r', '-':
137		case 'I', 'L': strings.write_byte(&b, '1')
138		case 'O': strings.write_byte(&b, '0')
139		case: strings.write_byte(&b, ch)
140		}
141	}
142	return strings.to_string(b)
143}
144b32dec :: proc(s: string, n: int) -> ([]u8, bool) {
145	t := b32norm(s)
146	if len(t) != (n * 8 + 4) / 5 do return nil, false
147	out := make([dynamic]u8)
148	bits, val: u32 = 0, 0
149	for ch in transmute([]u8)t {
150		i := strings.index_byte(B32, ch)
151		if i < 0 do return nil, false
152		val = ((val << 5) | u32(i)) & 0xffff
153		bits += 5
154		if bits >= 8 {append(&out, u8((val >> (bits - 8)) & 255)); bits -= 8}
155	}
156	return out[:n], true
157}
158
159Recovery :: struct {
160	salt:    string `json:"salt"`,
161	iv:      string `json:"iv"`,
162	ct:      string `json:"ct"`,
163	created: i64 `json:"created"`,
164}
165
166recovery_unwrap :: proc(phrase: string, rec: Recovery) -> ([]u8, string) {
167	b, ok := b32dec(phrase, 20)
168	if !ok do return nil, "a recovery key is 32 letters and digits"
169	k, ok2 := s_open(s_hkdf(b, s_unb64(rec.salt), "rc-storage recovery v1"), s_unb64(rec.iv), s_unb64(rec.ct))
170	if !ok2 do return nil, "the recovery key does not open it"
171	return k, ""
172}
173
174// DEVICE APPROVAL
175new_code :: proc() -> string {
176	r := random_bytes(12)
177	b := strings.builder_make()
178	for x, i in r {
179		if i > 0 && i % 4 == 0 do strings.write_byte(&b, '-')
180		strings.write_byte(&b, B32[x & 31])
181	}
182	return strings.to_string(b)
183}
184approval_key :: proc(code: string) -> []u8 {return s_hkdf(bytes_of(b32norm(code)), nil, "rc-storage approve v1")}
185req_msg :: proc(id, pub: string) -> []u8 {return join(bytes_of("req\x00"), bytes_of(id), {0}, s_unb64(pub))}
186ok_msg :: proc(id, pub: string, w: Wrap, mkid: string) -> []u8 {
187	return join(bytes_of("ok\x00"), bytes_of(id), {0}, s_unb64(pub), s_unb64(w.eph), s_unb64(w.iv), s_unb64(w.ct), unhex(mkid))
188}
189request_tag :: proc(code, id, pub: string) -> string {return b64(s_hmac(approval_key(code), req_msg(id, pub)))}
190check_request :: proc(code: string, q: json.Value) -> bool {
191	return const_eq(request_tag(code, jstr(q, "id"), jstr(q, "pub")), jstr(q, "tag"))
192}
193approval_tag :: proc(code, id, pub: string, w: Wrap, mkid: string) -> string {return b64(s_hmac(approval_key(code), ok_msg(id, pub, w, mkid)))}
194
195// THE ROOT
196Root_Entry :: struct {
197	id:  string `json:"id"`,
198	pub: string `json:"pub,omitempty"`, // a root wrap key (storage's keyring)
199	eph: string `json:"eph,omitempty"`, // a wrap for the root (an app's keyring)
200	iv:  string `json:"iv"`,
201	ct:  string `json:"ct"`,
202}
203
204root_id :: proc(pub_b64: string) -> string {return hex(sha256(join(bytes_of("rc-root id v1"), s_unb64(pub_b64))))[:32]}
205rwk_aad :: proc(root: []u8, pub_b64: string) -> []u8 {return join(bytes_of("rc-root rwk v1\x00"), unhex(mk_id(root)), s_unb64(pub_b64))}
206open_root_wrap_key :: proc(root: []u8, e: Root_Entry) -> (Ec, string) {
207	if e.id != root_id(e.pub) do return {}, "root key id mismatch"
208	d, ok := s_open(s_hkdf(root, nil, "rc-root rwk-wrap v1"), s_unb64(e.iv), s_unb64(e.ct), rwk_aad(root, e.pub))
209	if !ok do return {}, "the root key does not open"
210	k, kok := ec_from_d(d)
211	if !kok || !eq_bytes(k.pub, s_unb64(e.pub)) do return {}, "root key does not match its public half"
212	return k, ""
213}
214app_aad :: proc(app, mkid: string) -> []u8 {return join(bytes_of("rc-root app v1\x00"), bytes_of(app), {0}, unhex(mkid))}
215unwrap_from_root :: proc(rwk: Ec, root_pub_b64, app, mkid: string, w: Root_Entry) -> ([]u8, string) {
216	eph := s_unb64(w.eph)
217	z, ok := ec_dh(rwk, eph)
218	if !ok do return nil, "ECDH failed"
219	mk, ok2 := s_open(s_hkdf(z, join(eph, s_unb64(root_pub_b64)), "rc-root app-wrap v1"), s_unb64(w.iv), s_unb64(w.ct), app_aad(app, mkid))
220	if !ok2 do return nil, "the app's key does not open under the root"
221	if mk_id(mk) != mkid do return nil, "app key id mismatch"
222	return mk, ""
223}
224
225// KEYRING v2: as storage holds it, field for field.
226Kr_Device :: struct {
227	id:      string `json:"id"`,
228	name:    string `json:"name"`,
229	pub:     string `json:"pub"`,
230	wrap:    Wrap `json:"wrap"`,
231	ok:      string `json:"ok,omitempty"`,
232	created: i64 `json:"created"`,
233	via:     string `json:"via"`,
234}
235Kr_Older :: struct {
236	mk_id: string `json:"mk_id"`,
237	iv:    string `json:"iv"`,
238	ct:    string `json:"ct"`,
239}
240Keyring :: struct {
241	v:        int `json:"v"`,
242	mk_id:    string `json:"mk_id"`,
243	epoch:    i64 `json:"epoch"`,
244	root:     Root_Entry `json:"root"`,
245	recovery: ^Recovery `json:"recovery,omitempty"`, // storage's own keyring only
246	devices:  []Kr_Device `json:"devices"`,
247	older:    []Kr_Older `json:"older"`,
248	mac:      string `json:"mac"`,
249}
250
251keyring_msg :: proc(kr: Keyring, user, app: string) -> []u8 {
252	b := strings.builder_make()
253	r := kr.root
254	fmt.sbprintf(&b, "rc-keyring v2\nuser %s\napp %s\nmk %s\nepoch %d\nroot %s %s %s %s\n", user, app, kr.mk_id, kr.epoch, r.id, r.pub if r.pub != "" else r.eph, r.iv, r.ct)
255	if app == "-" && kr.recovery != nil {c := kr.recovery^; fmt.sbprintf(&b, "recovery %s %s %s %d\n", c.salt, c.iv, c.ct, c.created)}
256	for d in kr.devices do fmt.sbprintf(&b, "device %s %s %s %s %s %s %s %d %s\n", d.id, d.pub, d.wrap.eph, d.wrap.iv, d.wrap.ct, d.ok if d.ok != "" else "-", d.via, d.created, b64(bytes_of(d.name)))
257	for o in kr.older do fmt.sbprintf(&b, "older %s %s %s\n", o.mk_id, o.iv, o.ct)
258	return transmute([]u8)strings.to_string(b)
259}
260keyring_mac :: proc(k: []u8, kr: Keyring, user, app: string) -> string {
261	return b64(s_hmac(s_hkdf(k, nil, "rc-keyring mac v1"), keyring_msg(kr, user, app)))
262}
263check_keyring :: proc(k: []u8, kr: Keyring, user, app: string) -> bool {
264	return kr.mac != "" && const_eq(keyring_mac(k, kr, user, app), kr.mac)
265}
266open_older :: proc(k: []u8, e: Kr_Older) -> bool {
267	old, ok := s_open(s_hkdf(k, nil, "rc-keyring older v1"), s_unb64(e.iv), s_unb64(e.ct), join(bytes_of("rc-keyring older v1\x00"), unhex(e.mk_id)))
268	return ok && mk_id(old) == e.mk_id
269}
270
271// A device the robot plays: its key, and what it remembers of the keyring.
272Dev :: struct {
273	id:    string,
274	priv:  Ec,
275	pub:   string,
276	pin:   string, // the mk_id it trusts, or ""
277	epoch: i64,
278	code:  string, // a pending approval code, or ""
279}
280
281// A device's view (rc-seal.js's trust()): the key its entry opens, or why it is refused.
282trust_keyring :: proc(kr: Keyring, dev: Dev, user, app: string) -> ([]u8, string) {
283	if kr.v != 2 do return nil, "not a v2 keyring"
284	mine: ^Kr_Device
285	for &d in kr.devices do if d.id == dev.id do mine = &d
286	if mine == nil do return nil, "this device is not in the keyring"
287	if mine.pub != dev.pub do return nil, "this device's entry carries another key"
288	k, ok := unwrap_for_device(dev.priv, dev.pub, mine.wrap)
289	if !ok do return nil, "this device's entry does not open"
290	if mk_id(k) != kr.mk_id do return nil, "this device's entry is not the keyring's key"
291	if dev.pin == kr.mk_id {
292	} else if dev.pin != "" {
293		held := false
294		for o in kr.older do if o.mk_id == dev.pin && open_older(k, o) do held = true
295		if !held do return nil, "the keyring's key changed, and the new one does not hold the old"
296	} else if dev.code == "" || mine.ok == "" || !const_eq(approval_tag(dev.code, dev.id, dev.pub, mine.wrap, kr.mk_id), mine.ok) {
297		return nil, "this device's entry was not vouched for under its code"
298	}
299	if !check_keyring(k, kr, user, app) do return nil, "the keyring was changed by someone without its key"
300	if dev.epoch > kr.epoch do return nil, "the keyring is older than one this device has seen"
301	return k, ""
302}
303
304// ENVELOPE (not FRAGMENTED MEDIA: the zoo seals words)
305ENV_TYPE :: "application/x-rc-encrypted"
306
307envelope_seal :: proc(mk, pt: []u8, name, type: string, log2 := 12) -> []u8 {
308	cs := 1 << uint(log2)
309	size := len(pt)
310	n := max(1, (size + cs - 1) / cs)
311	fk := random_bytes(32)
312	P := random_bytes(8)
313	fk_iv := random_bytes(12)
314	meta := fmt.tprintf(`{{"name":%s,"type":%s,"mtime":%d}}`, jq(name), jq(type), now_ms())
315	meta_ct := s_seal(fk, join(P, {0xff, 0xff, 0xff, 0xff}), bytes_of(meta), bytes_of("rc-meta"))
316	size8 := make([]u8, 8)
317	for i in 0 ..< 8 do size8[i] = u8(u64(size) >> uint(56 - 8 * i))
318	head := join(bytes_of("RCE1"), {u8(log2), 0, 0, 0}, size8, unhex(mk_id(mk)), P, fk_iv, s_seal(mk, fk_iv, fk), be32(u32(len(meta_ct))), meta_ct)
319	hh := sha256(head)
320	out := make([dynamic]u8)
321	append(&out, ..head)
322	for i in 0 ..< n {
323		last: u8 = 1 if i == n - 1 else 0
324		append(&out, ..s_seal(fk, join(P, be32(u32(i))), pt[i * cs:min(size, (i + 1) * cs)], join(hh, {last})))
325	}
326	return out[:]
327}
328
329// The words and the meta, with the key `key_for` gives for the envelope's mk_id. Refuses what
330// rc-crypt.js refuses.
331envelope_open :: proc(key_for: proc(mkid: string, arg: rawptr) -> []u8, arg: rawptr, env_: []u8) -> (pt: []u8, err: string) {
332	e := env_
333	if len(e) < 104 || string(e[:4]) != "RCE1" do return nil, "not an encrypted file"
334	log2 := int(e[4])
335	if log2 < 12 || log2 > 24 || e[5] != 0 || e[6] != 0 || e[7] != 0 do return nil, "bad header"
336	size := 0
337	for i in 0 ..< 8 do size = size << 8 | int(e[8 + i])
338	mkid := hex(e[16:32])
339	k := key_for(mkid, arg)
340	if k == nil || mk_id(k) != mkid do return nil, "sealed with a different key"
341	meta_len := int(e[100]) << 24 | int(e[101]) << 16 | int(e[102]) << 8 | int(e[103])
342	if meta_len > 65536 || 104 + meta_len > len(e) do return nil, "bad header"
343	hl := 104 + meta_len
344	P := e[32:40]
345	fk, ok := s_open(k, e[40:52], e[52:100])
346	if !ok do return nil, "the file key does not open"
347	if _, mok := s_open(fk, join(P, {0xff, 0xff, 0xff, 0xff}), e[104:hl], bytes_of("rc-meta")); !mok do return nil, "the meta does not open"
348	hh := sha256(e[:hl])
349	cs := 1 << uint(log2)
350	n := max(1, (size + cs - 1) / cs)
351	out := make([dynamic]u8)
352	at := hl
353	for i in 0 ..< n {
354		l := min(cs, size - i * cs) + 16
355		if at + l > len(e) do return nil, "truncated"
356		last: u8 = 1 if i == n - 1 else 0
357		chunk, cok := s_open(fk, join(P, be32(u32(i))), e[at:at + l], join(hh, {last}))
358		if !cok do return nil, "a chunk does not open"
359		append(&out, ..chunk)
360		at += l
361	}
362	if at != len(e) do return nil, "trailing bytes"
363	return out[:], ""
364}
365
366// ---- making a keyring (once per environment, robotseal.odin) ----
367
368b32enc :: proc(bytes: []u8) -> string {
369	out := strings.builder_make()
370	bits, val: u32 = 0, 0
371	for c in bytes {
372		val = ((val << 8) | u32(c)) & 0xffff
373		bits += 8
374		for bits >= 5 {strings.write_byte(&out, B32[(val >> (bits - 5)) & 31]); bits -= 5}
375	}
376	if bits > 0 do strings.write_byte(&out, B32[(val << (5 - bits)) & 31])
377	return strings.to_string(out)
378}
379new_recovery_key :: proc() -> ([]u8, string) {
380	b := random_bytes(20)
381	s := b32enc(b)
382	parts := make([dynamic]string)
383	for i := 0; i < len(s); i += 4 do append(&parts, s[i:min(i + 4, len(s))])
384	return b, strings.join(parts[:], "-")
385}
386recovery_wrap :: proc(bytes, k: []u8) -> Recovery {
387	salt, iv := random_bytes(16), random_bytes(12)
388	return {b64(salt), b64(iv), b64(s_seal(s_hkdf(bytes, salt, "rc-storage recovery v1"), iv, k)), now()}
389}
390new_root_wrap_key :: proc(root: []u8) -> Root_Entry {
391	k := ec_new()
392	pub := b64(k.pub)
393	iv := random_bytes(12)
394	return {id = root_id(pub), pub = pub, iv = b64(iv), ct = b64(s_seal(s_hkdf(root, nil, "rc-root rwk-wrap v1"), iv, k.d, rwk_aad(root, pub)))}
395}
396wrap_for_root :: proc(root_id_, root_pub, app: string, app_mk: []u8) -> Root_Entry {
397	rpub := s_unb64(root_pub)
398	eph := ec_new()
399	z, _ := ec_dh(eph, rpub)
400	iv := random_bytes(12)
401	return {id = root_id_, eph = b64(eph.pub), iv = b64(iv), ct = b64(s_seal(s_hkdf(z, join(eph.pub, rpub), "rc-root app-wrap v1"), iv, app_mk, app_aad(app, mk_id(app_mk))))}
402}

web/e26.js sha256 da79c09372d9 · raw

1(async () => {
2  const box = document.getElementById("seal26");
3  if (!box) return;
4  const say = (html) => { box.innerHTML = html; };
5  if (!window.RCSeal) { say('<p class="tag bad">storage\'s sealing scripts did not load, or not the ones this page pins</p>'); return; }
6  const call = async (op, body) => { const j = await zoo.call("/api/26/storage", { op, body }); if (j.error) throw new Error(j.error); return j; };
7  const seal = RCSeal.app({ app: "zoo", user: box.dataset.user, call: (body) => call("keyring", body) });
8  window.zooSeal = seal;
9  const hex = (u) => [...u].map((x) => x.toString(16).padStart(2, "0")).join(" ");
10  const when = (t) => new Date(t * 1000).toLocaleString(undefined, { hour: "2-digit", minute: "2-digit", month: "short", day: "numeric" });
11
12  // The postcard as storage and the bucket hold it, and, on a device that can, opened.
13  async function postcard() {
14    const u = (await call("urls", {})).files[0];
15    if (!u || !u.url) return null;
16    const bytes = new Uint8Array(await (await fetch(u.url)).arrayBuffer());
17    let opened = null, why = "";
18    if (seal.status === "ready") {
19      try { const d = await RCCrypt.decrypt((id) => seal.keyFor(id), new Blob([bytes])); opened = { words: await d.blob.text(), meta: d.meta }; }
20      catch (e) { why = e.message; }
21    }
22    return { u, bytes, opened, why };
23  }
24  function held(p) {
25    const head = hex(p.bytes.slice(0, 48));
26    return '<div class="held"><p><b>What storage and the bucket hold</b> <span class="muted small">(' + p.bytes.length + ' bytes, as B2 serves them)</span></p>'
27      + '<pre class="log hexdump">' + zoo.esc(head) + ' …</pre>'
28      + '<p class="muted small">It starts <code>RCE1</code>: an envelope. Your words are not in it. What the server knows: ' + p.u.size + ' bytes, saved ' + zoo.esc(when(p.u.updated)) + ', a random file name. Not the words, not that they are words.</p></div>';
29  }
30  async function render(flash) {
31    try { await seal.load(); } catch (e) { say('<p class="tag bad">' + zoo.esc(e.message) + '</p>'); return; }
32    const st = seal.status;
33    if (st === "unsupported") { say('<p class="muted">This browser cannot seal (no WebCrypto or IndexedDB here).</p>'); return; }
34    if (st === "nostorage" || st === "none") {
35      say('<p>The zoo seals a postcard with a key of its own, kept under yours: only your devices and your recovery key open it.</p>'
36        + '<p><button class="primary" id="seal-setup">' + (st === "nostorage" ? "Set up sealing" : "Let the zoo seal with your key") + '</button> <span class="out" id="seal-out"></span></p>'
37        + '<p class="muted small">' + (st === "nostorage" ? "Storage opens in a small window: you make your key and write down a recovery key, once." : "Storage opens in a small window and hands the zoo your key's public half.") + '</p>');
38      document.getElementById("seal-setup").onclick = async (ev) => {
39        ev.target.disabled = true; document.getElementById("seal-out").textContent = "in storage's window…";
40        try { await seal.setup(); render("The zoo now seals with its own key, kept under yours."); }
41        catch (e) { ev.target.disabled = false; document.getElementById("seal-out").textContent = e.message; }
42      };
43      return;
44    }
45    const p = await postcard().catch(() => null);
46    if (st === "locked") {
47      say('<p><span class="tag bad">locked</span> This browser cannot open your sealed postcard.' + (seal.why ? ' <span class="muted small">' + zoo.esc(seal.why) + '</span>' : '') + ' Card 27 lets it in.</p>' + (p ? held(p) : ''));
48      return;
49    }
50    let html = (flash ? '<p class="tag ok">' + zoo.esc(flash) + '</p>' : '')
51      + '<form id="seal-form" class="row"><input id="seal-words" maxlength="500" placeholder="Your words, for nobody but you" required><button class="primary">Seal a postcard</button></form><p class="out" id="seal-out"></p>';
52    if (p) {
53      html += '<div class="sealpair"><div class="opened"><p><b>Opened on this device</b></p>'
54        + (p.opened ? '<blockquote id="seal-opened">' + zoo.esc(p.opened.words) + '</blockquote><p class="muted small">sealed ' + zoo.esc(new Date(p.opened.meta.mtime).toLocaleString()) + '</p>'
55                    : '<p class="tag bad">does not open: ' + zoo.esc(p.why) + '</p>')
56        + '</div>' + held(p) + '</div>';
57    }
58    say(html);
59    document.getElementById("seal-form").onsubmit = async (ev) => {
60      ev.preventDefault();
61      const out = document.getElementById("seal-out"), words = document.getElementById("seal-words").value;
62      out.textContent = "sealing in this browser…";
63      try {
64        await seal.load();
65        if (seal.status !== "ready") throw new Error("this browser cannot seal right now: " + (seal.why || seal.status));
66        const env = await RCCrypt.encrypt(seal.key, new Blob([words]), { name: "postcard.txt", type: "text/plain" });
67        const b = (await call("begin", { files: [{ path: "sealed/postcard.rce", size: env.size, type: RCCrypt.TYPE }] })).files[0];
68        if (!b.url) throw new Error(b.error || "storage would not begin it");
69        const put = await fetch(b.url, { method: "PUT", headers: { "Content-Type": b.type }, body: env });
70        if (!put.ok) throw new Error("B2 answered " + put.status);
71        const c = (await call("commit", { ids: [b.id] })).files[0];
72        if (!c.file) throw new Error(c.error || "storage would not commit it");
73        render("Sealed here, sent straight to B2 as " + env.size + " bytes.");
74      } catch (e) { out.textContent = e.message; }
75    };
76  }
77  window.zooSealRender = render;
78  render();
79})();