@tide-ota/protocol 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/s3.js ADDED
@@ -0,0 +1,411 @@
1
+ import { ProtocolError, hex, sha256Hex } from "./hash.js";
2
+ /** Error codes a message may name; S3 defines many more, and any other is reported as unrecognised. */
3
+ const S3_ERROR_CODES = new Set([
4
+ "AccessDenied",
5
+ "InvalidAccessKeyId",
6
+ "SignatureDoesNotMatch",
7
+ "RequestTimeTooSkewed",
8
+ "NoSuchKey",
9
+ "NoSuchBucket",
10
+ "PreconditionFailed",
11
+ "ConditionalRequestConflict",
12
+ "InvalidArgument",
13
+ "InvalidRequest",
14
+ "XAmzContentSHA256Mismatch",
15
+ "SlowDown",
16
+ "InternalError",
17
+ "ServiceUnavailable",
18
+ ]);
19
+ /** What can be wrong with a 200; each is reported in these fixed words, never with the value received. */
20
+ const PROBLEMS = {
21
+ encoding: "an unsupported content-encoding",
22
+ length: "a missing or invalid content-length",
23
+ body: "a body that differs from its content-length",
24
+ over: "a content-length over the caller's limit",
25
+ etag: "a missing or invalid ETag",
26
+ date: "a missing or invalid Date",
27
+ listing: "an invalid listing page",
28
+ };
29
+ /**
30
+ * An S3 failure. Its message holds only fixed words, the operation, the HTTP status and an allowlisted error code,
31
+ * so no provider text, key or credential can reach a log.
32
+ */
33
+ export class S3Error extends Error {
34
+ status; // Undefined when no response arrived.
35
+ constructor(operation, failure) {
36
+ super(s3Message(operation, failure));
37
+ this.name = "S3Error";
38
+ this.status =
39
+ failure === "network" || "timeoutMs" in failure
40
+ ? undefined
41
+ : "problem" in failure
42
+ ? 200
43
+ : failure.status;
44
+ }
45
+ /** The error for a request that got no response: a timeout when the deadline aborted it, else a network failure. */
46
+ static unanswered(operation, aborted, timeoutMs) {
47
+ return new S3Error(operation, aborted ? { timeoutMs } : "network");
48
+ }
49
+ }
50
+ function s3Message(operation, failure) {
51
+ const what = `S3 ${operation}`;
52
+ if (failure === "network")
53
+ return `${what} failed: network error`;
54
+ if ("timeoutMs" in failure)
55
+ return `${what} timed out after ${failure.timeoutMs} ms`;
56
+ if ("problem" in failure)
57
+ return `${what} returned 200 with ${PROBLEMS[failure.problem]}`;
58
+ const { status, code } = failure;
59
+ if (code === undefined)
60
+ return `${what} failed: ${status} without an S3 error document`;
61
+ if (S3_ERROR_CODES.has(code))
62
+ return `${what} failed: ${status} ${code}`;
63
+ return `${what} failed: ${status} with an unrecognised error code`;
64
+ }
65
+ export const EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
66
+ const ERROR_BODY_LIMIT = 4096;
67
+ const encoder = new TextEncoder();
68
+ /** Returns the validated target; no message echoes a value, since a rejected one may carry a credential. */
69
+ export function s3Target(config) {
70
+ const endpoint = URL.parse(config.endpoint);
71
+ if (!endpoint ||
72
+ !/^https?:$/.test(endpoint.protocol) ||
73
+ endpoint.href !== `${endpoint.origin}/`) {
74
+ throw new ProtocolError("endpoint", "must be an http or https origin with no credentials, path or query");
75
+ }
76
+ // One path segment that cannot be a dot segment or carry a query: the request cannot leave the bucket.
77
+ if (!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(config.bucket)) {
78
+ throw new ProtocolError("bucket", "must be 3 to 63 of a-z, 0-9, . and -, starting and ending alphanumeric");
79
+ }
80
+ return { endpoint, bucket: config.bucket, credentials: sigV4Credentials(config, "s3") };
81
+ }
82
+ /** Returns validated credentials for `service`; a rejected one throws a `ProtocolError` naming the field, never the value. */
83
+ export function sigV4Credentials(config, service) {
84
+ const { region, accessKeyId, secretAccessKey } = config;
85
+ if (!/^[a-z0-9-]{1,32}$/.test(region)) {
86
+ throw new ProtocolError("region", "must be 1 to 32 of a-z, 0-9 and -");
87
+ }
88
+ // Header-safe: printable ASCII with no whitespace.
89
+ if (!/^[A-Za-z0-9]{16,128}$/.test(accessKeyId)) {
90
+ throw new ProtocolError("accessKeyId", "must be 16 to 128 of A-Z, a-z and 0-9");
91
+ }
92
+ if (!/^[\x21-\x7E]{16,256}$/.test(secretAccessKey)) {
93
+ throw new ProtocolError("secretAccessKey", "must be 16 to 256 printable ASCII characters");
94
+ }
95
+ return { accessKeyId, secretAccessKey, region, service };
96
+ }
97
+ /** Signs and sends one S3 request through `awsFetch`. */
98
+ export function s3Fetch(target, request, signal) {
99
+ // S3 reads a literal + in a path as a space, so each segment is sent in SigV4's encoding.
100
+ const path = request.key === undefined
101
+ ? `/${target.bucket}`
102
+ : `/${target.bucket}/${request.key.split("/").map(uriEncode).join("/")}`;
103
+ const query = Object.entries(request.query ?? {})
104
+ .map(([k, v]) => `${uriEncode(k)}=${uriEncode(v)}`)
105
+ .join("&");
106
+ const url = new URL(query === "" ? path : `${path}?${query}`, target.endpoint);
107
+ return awsFetch({ ...request, url }, target.credentials, signal);
108
+ }
109
+ /**
110
+ * Signs and sends one request with every header given. A 3xx is returned, never followed. Network failures reject
111
+ * with fetch's own error, which the caller replaces with its own.
112
+ */
113
+ export async function awsFetch(request, credentials, signal) {
114
+ const { method, url, body } = request;
115
+ const signed = {
116
+ ...request.headers,
117
+ host: url.host,
118
+ "x-amz-content-sha256": body === undefined ? EMPTY_SHA256 : await sha256Hex(body),
119
+ "x-amz-date": new Date().toISOString().replace(/[-:]|\.\d{3}/g, ""),
120
+ };
121
+ const authorization = await signV4({ method, url, headers: signed }, credentials);
122
+ const { host: _, ...headers } = signed; // fetch sets Host itself.
123
+ return fetch(url, {
124
+ method,
125
+ headers: { ...headers, authorization },
126
+ ...(body === undefined ? {} : { body }),
127
+ redirect: "manual", // workerd has no "error" mode; a 3xx sends no credential to another origin.
128
+ signal,
129
+ });
130
+ }
131
+ /** Returns the SigV4 `Authorization` value for a request, signing its query and every header given. */
132
+ export async function signV4(request, credentials) {
133
+ const headers = Object.entries(request.headers)
134
+ .map(([k, v]) => [k.toLowerCase(), v.trim().replace(/\s+/g, " ")])
135
+ .sort(([a], [b]) => compare(a, b));
136
+ const header = (name) => headers.find(([k]) => k === name)?.[1];
137
+ const date = header("x-amz-date");
138
+ const payloadHash = header("x-amz-content-sha256");
139
+ if (date === undefined || !/^\d{8}T\d{6}Z$/.test(date) || payloadHash === undefined) {
140
+ throw new Error("signV4 needs x-amz-date and x-amz-content-sha256 headers");
141
+ }
142
+ const search = request.url.search.slice(1);
143
+ const query = (search === "" ? [] : search.split("&"))
144
+ .map((pair) => {
145
+ const eq = pair.indexOf("=");
146
+ const [name, value] = eq === -1 ? [pair, ""] : [pair.slice(0, eq), pair.slice(eq + 1)];
147
+ return [uriEncode(decodeURIComponent(name)), uriEncode(decodeURIComponent(value))];
148
+ })
149
+ .sort(([an, av], [bn, bv]) => compare(an, bn) || compare(av, bv));
150
+ const signedHeaders = headers.map(([k]) => k).join(";");
151
+ const canonicalRequest = [
152
+ request.method,
153
+ request.url.pathname
154
+ .split("/")
155
+ .map((s) => uriEncode(decodeURIComponent(s)))
156
+ .join("/"),
157
+ query.map(([n, v]) => `${n}=${v}`).join("&"),
158
+ headers.map(([k, v]) => `${k}:${v}\n`).join(""),
159
+ signedHeaders,
160
+ payloadHash,
161
+ ].join("\n");
162
+ const scope = `${date.slice(0, 8)}/${credentials.region}/${credentials.service}/aws4_request`;
163
+ const stringToSign = [
164
+ "AWS4-HMAC-SHA256",
165
+ date,
166
+ scope,
167
+ await sha256Hex(new Uint8Array(encoder.encode(canonicalRequest))),
168
+ ].join("\n");
169
+ let key = new Uint8Array(encoder.encode(`AWS4${credentials.secretAccessKey}`));
170
+ for (const part of scope.split("/"))
171
+ key = await hmac(key, part);
172
+ const signature = hex(await hmac(key, stringToSign));
173
+ return `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope},SignedHeaders=${signedHeaders},Signature=${signature}`;
174
+ }
175
+ /** Returns what makes a 200 unusable as one whole unencoded object, or undefined. */
176
+ export function s3BodyProblem(res) {
177
+ const encoding = res.headers.get("content-encoding");
178
+ // Tide stores objects unencoded; fetch would also decode gzip without changing the length.
179
+ if (encoding !== null && encoding !== "identity")
180
+ return "encoding";
181
+ const length = res.headers.get("content-length");
182
+ if (res.body === null ||
183
+ length === null ||
184
+ !/^\d+$/.test(length) ||
185
+ !Number.isSafeInteger(Number(length))) {
186
+ return "length";
187
+ }
188
+ return undefined;
189
+ }
190
+ /**
191
+ * Returns the `Code` of a complete S3 error document of at most 4 KiB: root `Error` with exactly one direct,
192
+ * text-only `Code` child. Anything else is undefined; a body that fails mid-read rejects.
193
+ */
194
+ export async function s3ErrorCode(res) {
195
+ const root = parseS3Xml((await readS3Text(res, ERROR_BODY_LIMIT)) ?? "");
196
+ if (root?.name !== "Error")
197
+ return undefined;
198
+ const codes = childElements(root, "Code");
199
+ const code = codes.length === 1 && codes[0] !== undefined ? textOf(codes[0]) : undefined;
200
+ return code === "" ? undefined : code;
201
+ }
202
+ /** Returns undefined for a 404 `NoSuchKey`, the one non-200 that means absence; any other response throws. */
203
+ export async function s3Absent(operation, res) {
204
+ const code = await s3ErrorCode(res);
205
+ if (res.status === 404 && code === "NoSuchKey")
206
+ return undefined;
207
+ throw new S3Error(operation, { status: res.status, code });
208
+ }
209
+ /**
210
+ * Returns a body of at most `limit` bytes as text, or undefined when it is absent, longer, or not valid UTF-8; the
211
+ * read stops at the limit. A body that fails mid-read rejects.
212
+ */
213
+ export async function readS3Text(res, limit) {
214
+ if (res.body === null)
215
+ return undefined;
216
+ const bytes = await readLimited(res, limit);
217
+ if (bytes === undefined)
218
+ return undefined;
219
+ try {
220
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
221
+ }
222
+ catch {
223
+ return undefined;
224
+ }
225
+ }
226
+ /** Returns the body's bytes, empty when absent, or undefined once it passes `limit`, cancelling the rest. */
227
+ export async function readLimited(res, limit) {
228
+ if (res.body === null)
229
+ return new Uint8Array(0);
230
+ const reader = res.body.getReader();
231
+ const chunks = [];
232
+ let size = 0;
233
+ for (;;) {
234
+ const { done, value } = await reader.read();
235
+ if (done)
236
+ break;
237
+ size += value.byteLength;
238
+ if (size > limit) {
239
+ await reader.cancel();
240
+ return undefined;
241
+ }
242
+ chunks.push(value);
243
+ }
244
+ const bytes = new Uint8Array(size);
245
+ let at = 0;
246
+ for (const c of chunks) {
247
+ bytes.set(c, at);
248
+ at += c.byteLength;
249
+ }
250
+ return bytes;
251
+ }
252
+ const S3_NAMESPACE = "http://s3.amazonaws.com/doc/2006-03-01/";
253
+ const XML_DECLARATION = /<\?xml [^<>?]*\?>/y;
254
+ const WHITESPACE = /[ \t\r\n]*/y;
255
+ const ELEMENT_NAME = /[A-Za-z_][A-Za-z0-9._-]*/y; // No colon: prefixed names are rejected.
256
+ const TAG_REST = /(?:[ \t\r\n]+xmlns="([^"<&]*)")?[ \t\r\n]*(\/?)>/y;
257
+ const ENTITIES = {
258
+ lt: "<",
259
+ gt: ">",
260
+ amp: "&",
261
+ quot: '"',
262
+ apos: "'",
263
+ };
264
+ /**
265
+ * Returns the element tree of one S3 response document, or undefined. Strict: an optional XML declaration, elements
266
+ * and text with the predefined entities and character references; no comments, CDATA, DOCTYPE, processing
267
+ * instructions, prefixed names, or attributes other than the S3 namespace on the root.
268
+ */
269
+ export function parseS3Xml(text) {
270
+ let at = 0;
271
+ const skip = (re) => {
272
+ re.lastIndex = at;
273
+ if (re.test(text))
274
+ at = re.lastIndex;
275
+ };
276
+ skip(XML_DECLARATION);
277
+ skip(WHITESPACE);
278
+ const open = [];
279
+ let root;
280
+ while (root === undefined) {
281
+ const parent = open.at(-1);
282
+ if (text[at] !== "<") {
283
+ const end = text.indexOf("<", at);
284
+ if (parent === undefined || end === -1)
285
+ return undefined;
286
+ const decoded = decodeText(text.slice(at, end));
287
+ if (decoded === undefined)
288
+ return undefined;
289
+ parent.children.push(decoded);
290
+ at = end;
291
+ }
292
+ else if (text.startsWith("</", at)) {
293
+ if (parent === undefined || !text.startsWith(`</${parent.name}`, at))
294
+ return undefined;
295
+ at += parent.name.length + 2;
296
+ skip(WHITESPACE);
297
+ if (text[at] !== ">")
298
+ return undefined;
299
+ at++;
300
+ open.pop();
301
+ if (open.length === 0)
302
+ root = parent;
303
+ }
304
+ else {
305
+ ELEMENT_NAME.lastIndex = at + 1;
306
+ const name = ELEMENT_NAME.exec(text)?.[0];
307
+ if (name === undefined)
308
+ return undefined;
309
+ TAG_REST.lastIndex = ELEMENT_NAME.lastIndex;
310
+ const rest = TAG_REST.exec(text);
311
+ if (rest === null)
312
+ return undefined;
313
+ const xmlns = rest[1];
314
+ if (xmlns !== undefined && (parent !== undefined || xmlns !== S3_NAMESPACE))
315
+ return undefined;
316
+ at = TAG_REST.lastIndex;
317
+ const element = { name, children: [] };
318
+ parent?.children.push(element);
319
+ if (rest[2] !== "/")
320
+ open.push(element);
321
+ else if (parent === undefined)
322
+ root = element;
323
+ }
324
+ }
325
+ skip(WHITESPACE);
326
+ return at === text.length ? root : undefined;
327
+ }
328
+ function decodeText(raw) {
329
+ if (raw.includes("]]>"))
330
+ return undefined;
331
+ const [first = "", ...rest] = raw.split("&");
332
+ let text = first;
333
+ for (const part of rest) {
334
+ const m = /^(?:([a-z]+)|#([0-9]{1,7})|#x([0-9a-fA-F]{1,6}));/.exec(part);
335
+ if (m === null)
336
+ return undefined;
337
+ const [ref, name, dec, hexDigits] = m;
338
+ const point = dec !== undefined ? Number(dec) : parseInt(hexDigits ?? "", 16);
339
+ const char = name !== undefined
340
+ ? ENTITIES[name]
341
+ : point === 0x9 ||
342
+ point === 0xa ||
343
+ point === 0xd ||
344
+ (point >= 0x20 && point <= 0xd7ff) ||
345
+ (point >= 0xe000 && point <= 0xfffd) ||
346
+ (point >= 0x10000 && point <= 0x10ffff)
347
+ ? String.fromCodePoint(point)
348
+ : undefined;
349
+ if (char === undefined)
350
+ return undefined;
351
+ text += char + part.slice(ref.length);
352
+ }
353
+ return text;
354
+ }
355
+ /** Returns the direct children of `element` named `name`. */
356
+ export function childElements(element, name) {
357
+ return element.children.filter((c) => typeof c !== "string" && c.name === name);
358
+ }
359
+ /** Returns the text of an element holding only text ("" when empty), or undefined. */
360
+ export function textOf(element) {
361
+ let text = "";
362
+ for (const c of element.children) {
363
+ if (typeof c !== "string")
364
+ return undefined;
365
+ text += c;
366
+ }
367
+ return text;
368
+ }
369
+ // The TIDE_ prefix keeps ambient AWS credentials out.
370
+ const S3_VARS = {
371
+ endpoint: "TIDE_S3_ENDPOINT",
372
+ region: "TIDE_S3_REGION",
373
+ bucket: "TIDE_S3_BUCKET",
374
+ accessKeyId: "TIDE_S3_ACCESS_KEY_ID",
375
+ secretAccessKey: "TIDE_S3_SECRET_ACCESS_KEY",
376
+ };
377
+ /** Returns the store the environment configures: TIDE_DISK_DIR, or every TIDE_S3_* variable. Empty means unset. */
378
+ export function storageFromEnv(env) {
379
+ const read = (name) => (env[name] === "" ? undefined : env[name]);
380
+ const disk = read("TIDE_DISK_DIR");
381
+ const names = Object.values(S3_VARS);
382
+ const missing = names.filter((name) => read(name) === undefined);
383
+ if (missing.length === names.length) {
384
+ if (disk !== undefined)
385
+ return { disk };
386
+ throw new Error(`no store configured: set TIDE_DISK_DIR, or all of ${names.join(", ")}`);
387
+ }
388
+ if (disk !== undefined)
389
+ throw new Error("set TIDE_DISK_DIR or the TIDE_S3_* variables, not both");
390
+ if (missing.length > 0)
391
+ throw new Error(`S3 store incomplete: set ${missing.join(", ")}`);
392
+ const config = Object.fromEntries(Object.entries(S3_VARS).map(([field, name]) => [field, read(name)]));
393
+ try {
394
+ s3Target(config);
395
+ }
396
+ catch (e) {
397
+ if (!(e instanceof ProtocolError))
398
+ throw e;
399
+ throw new Error(`${S3_VARS[e.field]}: ${e.message}`);
400
+ }
401
+ return { s3: config };
402
+ }
403
+ /** RFC 3986 encoding, as SigV4 requires: everything but unreserved characters. */
404
+ const uriEncode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
405
+ async function hmac(key, data) {
406
+ const k = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, [
407
+ "sign",
408
+ ]);
409
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, encoder.encode(data)));
410
+ }
411
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
package/dist/sfv.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Returns `members` as an RFC 8941 dictionary of strings, the `expo-manifest-filters` header value. */
2
+ export declare function encodeSfvDictionary(members: Readonly<Record<string, string>>): string;
3
+ /** A dictionary member: the text of a string or token, or the kind of any other item. */
4
+ type SfvMember = {
5
+ readonly kind: "string" | "token";
6
+ readonly text: string;
7
+ } | {
8
+ readonly kind: "number" | "bytes" | "boolean" | "inner-list";
9
+ };
10
+ /** Returns the members of an RFC 8941 dictionary. Parameters are dropped and a repeated key keeps its last value. */
11
+ export declare function parseSfvDictionary(value: string, field: string): Map<string, SfvMember>;
12
+ export {};
package/dist/sfv.js ADDED
@@ -0,0 +1,146 @@
1
+ import { ProtocolError } from "./hash.js";
2
+ const KEY = /[a-z*][a-z0-9_.*-]*/y; // Sticky: the parser matches at `lastIndex`.
3
+ const STRING_CHAR = /[\x20-\x7E]/;
4
+ const WHOLE_KEY = new RegExp(`^(?:${KEY.source})$`);
5
+ const WHOLE_STRING = new RegExp(`^${STRING_CHAR.source}*$`);
6
+ /** Returns `members` as an RFC 8941 dictionary of strings, the `expo-manifest-filters` header value. */
7
+ export function encodeSfvDictionary(members) {
8
+ const entries = Object.entries(members);
9
+ return entries
10
+ .map(([key, value]) => {
11
+ if (!WHOLE_KEY.test(key))
12
+ throw new ProtocolError(key, "must be an RFC 8941 key");
13
+ if (typeof value !== "string" || !WHOLE_STRING.test(value)) {
14
+ throw new ProtocolError(key, "must be a string of printable ASCII");
15
+ }
16
+ return `${key}="${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
17
+ })
18
+ .join(", ");
19
+ }
20
+ const TOKEN_CHAR = /[!#$%&'*+.^_`|~0-9A-Za-z:/-]/;
21
+ // Empty or padded base64: the byte sequences both stock clients decode (iOS rejects unpadded, Android extra `=`).
22
+ const BYTES = /^:((?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?):/;
23
+ /** Returns the members of an RFC 8941 dictionary. Parameters are dropped and a repeated key keeps its last value. */
24
+ export function parseSfvDictionary(value, field) {
25
+ const fail = (reason) => {
26
+ throw new ProtocolError(field, `is not an RFC 8941 dictionary: ${reason}`);
27
+ };
28
+ const members = new Map();
29
+ let at = 0;
30
+ const peek = () => value[at] ?? "";
31
+ const skip = (chars) => {
32
+ while (at < value.length && chars.includes(peek()))
33
+ at++;
34
+ };
35
+ const key = () => {
36
+ KEY.lastIndex = at;
37
+ const k = KEY.exec(value)?.[0] ?? fail(`expected a key at ${at}`);
38
+ at += k.length;
39
+ return k;
40
+ };
41
+ const bareItem = () => {
42
+ const c = peek();
43
+ if (c === '"') {
44
+ let s = "";
45
+ for (at++;; at++) {
46
+ const ch = peek();
47
+ if (ch === "")
48
+ return fail("unterminated string");
49
+ if (ch === '"')
50
+ break;
51
+ if (ch === "\\") {
52
+ at++;
53
+ if (peek() !== '"' && peek() !== "\\")
54
+ fail(`bad escape at ${at}`);
55
+ s += peek();
56
+ }
57
+ else if (!STRING_CHAR.test(ch)) {
58
+ fail(`bad string character at ${at}`);
59
+ }
60
+ else
61
+ s += ch;
62
+ }
63
+ at++;
64
+ return { kind: "string", text: s };
65
+ }
66
+ if (c === "-" || (c >= "0" && c <= "9")) {
67
+ const m = /^-?(?:\d{1,15}(?![\d.])|\d{1,12}\.\d{1,3}(?!\d))/.exec(value.slice(at));
68
+ if (m === null)
69
+ return fail(`bad number at ${at}`);
70
+ at += m[0].length;
71
+ return { kind: "number" };
72
+ }
73
+ if (/[A-Za-z*]/.test(c)) {
74
+ const start = at;
75
+ for (at++; TOKEN_CHAR.test(peek()); at++)
76
+ ;
77
+ return { kind: "token", text: value.slice(start, at) };
78
+ }
79
+ if (c === ":") {
80
+ const m = BYTES.exec(value.slice(at));
81
+ if (m === null)
82
+ return fail(`bad byte sequence at ${at}`);
83
+ at += m[0].length;
84
+ return { kind: "bytes" };
85
+ }
86
+ if (c === "?") {
87
+ if (value[at + 1] !== "0" && value[at + 1] !== "1")
88
+ fail(`bad boolean at ${at}`);
89
+ at += 2;
90
+ return { kind: "boolean" };
91
+ }
92
+ return fail(`expected an item at ${at}`);
93
+ };
94
+ const parameters = () => {
95
+ while (peek() === ";") {
96
+ at++;
97
+ skip(" ");
98
+ key();
99
+ if (peek() === "=") {
100
+ at++;
101
+ bareItem();
102
+ }
103
+ }
104
+ };
105
+ const itemOrInnerList = () => {
106
+ if (peek() !== "(") {
107
+ const item = bareItem();
108
+ parameters();
109
+ return item;
110
+ }
111
+ for (at++;;) {
112
+ skip(" ");
113
+ if (peek() === ")")
114
+ break;
115
+ bareItem();
116
+ parameters();
117
+ if (peek() !== " " && peek() !== ")")
118
+ fail(`expected space or ) at ${at}`);
119
+ }
120
+ at++;
121
+ parameters();
122
+ return { kind: "inner-list" };
123
+ };
124
+ skip(" ");
125
+ while (at < value.length) {
126
+ const k = key();
127
+ let member = { kind: "boolean" }; // A bare key is the boolean true.
128
+ if (peek() === "=") {
129
+ at++;
130
+ member = itemOrInnerList();
131
+ }
132
+ else
133
+ parameters();
134
+ members.set(k, member);
135
+ skip(" \t");
136
+ if (at === value.length)
137
+ break;
138
+ if (peek() !== ",")
139
+ fail(`expected , at ${at}`);
140
+ at++;
141
+ skip(" \t");
142
+ if (at === value.length)
143
+ fail("trailing comma");
144
+ }
145
+ return members;
146
+ }
@@ -0,0 +1,32 @@
1
+ /** Signs exact bytes with RSASSA-PKCS1-v1_5 SHA-256; the caller leaves `bytes` unchanged until `sign` settles. */
2
+ export interface Signer {
3
+ readonly keyId: string;
4
+ sign(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
5
+ }
6
+ /** Returns a signer over a private RSASSA-PKCS1-v1_5 SHA-256 key, the only key whose digest matches the header. */
7
+ export declare function cryptoKeySigner(key: CryptoKey, keyId: string): Signer;
8
+ /** Returns the expo-signature header value for `bytes`. The key ID is checked before the signer runs. */
9
+ export declare function expoSignature(bytes: Uint8Array<ArrayBuffer>, signer: Signer): Promise<string>;
10
+ /**
11
+ * Checks `header` over `bytes` as expo-updates does, but stricter: a non-string `keyid` or `alg` is malformed,
12
+ * where the client would apply the default. `key` must come from trusted configuration, never from the response.
13
+ */
14
+ export declare function verifyExpoSignature(bytes: Uint8Array<ArrayBuffer>, header: string, key: CryptoKey, keyId: string): Promise<void>;
15
+ /** Returns the signature bytes and key ID of an expo-signature header, checked as `verifyExpoSignature` does. */
16
+ export declare function parseExpoSignature(header: string): {
17
+ readonly sig: Uint8Array<ArrayBuffer>;
18
+ readonly keyId: string;
19
+ };
20
+ /** Returns the verify key in the first CERTIFICATE block of `pem`. Dates, usages and the chain are not checked. */
21
+ export declare function certificatePublicKey(pem: string): Promise<CryptoKey>;
22
+ /** A direct-signing certificate's verify key, and the lowercase hex SHA-256 of its DER. */
23
+ export interface CodeSigningCertificate {
24
+ readonly key: CryptoKey;
25
+ readonly sha256: string;
26
+ }
27
+ /**
28
+ * Returns `pem` as the one self-signed certificate stock expo-updates trusts for direct signing at `now`: X.509 v3,
29
+ * valid at `now`, sha256WithRSAEncryption, Key Usage digitalSignature, Extended Key Usage codeSigning, no Expo
30
+ * project information, and an RSA key of 2048 to 4096 bits.
31
+ */
32
+ export declare function codeSigningCertificate(pem: string, now: Date): Promise<CodeSigningCertificate>;