@tide-ota/protocol 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ import { ProtocolError, assetHash, contentKey } from "./hash.js";
2
+ import { TOKEN } from "./multipart.js";
3
+ // Every asset extension a default Expo project bundles (Metro's `assetExts` plus Expo's), and the launch bundle's.
4
+ const CONTENT_TYPES = new Map(Object.entries({
5
+ bundle: "application/javascript",
6
+ js: "application/javascript",
7
+ hbc: "application/javascript",
8
+ bmp: "image/bmp",
9
+ gif: "image/gif",
10
+ jpg: "image/jpeg",
11
+ jpeg: "image/jpeg",
12
+ png: "image/png",
13
+ psd: "image/vnd.adobe.photoshop",
14
+ svg: "image/svg+xml",
15
+ webp: "image/webp",
16
+ heic: "image/heic",
17
+ avif: "image/avif",
18
+ xml: "application/xml",
19
+ html: "text/html",
20
+ pdf: "application/pdf",
21
+ yaml: "application/yaml",
22
+ yml: "application/yaml",
23
+ zip: "application/zip",
24
+ db: "application/vnd.sqlite3",
25
+ m4v: "video/x-m4v",
26
+ mov: "video/quicktime",
27
+ mp4: "video/mp4",
28
+ mpeg: "video/mpeg",
29
+ mpg: "video/mpeg",
30
+ webm: "video/webm",
31
+ aac: "audio/aac",
32
+ aiff: "audio/x-aiff",
33
+ caf: "audio/x-caf",
34
+ m4a: "audio/mp4",
35
+ mp3: "audio/mpeg",
36
+ wav: "audio/wav",
37
+ otf: "font/otf",
38
+ ttf: "font/ttf",
39
+ woff: "font/woff",
40
+ woff2: "font/woff2",
41
+ }));
42
+ /** Returns the media type for a bare file extension (`png`, no dot); `application/octet-stream` when unknown. */
43
+ export function assetContentType(ext) {
44
+ return CONTENT_TYPES.get(ext.toLowerCase()) ?? "application/octet-stream";
45
+ }
46
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
47
+ // The device stores `key + fileExtension` as a file name; without "." in keys, names are safe and distinct.
48
+ export const ASSET_KEY = /^[A-Za-z0-9_-]{1,64}$/;
49
+ const FILE_EXTENSION = /^\.[A-Za-z0-9]{1,16}$/;
50
+ const MEDIA_TYPE = new RegExp(`^${TOKEN}/${TOKEN}$`);
51
+ const NON_EMPTY = /./s;
52
+ const encoder = new TextEncoder();
53
+ /**
54
+ * Returns the manifest as the exact UTF-8 bytes to sign, store and serve. Each input field is read once and the
55
+ * bytes are built from fresh objects holding only validated values, so no input method shapes the output.
56
+ */
57
+ export function buildManifest(input) {
58
+ const m = object(input, "input");
59
+ const id = matching(m.id, "id", UUID, "a lowercase UUID");
60
+ const createdAt = isoDate(m.createdAt, "createdAt");
61
+ const runtimeVersion = matching(m.runtimeVersion, "runtimeVersion", NON_EMPTY, "non-empty");
62
+ const launch = object(m.launchAsset, "launchAsset");
63
+ const launchHash = assetHash(launch.hash, "launchAsset.hash");
64
+ const launchAsset = {
65
+ hash: launchHash,
66
+ key: contentKey(launchHash),
67
+ ...assetFile(launch, "launchAsset"),
68
+ };
69
+ // Lowercased, because a case-insensitive disk would store two keys differing only in case as one file.
70
+ const keys = new Set([launchAsset.key]);
71
+ const assets = array(m.assets, "assets", (value, field) => {
72
+ const a = object(value, field);
73
+ const hash = assetHash(a.hash, `${field}.hash`);
74
+ const key = matching(a.key, `${field}.key`, ASSET_KEY, "1 to 64 of A-Z, a-z, 0-9, _ and -");
75
+ if (keys.has(key.toLowerCase()))
76
+ throw new ProtocolError(`${field}.key`, "duplicates another key");
77
+ keys.add(key.toLowerCase());
78
+ return { hash, key, ...assetFile(a, field) };
79
+ });
80
+ const metadata = Object.fromEntries(Object.entries(object(m.metadata, "metadata")).map(([k, v]) => [k, string(v, `metadata.${k}`)]));
81
+ const extra = jsonObject(m.extra, "extra", new Set());
82
+ return encode({ id, createdAt, runtimeVersion, launchAsset, assets, metadata, extra });
83
+ }
84
+ /** Returns the noUpdateAvailable directive as the exact UTF-8 bytes to sign and store. */
85
+ export function buildNoUpdateAvailable() {
86
+ return encode({ type: "noUpdateAvailable" });
87
+ }
88
+ /** Returns the rollBackToEmbedded directive as the exact UTF-8 bytes to sign and store. */
89
+ export function buildRollBackToEmbedded(input) {
90
+ const commitTime = isoDate(object(input, "input").commitTime, "commitTime");
91
+ return encode({ type: "rollBackToEmbedded", parameters: { commitTime } });
92
+ }
93
+ function encode(value) {
94
+ // The copy types the bytes as ArrayBuffer-backed under Workers types too, where the server compiles this.
95
+ return new Uint8Array(encoder.encode(JSON.stringify(value)));
96
+ }
97
+ function assetFile(a, field) {
98
+ return {
99
+ contentType: matching(a.contentType, `${field}.contentType`, MEDIA_TYPE, "a type/subtype media type"),
100
+ fileExtension: matching(a.fileExtension, `${field}.fileExtension`, FILE_EXTENSION, "a dot and 1 to 16 of A-Z, a-z and 0-9"),
101
+ url: assetUrl(a.url, `${field}.url`),
102
+ };
103
+ }
104
+ function string(value, field) {
105
+ if (typeof value !== "string")
106
+ throw new ProtocolError(field, "must be a string");
107
+ return value;
108
+ }
109
+ function matching(value, field, rule, description) {
110
+ const s = string(value, field);
111
+ if (!rule.test(s))
112
+ throw new ProtocolError(field, `must be ${description}`);
113
+ return s;
114
+ }
115
+ /** The URL goes on the wire verbatim, so it must already be in the form a URL parser would print. */
116
+ function assetUrl(value, field) {
117
+ const raw = string(value, field);
118
+ const url = URL.parse(raw);
119
+ if (url?.href !== raw)
120
+ throw new ProtocolError(field, "must be an absolute URL in canonical form");
121
+ if (/%(?![0-9A-Fa-f]{2})/.test(raw))
122
+ throw new ProtocolError(field, "has a malformed % escape");
123
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
124
+ throw new ProtocolError(field, "must be an http or https URL");
125
+ }
126
+ if (url.username !== "" || url.password !== "") {
127
+ throw new ProtocolError(field, "must not carry credentials");
128
+ }
129
+ return raw;
130
+ }
131
+ /** Formats from the internal time value, so a Date subclass cannot change the text. */
132
+ function isoDate(value, field) {
133
+ let iso = "";
134
+ try {
135
+ iso = new Date(Date.prototype.getTime.call(value)).toISOString();
136
+ }
137
+ catch {
138
+ // Not a Date, or an invalid one.
139
+ }
140
+ if (!/^\d{4}-/.test(iso)) {
141
+ throw new ProtocolError(field, "must be a valid Date in the years 0000 to 9999");
142
+ }
143
+ return iso;
144
+ }
145
+ /** An object whose prototype is Object.prototype or null, so a Date, array or class instance is rejected. */
146
+ function object(value, field) {
147
+ const proto = typeof value === "object" && value !== null && Object.getPrototypeOf(value);
148
+ if (proto !== Object.prototype && proto !== null) {
149
+ throw new ProtocolError(field, "must be a plain object");
150
+ }
151
+ return value;
152
+ }
153
+ /** Copies own indexed entries, so neither a subclass nor an iterator can change them; a hole reads as undefined. */
154
+ function array(value, field, item) {
155
+ if (!Array.isArray(value))
156
+ throw new ProtocolError(field, "must be an array");
157
+ const own = value;
158
+ return Array.from({ length: own.length }, (_, i) => item(Object.hasOwn(own, i) ? own[i] : undefined, `${field}[${i}]`));
159
+ }
160
+ function jsonObject(value, field, ancestors) {
161
+ return within(value, field, ancestors, () => Object.fromEntries(Object.entries(object(value, field)).map(([k, v]) => [
162
+ k,
163
+ json(v, `${field}.${k}`, ancestors),
164
+ ])));
165
+ }
166
+ function json(value, field, ancestors) {
167
+ if (value === null || typeof value === "string" || typeof value === "boolean")
168
+ return value;
169
+ if (typeof value === "number" && Number.isFinite(value))
170
+ return value;
171
+ if (Array.isArray(value)) {
172
+ return within(value, field, ancestors, () => array(value, field, (v, at) => json(v, at, ancestors)));
173
+ }
174
+ if (typeof value === "object")
175
+ return jsonObject(value, field, ancestors);
176
+ throw new ProtocolError(field, "must be a string, finite number, boolean, null, array or object");
177
+ }
178
+ /** Rejects a cycle; the same acyclic value may still appear in several places. */
179
+ function within(value, field, ancestors, build) {
180
+ if (ancestors.has(value))
181
+ throw new ProtocolError(field, "must not contain a cycle");
182
+ ancestors.add(value);
183
+ const built = build();
184
+ ancestors.delete(value);
185
+ return built;
186
+ }
@@ -0,0 +1,34 @@
1
+ /** The parts Expo Updates v1 defines, each with the one Content-Type it is sent with. */
2
+ declare const CONTENT_TYPES: {
3
+ readonly manifest: "application/json";
4
+ readonly directive: "application/json";
5
+ readonly extensions: "application/json";
6
+ readonly certificate_chain: "application/x-pem-file";
7
+ };
8
+ export type PartName = keyof typeof CONTENT_TYPES;
9
+ /** A part; its Content-Disposition and Content-Type follow from `name`, so the encoder writes every header line. */
10
+ export interface Part {
11
+ readonly name: PartName;
12
+ readonly body: Uint8Array<ArrayBuffer>;
13
+ readonly signature?: string;
14
+ }
15
+ /** RFC 9110 token. */
16
+ export declare const TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
17
+ /** A header value as fetch delivers it: printable ASCII without edge whitespace. */
18
+ export declare const HEADER_VALUE: RegExp;
19
+ export declare const BOUNDARY: RegExp;
20
+ /**
21
+ * Returns a multipart/mixed body of `parts` in order. Without `boundary` a random one is drawn; a given boundary
22
+ * that occurs anywhere in a part is rejected, so every CRLF--boundary in the body is a delimiter.
23
+ */
24
+ export declare function encodeMultipart(parts: readonly Part[], boundary?: string): {
25
+ boundary: string;
26
+ body: Uint8Array<ArrayBuffer>;
27
+ };
28
+ /**
29
+ * Returns the parts of a multipart/mixed body with their exact body bytes. Strict: no preamble or epilogue, known
30
+ * part names only, each once, with their fixed Content-Type, no header beyond the three Expo defines, and no
31
+ * occurrence of the boundary inside a part.
32
+ */
33
+ export declare function parseMultipart(input: Uint8Array<ArrayBuffer>, boundary: string): Part[];
34
+ export {};
@@ -0,0 +1,213 @@
1
+ import { ProtocolError } from "./hash.js";
2
+ /** The parts Expo Updates v1 defines, each with the one Content-Type it is sent with. */
3
+ const CONTENT_TYPES = {
4
+ manifest: "application/json",
5
+ directive: "application/json",
6
+ extensions: "application/json",
7
+ certificate_chain: "application/x-pem-file",
8
+ };
9
+ /** RFC 9110 token. */
10
+ export const TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
11
+ const HEADER_NAME = new RegExp(`^${TOKEN}$`);
12
+ /** A header value as fetch delivers it: printable ASCII without edge whitespace. */
13
+ export const HEADER_VALUE = /^[\x21-\x7E](?:[\t\x20-\x7E]*[\x21-\x7E])?$/;
14
+ export const BOUNDARY = /^[0-9A-Za-z_-]{1,70}$/;
15
+ const PART_HEADERS = new Set(["content-disposition", "content-type", "expo-signature"]);
16
+ // Any other field is rejected, so a misshapen part cannot drop its signature unnoticed.
17
+ const PART_FIELDS = { name: true, body: true, signature: true };
18
+ const encoder = new TextEncoder();
19
+ const decoder = new TextDecoder();
20
+ const CRLF = encoder.encode("\r\n");
21
+ const DASHES = encoder.encode("--");
22
+ /**
23
+ * Returns a multipart/mixed body of `parts` in order. Without `boundary` a random one is drawn; a given boundary
24
+ * that occurs anywhere in a part is rejected, so every CRLF--boundary in the body is a delimiter.
25
+ */
26
+ export function encodeMultipart(parts, boundary) {
27
+ if (boundary !== undefined)
28
+ checkBoundary(boundary);
29
+ if (parts.length === 0)
30
+ throw new ProtocolError("parts", "must not be empty");
31
+ const names = new Set();
32
+ const framed = parts.map((part, i) => {
33
+ const field = `parts[${i}]`;
34
+ for (const key of Object.keys(part)) {
35
+ if (!Object.hasOwn(PART_FIELDS, key))
36
+ throw new ProtocolError(`${field}.${key}`, "is not a part field");
37
+ }
38
+ const name = part.name;
39
+ if (!isPartName(name))
40
+ throw new ProtocolError(`${field}.name`, "is not a known part name");
41
+ if (names.has(name))
42
+ throw new ProtocolError(`${field}.name`, "duplicates another part");
43
+ names.add(name);
44
+ const signature = part.signature;
45
+ if (signature !== undefined &&
46
+ (typeof signature !== "string" || !HEADER_VALUE.test(signature))) {
47
+ throw new ProtocolError(`${field}.signature`, "must be printable ASCII without edge whitespace");
48
+ }
49
+ // Stock iOS clients look the signature up by its exact lowercase name.
50
+ const lines = [
51
+ `Content-Disposition: form-data; name="${name}"`,
52
+ `Content-Type: ${CONTENT_TYPES[name]}`,
53
+ ];
54
+ if (signature !== undefined)
55
+ lines.push(`expo-signature: ${signature}`);
56
+ const head = encoder.encode(lines.map((l) => `${l}\r\n`).join(""));
57
+ return { field, head, body: part.body };
58
+ });
59
+ let chosen;
60
+ if (boundary === undefined) {
61
+ do
62
+ chosen = randomBoundary();
63
+ while (framed.some((p) => containsBoundary(p.head, p.body, encoder.encode(chosen))));
64
+ }
65
+ else {
66
+ chosen = boundary;
67
+ for (const p of framed) {
68
+ if (containsBoundary(p.head, p.body, encoder.encode(chosen))) {
69
+ throw new ProtocolError(p.field, "contains the boundary");
70
+ }
71
+ }
72
+ }
73
+ const chunks = [];
74
+ for (const p of framed)
75
+ chunks.push(encoder.encode(`--${chosen}\r\n`), p.head, CRLF, p.body, CRLF);
76
+ chunks.push(encoder.encode(`--${chosen}--\r\n`));
77
+ return { boundary: chosen, body: concat(chunks) };
78
+ }
79
+ /**
80
+ * Returns the parts of a multipart/mixed body with their exact body bytes. Strict: no preamble or epilogue, known
81
+ * part names only, each once, with their fixed Content-Type, no header beyond the three Expo defines, and no
82
+ * occurrence of the boundary inside a part.
83
+ */
84
+ export function parseMultipart(input, boundary) {
85
+ checkBoundary(boundary);
86
+ const bytes = new Uint8Array(input);
87
+ const token = encoder.encode(boundary);
88
+ const delimiter = encoder.encode(`\r\n--${boundary}`);
89
+ // The first delimiter has no leading CRLF because there is no preamble.
90
+ const open = encoder.encode(`--${boundary}\r\n`);
91
+ if (!startsWith(bytes, open, 0)) {
92
+ throw new ProtocolError("body", "must start with the boundary delimiter");
93
+ }
94
+ const parts = [];
95
+ const names = new Set();
96
+ let pos = open.length;
97
+ for (;;) {
98
+ const field = `parts[${parts.length}]`;
99
+ const headStart = pos;
100
+ const headers = [];
101
+ for (;;) {
102
+ const eol = indexOf(bytes, CRLF, pos);
103
+ if (eol === -1)
104
+ throw new ProtocolError(field, "headers must end with an empty line");
105
+ const line = bytes.subarray(pos, eol);
106
+ pos = eol + CRLF.length;
107
+ if (line.length === 0)
108
+ break;
109
+ headers.push(parseHeaderLine(line, `${field}.headers[${headers.length}]`));
110
+ }
111
+ checkHeaders(headers, field);
112
+ const name = partName(headers, field);
113
+ if (names.has(name))
114
+ throw new ProtocolError(field, "duplicates another part name");
115
+ names.add(name);
116
+ const signature = headers.find(([n]) => n.toLowerCase() === "expo-signature")?.[1];
117
+ const end = indexOf(bytes, delimiter, pos);
118
+ if (end === -1)
119
+ throw new ProtocolError("body", "is missing the closing boundary");
120
+ const body = bytes.slice(pos, end);
121
+ if (containsBoundary(bytes.subarray(headStart, pos), body, token)) {
122
+ throw new ProtocolError(field, "contains the boundary");
123
+ }
124
+ parts.push(signature === undefined ? { name, body } : { name, body, signature });
125
+ pos = end + delimiter.length;
126
+ if (startsWith(bytes, CRLF, pos)) {
127
+ pos += CRLF.length;
128
+ continue;
129
+ }
130
+ if (!startsWith(bytes, DASHES, pos)) {
131
+ throw new ProtocolError("body", "must follow a boundary with CRLF or --");
132
+ }
133
+ pos += DASHES.length;
134
+ const rest = bytes.length - pos;
135
+ if (rest === 0 || (rest === CRLF.length && startsWith(bytes, CRLF, pos)))
136
+ return parts;
137
+ throw new ProtocolError("body", "must end after the closing boundary");
138
+ }
139
+ }
140
+ function isPartName(name) {
141
+ return typeof name === "string" && Object.hasOwn(CONTENT_TYPES, name);
142
+ }
143
+ function checkBoundary(boundary) {
144
+ if (typeof boundary !== "string" || !BOUNDARY.test(boundary)) {
145
+ throw new ProtocolError("boundary", "must be 1 to 70 characters of A-Z, a-z, 0-9, _ or -");
146
+ }
147
+ }
148
+ function checkHeaders(headers, field) {
149
+ const seen = new Set();
150
+ headers.forEach(([name, value], i) => {
151
+ const at = `${field}.headers[${i}]`;
152
+ if (!HEADER_NAME.test(name))
153
+ throw new ProtocolError(at, "name must be an RFC 9110 token");
154
+ if (!HEADER_VALUE.test(value)) {
155
+ throw new ProtocolError(at, "value must be printable ASCII without edge whitespace");
156
+ }
157
+ const lower = name.toLowerCase();
158
+ if (seen.has(lower))
159
+ throw new ProtocolError(at, "duplicates another header");
160
+ if (!PART_HEADERS.has(lower))
161
+ throw new ProtocolError(at, "is not a part header");
162
+ seen.add(lower);
163
+ });
164
+ }
165
+ function parseHeaderLine(line, field) {
166
+ const text = decoder.decode(line);
167
+ const colon = text.indexOf(":");
168
+ if (colon === -1)
169
+ throw new ProtocolError(field, "must be name: value");
170
+ return [text.slice(0, colon), text.slice(colon + 1).replace(/^[\t ]+|[\t ]+$/g, "")];
171
+ }
172
+ function partName(headers, field) {
173
+ const value = (name) => headers.find(([n]) => n.toLowerCase() === name)?.[1];
174
+ const disposition = value("content-disposition");
175
+ if (disposition === undefined)
176
+ throw new ProtocolError(field, "is missing Content-Disposition");
177
+ const name = /^form-data; name="([a-z_]+)"$/.exec(disposition)?.[1];
178
+ if (!isPartName(name)) {
179
+ throw new ProtocolError(field, "must be form-data with a known part name");
180
+ }
181
+ if (value("content-type") !== CONTENT_TYPES[name]) {
182
+ throw new ProtocolError(field, `must have Content-Type ${CONTENT_TYPES[name]}`);
183
+ }
184
+ return name;
185
+ }
186
+ function containsBoundary(head, body, token) {
187
+ return indexOf(head, token, 0) !== -1 || indexOf(body, token, 0) !== -1;
188
+ }
189
+ function randomBoundary() {
190
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
191
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
192
+ }
193
+ function startsWith(bytes, prefix, at) {
194
+ return indexOf(bytes.subarray(at, at + prefix.length), prefix, 0) === 0;
195
+ }
196
+ function indexOf(bytes, needle, from) {
197
+ outer: for (let i = from; i <= bytes.length - needle.length; i++) {
198
+ for (let j = 0; j < needle.length; j++)
199
+ if (bytes[i + j] !== needle[j])
200
+ continue outer;
201
+ return i;
202
+ }
203
+ return -1;
204
+ }
205
+ function concat(chunks) {
206
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
207
+ let at = 0;
208
+ for (const c of chunks) {
209
+ out.set(c, at);
210
+ at += c.length;
211
+ }
212
+ return out;
213
+ }
@@ -0,0 +1,35 @@
1
+ /** One asset of an embedded build, as the asset key identity check compares it. */
2
+ export interface BaseAsset {
3
+ readonly key: string;
4
+ readonly hash: string;
5
+ }
6
+ interface BaseFields {
7
+ readonly updateId: string;
8
+ readonly runtimeVersion: string;
9
+ readonly platform: "ios" | "android";
10
+ readonly launchAsset: {
11
+ readonly hash: string;
12
+ };
13
+ }
14
+ /** What `bases/<updateId>` holds: a launch bundle patches may start from (docs/design.md, Base records). */
15
+ export type BaseRecord = (BaseFields & {
16
+ readonly kind: "update";
17
+ }) | (BaseFields & {
18
+ readonly kind: "embedded";
19
+ readonly assets: readonly BaseAsset[];
20
+ });
21
+ /** The largest base record the server reads; encode refuses a larger one. */
22
+ export declare const MAX_BASE_BYTES: number;
23
+ /**
24
+ * Returns the record bytes: one JSON object, keys in a fixed order, no trailing newline. Embedded assets are sorted
25
+ * by key and exact repeats collapse; two keys equal but for case must share one hash.
26
+ */
27
+ export declare function encodeBaseRecord(record: BaseRecord): Uint8Array<ArrayBuffer>;
28
+ /** Returns the record `bytes` hold; anything `encodeBaseRecord` would not write byte for byte is refused. */
29
+ export declare function decodeBaseRecord(bytes: Uint8Array): BaseRecord;
30
+ /**
31
+ * Returns `base` with the BSDIFF40 `patch` applied. Refuses, with a ProtocolError, a malformed, truncated or
32
+ * trailing-garbage patch, one that reads or seeks outside `base`, and one declaring more than `maxOutput` bytes.
33
+ */
34
+ export declare function applyBsdiff(base: Uint8Array, patch: Uint8Array, maxOutput: number): Uint8Array<ArrayBuffer>;
35
+ export {};
package/dist/patch.js ADDED
@@ -0,0 +1,201 @@
1
+ import { bunzip2 } from "./bzip2.js";
2
+ import { ProtocolError, assetHash } from "./hash.js";
3
+ import { ASSET_KEY } from "./manifest.js";
4
+ import { checkName, checkUpdateId } from "./reply.js";
5
+ /** The largest base record the server reads; encode refuses a larger one. */
6
+ export const MAX_BASE_BYTES = 256 * 1024;
7
+ const VERSION = 1;
8
+ const encoder = new TextEncoder();
9
+ const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
10
+ /**
11
+ * Returns the record bytes: one JSON object, keys in a fixed order, no trailing newline. Embedded assets are sorted
12
+ * by key and exact repeats collapse; two keys equal but for case must share one hash.
13
+ */
14
+ export function encodeBaseRecord(record) {
15
+ return encode(record).bytes;
16
+ }
17
+ /** Returns the record `bytes` hold; anything `encodeBaseRecord` would not write byte for byte is refused. */
18
+ export function decodeBaseRecord(bytes) {
19
+ if (bytes.length > MAX_BASE_BYTES) {
20
+ throw new ProtocolError("record", `is too large: over ${MAX_BASE_BYTES} bytes`);
21
+ }
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(utf8.decode(bytes));
25
+ }
26
+ catch {
27
+ throw new ProtocolError("record", "is not UTF-8 JSON");
28
+ }
29
+ if (!isObject(parsed))
30
+ throw new ProtocolError("record", "must be a JSON object");
31
+ // Version first, so a later layout is reported as unsupported rather than as malformed.
32
+ const { version, ...rest } = parsed;
33
+ if (!Number.isInteger(version))
34
+ throw new ProtocolError("version", "must be an integer");
35
+ if (version !== VERSION)
36
+ throw new ProtocolError("version", "is not supported");
37
+ const canonical = encode(rest);
38
+ if (canonical.bytes.length !== bytes.length || canonical.bytes.some((b, i) => b !== bytes[i])) {
39
+ throw new ProtocolError("record", "is not in the form encodeBaseRecord writes");
40
+ }
41
+ return canonical.record;
42
+ }
43
+ function encode(input) {
44
+ if (!isObject(input))
45
+ throw new ProtocolError("record", "must be an object");
46
+ const kind = input.kind;
47
+ if (kind !== "update" && kind !== "embedded") {
48
+ throw new ProtocolError("kind", "must be update or embedded");
49
+ }
50
+ const { updateId, runtimeVersion, platform, launchAsset } = input;
51
+ if (typeof runtimeVersion !== "string") {
52
+ throw new ProtocolError("runtimeVersion", "must be a string");
53
+ }
54
+ checkName(runtimeVersion, "runtimeVersion");
55
+ if (platform !== "ios" && platform !== "android") {
56
+ throw new ProtocolError("platform", "must be ios or android");
57
+ }
58
+ if (!isObject(launchAsset))
59
+ throw new ProtocolError("launchAsset", "must be an object");
60
+ const fields = {
61
+ updateId: checkUpdateId(updateId),
62
+ runtimeVersion,
63
+ platform,
64
+ launchAsset: { hash: assetHash(launchAsset.hash, "launchAsset.hash") },
65
+ };
66
+ const record = kind === "update" ? { kind, ...fields } : { kind, ...fields, assets: baseAssets(input) };
67
+ const bytes = new Uint8Array(encoder.encode(JSON.stringify({ version: VERSION, ...record })));
68
+ if (bytes.length > MAX_BASE_BYTES) {
69
+ throw new ProtocolError("record", `is too large: over ${MAX_BASE_BYTES} bytes`);
70
+ }
71
+ return { record, bytes };
72
+ }
73
+ /** Returns a sorted copy of the embedded assets, exact repeats collapsed. */
74
+ function baseAssets(input) {
75
+ const assets = input.assets;
76
+ if (!Array.isArray(assets))
77
+ throw new ProtocolError("assets", "must be an array");
78
+ const entries = assets.map((a, i) => {
79
+ const field = `assets[${i}]`;
80
+ if (!isObject(a))
81
+ throw new ProtocolError(field, "must be an object");
82
+ if (typeof a.key !== "string" || !ASSET_KEY.test(a.key)) {
83
+ throw new ProtocolError(`${field}.key`, "must be 1 to 64 of A-Z, a-z, 0-9, _ and -");
84
+ }
85
+ return { key: a.key, hash: assetHash(a.hash, `${field}.hash`), i };
86
+ });
87
+ entries.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
88
+ const out = [];
89
+ // iOS keeps asset files on a case-insensitive disk, so keys equal but for case must name the same bytes.
90
+ const folded = new Map();
91
+ for (const { key, hash, i } of entries) {
92
+ const previous = out.at(-1);
93
+ if (previous?.key === key && previous.hash === hash)
94
+ continue;
95
+ const other = folded.get(key.toLowerCase());
96
+ if (other !== undefined && other !== hash) {
97
+ throw new ProtocolError(`assets[${i}].key`, "names another hash than an equal key");
98
+ }
99
+ folded.set(key.toLowerCase(), hash);
100
+ out.push({ key, hash });
101
+ }
102
+ return out;
103
+ }
104
+ /**
105
+ * Returns `base` with the BSDIFF40 `patch` applied. Refuses, with a ProtocolError, a malformed, truncated or
106
+ * trailing-garbage patch, one that reads or seeks outside `base`, and one declaring more than `maxOutput` bytes.
107
+ */
108
+ export function applyBsdiff(base, patch, maxOutput) {
109
+ if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
110
+ throw new ProtocolError("maxOutput", "must be a non-negative safe integer");
111
+ }
112
+ if (patch.length < 32)
113
+ throw new ProtocolError("patch", "is shorter than its 32-byte header");
114
+ if (String.fromCharCode(...patch.subarray(0, 8)) !== "BSDIFF40") {
115
+ throw new ProtocolError("patch", "does not start with BSDIFF40");
116
+ }
117
+ const ctrlLen = header(patch, 8, "ctrl length");
118
+ const diffLen = header(patch, 16, "diff length");
119
+ const newSize = header(patch, 24, "output size");
120
+ if (32 + ctrlLen + diffLen > patch.length) {
121
+ throw new ProtocolError("patch", "is shorter than its header's block lengths");
122
+ }
123
+ if (newSize > maxOutput) {
124
+ throw new ProtocolError("patch", `declares an output over ${maxOutput} bytes`);
125
+ }
126
+ const out = new Uint8Array(newSize);
127
+ const diffAt = 32 + ctrlLen;
128
+ const extraAt = diffAt + diffLen;
129
+ // A triple that moves nothing makes no progress, so ctrl is capped at one triple per output byte, plus one.
130
+ const ctrl = bunzip2(patch.subarray(32, diffAt), "patch.ctrl", 24 * (newSize + 1));
131
+ const diff = bunzip2(patch.subarray(diffAt, extraAt), "patch.diff", newSize);
132
+ const extra = bunzip2(patch.subarray(extraAt), "patch.extra", newSize);
133
+ const triple = new Uint8Array(24);
134
+ let newPos = 0;
135
+ let oldPos = 0; // Always within [0, base.length].
136
+ while (newPos < newSize) {
137
+ if (ctrl.read(triple) !== 24) {
138
+ throw new ProtocolError("patch.ctrl", "ends before the output is complete");
139
+ }
140
+ const add = offset(triple, 0, false);
141
+ const copy = offset(triple, 8, false);
142
+ const seek = offset(triple, 16, true);
143
+ if (newPos + add > newSize)
144
+ throw new ProtocolError("patch.ctrl", "adds past the output's end");
145
+ // Reference bspatch skips adds outside the base; bsdiff never writes one, so it is refused here.
146
+ if (oldPos + add > base.length)
147
+ throw new ProtocolError("patch.ctrl", "reads past the base's end");
148
+ if (diff.read(out.subarray(newPos, newPos + add)) !== add) {
149
+ throw new ProtocolError("patch.diff", "ends before the output is complete");
150
+ }
151
+ for (let i = 0; i < add; i++)
152
+ out[newPos + i] = (out[newPos + i] ?? 0) + (base[oldPos + i] ?? 0);
153
+ newPos += add;
154
+ oldPos += add;
155
+ if (newPos + copy > newSize) {
156
+ throw new ProtocolError("patch.ctrl", "copies past the output's end");
157
+ }
158
+ if (extra.read(out.subarray(newPos, newPos + copy)) !== copy) {
159
+ throw new ProtocolError("patch.extra", "ends before the output is complete");
160
+ }
161
+ newPos += copy;
162
+ oldPos += seek;
163
+ if (oldPos < 0 || oldPos > base.length) {
164
+ throw new ProtocolError("patch.ctrl", "seeks outside the base");
165
+ }
166
+ }
167
+ ctrl.end();
168
+ diff.end();
169
+ extra.end();
170
+ return out;
171
+ }
172
+ /** A header length: non-negative, below 2^53. */
173
+ function header(patch, at, name) {
174
+ if ((patch[at + 7] ?? 0) & 0x80)
175
+ throw new ProtocolError("patch", `has a negative ${name}`);
176
+ return magnitude(patch, at, "patch", name);
177
+ }
178
+ /** A control value: sign-magnitude, never negative zero; `add` and `copy` lengths are never negative. */
179
+ function offset(triple, at, signed) {
180
+ const value = magnitude(triple, at, "patch.ctrl", "control value");
181
+ if (((triple[at + 7] ?? 0) & 0x80) === 0)
182
+ return value;
183
+ if (value === 0)
184
+ throw new ProtocolError("patch.ctrl", "has a negative zero");
185
+ if (!signed)
186
+ throw new ProtocolError("patch.ctrl", "has a negative length");
187
+ return -value;
188
+ }
189
+ /** The 63-bit little-endian magnitude at `at`, refused at 2^53 or more. */
190
+ function magnitude(bytes, at, field, name) {
191
+ if (((bytes[at + 7] ?? 0) & 0x7f) !== 0 || (bytes[at + 6] ?? 0) >= 0x20) {
192
+ throw new ProtocolError(field, `has a ${name} of 2^53 or more`);
193
+ }
194
+ let value = 0;
195
+ for (let i = 6; i >= 0; i--)
196
+ value = value * 256 + (bytes[at + i] ?? 0);
197
+ return value;
198
+ }
199
+ function isObject(value) {
200
+ return typeof value === "object" && value !== null && !Array.isArray(value);
201
+ }