@tide-ota/cli 0.0.0-stage → 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.
package/dist/probe.js ADDED
@@ -0,0 +1,306 @@
1
+ import { createHash } from "node:crypto";
2
+ import { parseArgs } from "node:util";
3
+ import { HEADER_VALUE, MAX_REPLY_BYTES, ProtocolError, UUID, assetHash, encodeSfvDictionary, parseMultipart, parseSfvDictionary, readLimited, replyKey, verifyExpoSignature, } from "@tide-ota/protocol";
4
+ import { BUILD_KEYID, KeyError, buildIdentity, isObject, member } from "./keys.js";
5
+ import { urlBase } from "./publish-record.js";
6
+ /** Exit codes by failure class; 1 is left to Node's exit on an uncaught error, so it always means a bug. */
7
+ export const PROBE_EXIT = {
8
+ usage: 2,
9
+ unreachable: 3,
10
+ status: 4,
11
+ unparseable: 5,
12
+ signature: 6,
13
+ bundleMissing: 7,
14
+ bundleHash: 8,
15
+ mismatch: 9,
16
+ };
17
+ export const PROBE_USAGE = "usage: tide probe --server-url <url> --channel <name> --runtime-version <version> --platform ios|android [--app-id <id>]";
18
+ /** Per-request deadlines: the manifest's matches a stock client's read timeout; a bundle may be megabytes. */
19
+ const MANIFEST_TIMEOUT_MS = 10_000;
20
+ const BUNDLE_TIMEOUT_MS = 60_000;
21
+ const DIRECTIVES = {
22
+ rollBackToEmbedded: true,
23
+ noUpdateAvailable: true,
24
+ };
25
+ const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
26
+ /** A failed probe. Its message is fixed text and statuses, never a header value, key or response body. */
27
+ class ProbeFailure extends Error {
28
+ failure;
29
+ constructor(failure, message) {
30
+ super(message);
31
+ this.name = "ProbeFailure";
32
+ this.failure = failure;
33
+ }
34
+ }
35
+ /**
36
+ * Fetches `/manifest` as a stock client would and verifies the signed part against the pinned certificate and keyid,
37
+ * then a manifest's launch asset against its hash. Returns 0 or the `PROBE_EXIT` code of the first failure.
38
+ */
39
+ export async function probe(args, env, io, options = {}) {
40
+ try {
41
+ const config = await configure(args, env);
42
+ for (const line of await check(config, options.timeoutMs))
43
+ io.out(line);
44
+ return 0;
45
+ }
46
+ catch (e) {
47
+ if (!(e instanceof ProbeFailure))
48
+ throw e;
49
+ io.err(`tide: ${e.message}`);
50
+ return PROBE_EXIT[e.failure];
51
+ }
52
+ }
53
+ async function configure(args, env) {
54
+ const usage = (message) => new ProbeFailure("usage", message);
55
+ let values;
56
+ try {
57
+ ({ values } = parseArgs({
58
+ args: [...args],
59
+ options: {
60
+ "server-url": { type: "string" },
61
+ channel: { type: "string" },
62
+ "runtime-version": { type: "string" },
63
+ platform: { type: "string" },
64
+ "app-id": { type: "string" },
65
+ },
66
+ strict: true,
67
+ allowPositionals: false,
68
+ }));
69
+ }
70
+ catch {
71
+ throw usage(`unrecognised arguments; ${PROBE_USAGE}`);
72
+ }
73
+ const { channel, platform } = values;
74
+ const server = values["server-url"];
75
+ const runtime = values["runtime-version"];
76
+ const appId = values["app-id"];
77
+ if (server === undefined || channel === undefined || runtime === undefined) {
78
+ throw usage(`--server-url, --channel and --runtime-version are required; ${PROBE_USAGE}`);
79
+ }
80
+ if (platform !== "ios" && platform !== "android") {
81
+ throw usage("--platform must be ios or android");
82
+ }
83
+ const base = urlBase(server);
84
+ if (base === undefined) {
85
+ throw usage("--server-url must be an https URL with no credentials, query or fragment (http only to a loopback IP)");
86
+ }
87
+ try {
88
+ replyKey(channel, runtime, platform);
89
+ }
90
+ catch (e) {
91
+ if (!(e instanceof ProtocolError))
92
+ throw e;
93
+ const flag = e.field === "channel" ? "--channel" : "--runtime-version";
94
+ throw usage(`${flag} ${e.message.slice(e.field.length + 1)}`);
95
+ }
96
+ if (appId !== undefined && !HEADER_VALUE.test(appId)) {
97
+ throw usage("--app-id must be printable ASCII without edge whitespace");
98
+ }
99
+ let identity;
100
+ try {
101
+ identity = await buildIdentity(env, Date.now());
102
+ }
103
+ catch (e) {
104
+ if (!(e instanceof KeyError))
105
+ throw e;
106
+ throw usage(e.message);
107
+ }
108
+ const { key, keyId } = identity;
109
+ return {
110
+ manifestUrl: `${base}/manifest`,
111
+ headers: {
112
+ "expo-protocol-version": "1",
113
+ "expo-platform": platform,
114
+ "expo-runtime-version": runtime,
115
+ "expo-channel-name": channel,
116
+ "expo-expect-signature": `sig, ${encodeSfvDictionary({ keyid: keyId, alg: "rsa-v1_5-sha256" })}`,
117
+ accept: "multipart/mixed",
118
+ ...(appId !== undefined && { "expo-app-id": appId }),
119
+ },
120
+ runtimeVersion: runtime,
121
+ key,
122
+ keyId,
123
+ };
124
+ }
125
+ /** Returns the report lines of a passing probe. */
126
+ async function check(probe, timeoutMs) {
127
+ const res = await get("GET /manifest", probe.manifestUrl, probe.headers, timeoutMs ?? MANIFEST_TIMEOUT_MS);
128
+ if (res.status !== 200) {
129
+ await res.body?.cancel();
130
+ throw new ProbeFailure("status", `GET /manifest answered ${res.status}`);
131
+ }
132
+ const boundary = boundaryOf(res.headers.get("content-type"));
133
+ if (boundary === undefined) {
134
+ await res.body?.cancel();
135
+ throw new ProbeFailure("unparseable", "the reply is not multipart/mixed with a boundary");
136
+ }
137
+ // A stock client reads a reply without it as a legacy manifest and rejects it.
138
+ if (res.headers.get("expo-protocol-version") !== "1") {
139
+ await res.body?.cancel();
140
+ throw new ProbeFailure("unparseable", "the reply's expo-protocol-version is not 1");
141
+ }
142
+ const body = await readReply(res);
143
+ let parts;
144
+ try {
145
+ parts = parseMultipart(body, boundary);
146
+ }
147
+ catch {
148
+ throw new ProbeFailure("unparseable", "the reply is not a valid multipart body");
149
+ }
150
+ const signed = parts.filter((p) => p.name === "manifest" || p.name === "directive");
151
+ const [part] = signed;
152
+ if (part === undefined || signed.length > 1) {
153
+ throw new ProbeFailure("unparseable", "the reply must hold one manifest or directive part");
154
+ }
155
+ await verify(part, probe);
156
+ let json;
157
+ try {
158
+ json = JSON.parse(utf8.decode(part.body));
159
+ }
160
+ catch {
161
+ throw new ProbeFailure("unparseable", `the ${part.name} part is not JSON`);
162
+ }
163
+ if (part.name === "directive") {
164
+ const type = member(json, "type");
165
+ if (typeof type !== "string" || !Object.hasOwn(DIRECTIVES, type)) {
166
+ throw new ProbeFailure("unparseable", "the directive is not rollBackToEmbedded or noUpdateAvailable");
167
+ }
168
+ return [`directive ${type}: signature verified; a directive has no bundle to check`];
169
+ }
170
+ const id = member(json, "id");
171
+ const launch = member(json, "launchAsset");
172
+ const url = member(launch, "url");
173
+ let hash;
174
+ try {
175
+ hash = assetHash(member(launch, "hash"), "hash");
176
+ }
177
+ catch {
178
+ throw new ProbeFailure("unparseable", "the manifest's launchAsset.hash is not a SHA-256");
179
+ }
180
+ if (typeof id !== "string" || !UUID.test(id)) {
181
+ throw new ProbeFailure("unparseable", "the manifest's id is not a lowercase UUID");
182
+ }
183
+ // A client never launches an update built for another runtime, so a misrouted pointer must fail here.
184
+ if (member(json, "runtimeVersion") !== probe.runtimeVersion) {
185
+ throw new ProbeFailure("mismatch", "the manifest is for another runtime version than requested");
186
+ }
187
+ if (excluded(res.headers.get("expo-manifest-filters"), member(json, "metadata"))) {
188
+ throw new ProbeFailure("mismatch", "the manifest's metadata does not match expo-manifest-filters");
189
+ }
190
+ const target = typeof url === "string" ? URL.parse(url) : null;
191
+ if (target === null || !(target.protocol === "https:" || target.protocol === "http:")) {
192
+ throw new ProbeFailure("unparseable", "the manifest's launchAsset.url is not an http(s) URL");
193
+ }
194
+ await checkBundle(target.href, hash, timeoutMs ?? BUNDLE_TIMEOUT_MS);
195
+ return [`manifest ${id}: signature verified`, `launch asset ${hash}: SHA-256 verified`];
196
+ }
197
+ /** Verifies the part's expo-signature over its exact bytes, as a client configured for code signing does. */
198
+ async function verify(part, { key, keyId }) {
199
+ const fail = (message) => new ProbeFailure("signature", `the ${part.name} part ${message}`);
200
+ if (part.signature === undefined)
201
+ throw fail("has no expo-signature");
202
+ try {
203
+ await verifyExpoSignature(part.body, part.signature, key, keyId);
204
+ }
205
+ catch (e) {
206
+ if (!(e instanceof ProtocolError))
207
+ throw e;
208
+ throw fail(e.field === "signature.keyid"
209
+ ? `is signed under another keyid than ${BUILD_KEYID}`
210
+ : e.field === "signature.sig"
211
+ ? "does not verify under the pinned certificate"
212
+ : "has a malformed expo-signature");
213
+ }
214
+ }
215
+ /**
216
+ * True when a stock client would drop the manifest: a filter names a metadata key (iOS ignores its case) whose value
217
+ * differs. A missing header or metadata filters nothing.
218
+ */
219
+ function excluded(header, metadata) {
220
+ if (header === null)
221
+ return false;
222
+ let filters;
223
+ try {
224
+ filters = parseSfvDictionary(header, "expo-manifest-filters");
225
+ }
226
+ catch {
227
+ filters = undefined;
228
+ }
229
+ if (filters === undefined || [...filters.values()].some((m) => m.kind !== "string")) {
230
+ throw new ProbeFailure("unparseable", "the reply's expo-manifest-filters is not a dictionary of strings");
231
+ }
232
+ if (!isObject(metadata))
233
+ return false;
234
+ return Object.entries(metadata).some(([key, value]) => {
235
+ const filter = filters.get(key.toLowerCase());
236
+ return filter?.kind === "string" && value !== filter.text;
237
+ });
238
+ }
239
+ /** Fetches the launch asset and compares its SHA-256, streamed, with the manifest's hash. */
240
+ async function checkBundle(url, hash, timeoutMs) {
241
+ const label = "GET launch asset";
242
+ const res = await get(label, url, {}, timeoutMs);
243
+ if (res.status !== 200) {
244
+ await res.body?.cancel();
245
+ if (res.status === 404)
246
+ throw new ProbeFailure("bundleMissing", `${label} answered 404`);
247
+ throw new ProbeFailure("status", `${label} answered ${res.status}`);
248
+ }
249
+ const digest = createHash("sha256");
250
+ try {
251
+ for await (const chunk of bodyOf(res))
252
+ digest.update(chunk);
253
+ }
254
+ catch {
255
+ throw new ProbeFailure("unreachable", `${label} failed: the body did not arrive in time`);
256
+ }
257
+ const got = digest.digest("base64url");
258
+ if (got !== hash) {
259
+ throw new ProbeFailure("bundleHash", "the launch asset's SHA-256 differs from the manifest's hash");
260
+ }
261
+ }
262
+ /** Sends one GET whose deadline also covers reading its body. */
263
+ async function get(label, url, headers, timeoutMs) {
264
+ const signal = AbortSignal.timeout(timeoutMs);
265
+ try {
266
+ return await fetch(url, { headers, signal });
267
+ }
268
+ catch {
269
+ // The caught error is dropped: its text can quote the URL or the peer.
270
+ throw new ProbeFailure("unreachable", signal.aborted
271
+ ? `${label} failed: no reply within ${timeoutMs} ms`
272
+ : `${label} failed: the server could not be reached`);
273
+ }
274
+ }
275
+ /** Returns the reply body, refusing one over the size the server ever serves. */
276
+ async function readReply(res) {
277
+ let body;
278
+ try {
279
+ body = await readLimited(res, MAX_REPLY_BYTES);
280
+ }
281
+ catch {
282
+ throw new ProbeFailure("unreachable", "GET /manifest failed: the body did not arrive in time");
283
+ }
284
+ if (body === undefined) {
285
+ throw new ProbeFailure("unparseable", `the reply is over ${MAX_REPLY_BYTES} bytes`);
286
+ }
287
+ return body;
288
+ }
289
+ /** Returns the boundary of a `multipart/mixed` Content-Type, unquoted, or undefined. */
290
+ function boundaryOf(contentType) {
291
+ const [type = "", ...params] = (contentType ?? "").split(";");
292
+ if (type.trim().toLowerCase() !== "multipart/mixed")
293
+ return undefined;
294
+ for (const param of params) {
295
+ const eq = param.indexOf("=");
296
+ if (eq !== -1 && param.slice(0, eq).trim().toLowerCase() === "boundary") {
297
+ return param
298
+ .slice(eq + 1)
299
+ .trim()
300
+ .replace(/^"(.*)"$/, "$1");
301
+ }
302
+ }
303
+ return undefined;
304
+ }
305
+ /** The response body; a reply without one reads as empty. */
306
+ const bodyOf = (res) => res.body ?? new ReadableStream();
@@ -0,0 +1,57 @@
1
+ import type { JsonObject } from "@tide-ota/protocol";
2
+ import type { SigningMetadata } from "./keys.ts";
3
+ import type { Platform } from "./publish-record.ts";
4
+ /** One exported file: its bytes and their SHA-256 as the manifest `hash`. */
5
+ interface ExportedFile {
6
+ readonly bytes: Uint8Array<ArrayBuffer>;
7
+ readonly hash: string;
8
+ }
9
+ /** A non-launch asset with the key the bundle references and its bare extension. */
10
+ interface ExportedAsset extends ExportedFile {
11
+ readonly key: string;
12
+ readonly ext: string;
13
+ }
14
+ export interface ExportedPlatform {
15
+ readonly bundle: ExportedFile;
16
+ readonly assets: readonly ExportedAsset[];
17
+ }
18
+ /** What `tide export` writes beside `dist/`: only what every manifest or shipped build already makes public. */
19
+ export interface ProjectExport {
20
+ readonly certificate: string;
21
+ readonly codeSigningMetadata: SigningMetadata;
22
+ readonly expoClient: JsonObject;
23
+ readonly platforms: Readonly<Partial<Record<Platform, {
24
+ readonly runtimeVersion: string;
25
+ }>>>;
26
+ }
27
+ export declare const EXPORT_FILE = "tide-export.json";
28
+ export declare const EXPORT_LIMIT: number;
29
+ /** Returns the bytes of `tide-export.json` for `value`. */
30
+ export declare function encodeProjectExport(value: ProjectExport): Uint8Array<ArrayBuffer>;
31
+ /**
32
+ * Reads an export directory `tide export` wrote: `tide-export.json` and each platform's files under `dist/`. Nothing
33
+ * outside the directory is read; the directory must not change while it is read.
34
+ */
35
+ export declare function readProjectExport(dir: string): Promise<{
36
+ certificate: string;
37
+ codeSigningMetadata: SigningMetadata;
38
+ expoClient: JsonObject;
39
+ platforms: ({
40
+ platform: Platform;
41
+ runtime: string;
42
+ } & ExportedPlatform)[];
43
+ }>;
44
+ /**
45
+ * Reads a production `expo export` of each target's platform from `dir`, returning each target's export and every file
46
+ * read, by its path in `metadata.json`. Every file must resolve inside the directory and be a regular file, and every
47
+ * asset must hash to the key in its path. The directory must not change while it is read.
48
+ */
49
+ export declare function readExport<T extends {
50
+ readonly platform: Platform;
51
+ }>(dir: string, targets: readonly T[]): Promise<{
52
+ platforms: (T & ExportedPlatform)[];
53
+ files: ReadonlyMap<string, Uint8Array<ArrayBuffer>>;
54
+ }>;
55
+ /** Returns the bytes of the regular file at `path`, read through one descriptor; `name` leads each refusal. */
56
+ export declare function readRegular(path: string, limit: number, name: string): Uint8Array<ArrayBuffer>;
57
+ export {};
@@ -0,0 +1,222 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readFileSync, realpathSync, statSync, } from "node:fs";
3
+ import { join, sep } from "node:path";
4
+ import { replyKey, sha256Base64Url } from "@tide-ota/protocol";
5
+ import { isObject, member, signingMetadata } from "./keys.js";
6
+ import { PublishError } from "./publish-record.js";
7
+ export const EXPORT_FILE = "tide-export.json";
8
+ export const EXPORT_LIMIT = 16 * 1024 * 1024;
9
+ const EXPORT_VERSION = 1;
10
+ // Every field the file holds; the reader refuses any other.
11
+ const EXPORT_FIELDS = {
12
+ version: true,
13
+ certificate: true,
14
+ codeSigningMetadata: true,
15
+ expoClient: true,
16
+ platforms: true,
17
+ };
18
+ const CERTIFICATE_LIMIT = 64 * 1024;
19
+ const METADATA_LIMIT = 16 * 1024 * 1024;
20
+ // O_NOFOLLOW refuses a symlink as the last component; O_NONBLOCK keeps a FIFO from hanging the open.
21
+ const OPEN_FLAGS = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
22
+ const SEGMENT = /^[^/\\\0]+$/;
23
+ const EXT = /^[A-Za-z0-9]{1,16}$/;
24
+ // Metro names each file by the key the bundle asks for: the MD5 of its bytes.
25
+ const ASSET_PATH = /^assets\/([0-9a-f]{32})$/;
26
+ const DOM_PATH = /^www\.bundle\/([0-9a-f]{32})\.([A-Za-z0-9]{1,16})$/;
27
+ /** Returns the bytes of `tide-export.json` for `value`. */
28
+ export function encodeProjectExport(value) {
29
+ return new Uint8Array(new TextEncoder().encode(JSON.stringify({ version: EXPORT_VERSION, ...value })));
30
+ }
31
+ /**
32
+ * Reads an export directory `tide export` wrote: `tide-export.json` and each platform's files under `dist/`. Nothing
33
+ * outside the directory is read; the directory must not change while it is read.
34
+ */
35
+ export async function readProjectExport(dir) {
36
+ let root;
37
+ try {
38
+ root = realpathSync(dir);
39
+ }
40
+ catch {
41
+ throw new PublishError("the export directory is unreadable");
42
+ }
43
+ let value;
44
+ try {
45
+ const bytes = readRegular(containedPath(root, EXPORT_FILE, EXPORT_FILE), EXPORT_LIMIT, EXPORT_FILE);
46
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
47
+ }
48
+ catch (e) {
49
+ if (e instanceof PublishError)
50
+ throw e;
51
+ throw new PublishError(`${EXPORT_FILE} is not UTF-8 JSON`);
52
+ }
53
+ const { certificate, codeSigningMetadata, expoClient, platforms } = checkExport(value);
54
+ const targets = Object.entries(platforms).map(([platform, { runtimeVersion }]) => ({
55
+ platform: platform,
56
+ runtime: runtimeVersion,
57
+ }));
58
+ const dist = containedPath(root, "dist", "dist");
59
+ if (!statSync(dist).isDirectory())
60
+ throw new PublishError("export dist is not a directory");
61
+ const exported = (await readExport(dist, targets)).platforms;
62
+ return { certificate, codeSigningMetadata, expoClient, platforms: exported };
63
+ }
64
+ /** Returns `value` as an export, refusing any field it should not hold. */
65
+ function checkExport(value) {
66
+ if (!isObject(value) || !Object.keys(value).every((k) => Object.hasOwn(EXPORT_FIELDS, k))) {
67
+ throw new PublishError(`${EXPORT_FILE} must hold only ${Object.keys(EXPORT_FIELDS).join(", ")}`);
68
+ }
69
+ if (value.version !== EXPORT_VERSION) {
70
+ throw new PublishError(`${EXPORT_FILE} version must be ${EXPORT_VERSION}`);
71
+ }
72
+ const { certificate, codeSigningMetadata, expoClient, platforms } = value;
73
+ if (typeof certificate !== "string" ||
74
+ new TextEncoder().encode(certificate).length > CERTIFICATE_LIMIT) {
75
+ throw new PublishError(`${EXPORT_FILE} certificate must be a string of at most 64 KiB`);
76
+ }
77
+ if (!isObject(expoClient))
78
+ throw new PublishError(`${EXPORT_FILE} expoClient must be an object`);
79
+ const entries = isObject(platforms) ? Object.entries(platforms) : [];
80
+ if (entries.length === 0) {
81
+ throw new PublishError(`${EXPORT_FILE} platforms must name at least one platform`);
82
+ }
83
+ for (const [platform, entry] of entries) {
84
+ const runtime = member(entry, "runtimeVersion");
85
+ if ((platform !== "ios" && platform !== "android") ||
86
+ !isObject(entry) ||
87
+ Object.keys(entry).length !== 1 ||
88
+ typeof runtime !== "string") {
89
+ throw new PublishError(`${EXPORT_FILE} platforms must map ios or android to only a string runtimeVersion`);
90
+ }
91
+ replyKey("main", runtime, platform);
92
+ }
93
+ return {
94
+ certificate,
95
+ codeSigningMetadata: signingMetadata(codeSigningMetadata, `${EXPORT_FILE} codeSigningMetadata`),
96
+ expoClient: expoClient,
97
+ platforms: platforms,
98
+ };
99
+ }
100
+ /**
101
+ * Reads a production `expo export` of each target's platform from `dir`, returning each target's export and every file
102
+ * read, by its path in `metadata.json`. Every file must resolve inside the directory and be a regular file, and every
103
+ * asset must hash to the key in its path. The directory must not change while it is read.
104
+ */
105
+ export async function readExport(dir, targets) {
106
+ let root;
107
+ try {
108
+ root = realpathSync(dir);
109
+ }
110
+ catch {
111
+ throw new PublishError("the export directory is unreadable");
112
+ }
113
+ const cache = new Map();
114
+ const files = new Map();
115
+ const file = async (path, field) => {
116
+ const real = containedPath(root, path, field);
117
+ let found = cache.get(real);
118
+ if (found === undefined) {
119
+ const bytes = readRegular(real, Infinity, `export ${field}`);
120
+ found = { bytes, hash: await sha256Base64Url(bytes) };
121
+ cache.set(real, found);
122
+ }
123
+ files.set(path, found.bytes);
124
+ return found;
125
+ };
126
+ let metadata;
127
+ try {
128
+ const bytes = readRegular(containedPath(root, "metadata.json", "metadata.json"), METADATA_LIMIT, "export metadata.json");
129
+ files.set("metadata.json", bytes);
130
+ metadata = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
131
+ }
132
+ catch (e) {
133
+ if (e instanceof PublishError)
134
+ throw e;
135
+ throw new PublishError("export metadata.json is not UTF-8 JSON");
136
+ }
137
+ if (member(metadata, "version") !== 0 || member(metadata, "bundler") !== "metro") {
138
+ throw new PublishError("export metadata.json is not version 0 from metro");
139
+ }
140
+ const result = [];
141
+ for (const target of targets) {
142
+ const { platform } = target;
143
+ const at = `metadata.json fileMetadata.${platform}`;
144
+ const entry = member(member(metadata, "fileMetadata"), platform);
145
+ const list = member(entry, "assets");
146
+ if (entry === undefined)
147
+ throw new PublishError(`export has no ${platform} bundle: ${at} is missing`);
148
+ if (!Array.isArray(list))
149
+ throw new PublishError(`export ${at}.assets is not an array`);
150
+ const bundle = await file(member(entry, "bundle"), `${at}.bundle`);
151
+ const assets = new Map();
152
+ for (const [i, item] of list.entries()) {
153
+ const name = `${at}.assets[${i}]`;
154
+ const path = member(item, "path");
155
+ const ext = member(item, "ext");
156
+ if (typeof ext !== "string" || !EXT.test(ext)) {
157
+ throw new PublishError(`export ${name}.ext must be 1 to 16 of A-Z, a-z and 0-9`);
158
+ }
159
+ const match = typeof path === "string" ? (ASSET_PATH.exec(path) ?? DOM_PATH.exec(path)) : null;
160
+ if (match === null || (match[2] !== undefined && match[2] !== ext)) {
161
+ throw new PublishError(`export ${name}.path is not assets/<md5> or www.bundle/<md5>.<ext>`);
162
+ }
163
+ const key = match[1] ?? "";
164
+ const exported = await file(path, `${name}.path`);
165
+ if (createHash("md5").update(exported.bytes).digest("hex") !== key) {
166
+ throw new PublishError(`export ${name}.path does not hash to the key in its name: the file changed after expo export`);
167
+ }
168
+ // DOM components can each list the same content-hashed chunk; identical entries collapse to one.
169
+ const seen = assets.get(key);
170
+ if (seen === undefined)
171
+ assets.set(key, { ...exported, key, ext });
172
+ else if (seen.ext !== ext) {
173
+ throw new PublishError(`export ${name} lists key ${key} with two extensions`);
174
+ }
175
+ else if (seen.hash !== exported.hash) {
176
+ // MD5 collides; SHA-256 is the identity the manifest promises.
177
+ throw new PublishError(`export ${name} lists key ${key} for two different files`);
178
+ }
179
+ }
180
+ result.push({ ...target, bundle, assets: [...assets.values()] });
181
+ }
182
+ return { platforms: result, files };
183
+ }
184
+ /** Returns the real path of `path` under `root`, refusing any form or symlink that leaves it. */
185
+ function containedPath(root, path, field) {
186
+ if (typeof path !== "string" ||
187
+ !path.split("/").every((s) => SEGMENT.test(s) && s !== "." && s !== "..")) {
188
+ throw new PublishError(`export ${field} must be a relative path inside the export`);
189
+ }
190
+ let real;
191
+ try {
192
+ real = realpathSync(join(root, path));
193
+ }
194
+ catch {
195
+ throw new PublishError(`export ${field} is missing or unreadable`);
196
+ }
197
+ if (!real.startsWith(root + sep)) {
198
+ throw new PublishError(`export ${field} resolves outside the export directory`);
199
+ }
200
+ return real;
201
+ }
202
+ /** Returns the bytes of the regular file at `path`, read through one descriptor; `name` leads each refusal. */
203
+ export function readRegular(path, limit, name) {
204
+ let fd;
205
+ try {
206
+ fd = openSync(path, OPEN_FLAGS);
207
+ }
208
+ catch {
209
+ throw new PublishError(`${name} is missing or unreadable`);
210
+ }
211
+ try {
212
+ const stat = fstatSync(fd);
213
+ if (!stat.isFile())
214
+ throw new PublishError(`${name} is not a regular file`);
215
+ if (stat.size > limit)
216
+ throw new PublishError(`${name} is over ${limit} bytes`);
217
+ return new Uint8Array(readFileSync(fd));
218
+ }
219
+ finally {
220
+ closeSync(fd);
221
+ }
222
+ }
@@ -0,0 +1,35 @@
1
+ import type { Bucket } from "./bucket.ts";
2
+ import type { Platform } from "./publish-record.ts";
3
+ /** A registered base of a publish target's runtime and platform; `createdAt` is an update's release record time. */
4
+ export interface PatchBase {
5
+ readonly key: string;
6
+ readonly kind: "update" | "embedded";
7
+ readonly runtimeVersion: string;
8
+ readonly platform: Platform;
9
+ readonly hash: string;
10
+ readonly createdAt: string | undefined;
11
+ }
12
+ interface PatchTarget {
13
+ readonly runtime: string;
14
+ readonly platform: Platform;
15
+ readonly bundle: {
16
+ readonly bytes: Uint8Array;
17
+ readonly hash: string;
18
+ };
19
+ }
20
+ /** Patches by store key, each applied to its base and hash-checked. */
21
+ type Patches = Map<string, Uint8Array<ArrayBuffer>>;
22
+ /**
23
+ * Returns the patches to store for each target's new bundle, from every embedded build and the newest
24
+ * `PATCH_UPDATE_BASES` updates of its runtime and platform. `stored` is the `bundles/` listing by key, with sizes.
25
+ * Refuses a base whose bundle is not stored and a patch that fails its self-check; writes nothing.
26
+ */
27
+ export declare function preparePatches(bucket: Bucket, targets: readonly PatchTarget[], bases: readonly PatchBase[], stored: ReadonlyMap<string, number>): Promise<Patches>;
28
+ /** Refuses `patch` unless protocol `applyBsdiff` turns `base` into bytes whose SHA-256 is `target.hash`. */
29
+ export declare function checkPatch(base: Uint8Array, patch: Uint8Array, target: {
30
+ readonly bytes: Uint8Array;
31
+ readonly hash: string;
32
+ }, key: string): Promise<void>;
33
+ /** Stores each patch; a lost create holds the same bytes, since `makeBsdiff` depends only on its inputs. */
34
+ export declare function uploadPatches(bucket: Bucket, patches: Patches): Promise<void>;
35
+ export {};