@tide-ota/cli 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,171 @@
1
+ import { createHash } from "node:crypto";
2
+ import { ProtocolError, awsFetch, decodeBase64, readS3Text, sigV4Credentials, } from "@tide-ota/protocol";
3
+ import { KeyError, read } from "./keys.js";
4
+ /** The KMS signer's variables; the TIDE_ prefix keeps ambient AWS credentials out. */
5
+ export const KMS_VARIABLES = {
6
+ keyId: "TIDE_KMS_KEY_ID",
7
+ region: "TIDE_KMS_REGION",
8
+ accessKeyId: "TIDE_KMS_ACCESS_KEY_ID",
9
+ secretAccessKey: "TIDE_KMS_SECRET_ACCESS_KEY",
10
+ sessionToken: "TIDE_KMS_SESSION_TOKEN",
11
+ endpoint: "TIDE_KMS_ENDPOINT",
12
+ };
13
+ const REQUIRED = ["keyId", "region", "accessKeyId", "secretAccessKey"];
14
+ const ALGORITHM = "RSASSA_PKCS1_V1_5_SHA_256";
15
+ const BODY_LIMIT = 16 * 1024;
16
+ /** Error codes a message may name; KMS defines more, and any other is reported as unrecognised. */
17
+ const ERROR_CODES = new Set([
18
+ "AccessDeniedException",
19
+ "ThrottlingException",
20
+ "DisabledException",
21
+ "KMSInvalidStateException",
22
+ "NotFoundException",
23
+ "InvalidKeyUsageException",
24
+ "KeyUnavailableException",
25
+ "DependencyTimeoutException",
26
+ "KMSInternalException",
27
+ "UnrecognizedClientException",
28
+ "InvalidSignatureException",
29
+ "IncompleteSignature",
30
+ "ExpiredTokenException",
31
+ "ValidationException",
32
+ ]);
33
+ /** Returns the validated KMS target; no message echoes a value, since a rejected one may carry a credential. */
34
+ function kmsTarget(env) {
35
+ const value = (field) => read(env, KMS_VARIABLES[field]);
36
+ const missing = REQUIRED.filter((field) => value(field) === undefined);
37
+ if (missing.length > 0) {
38
+ throw new KeyError(`KMS signer incomplete: set ${missing.map((f) => KMS_VARIABLES[f]).join(", ")}`);
39
+ }
40
+ const required = (field) => value(field) ?? ""; // Present: checked above.
41
+ const keyId = required("keyId");
42
+ if (!/^[\x21-\x7E]{1,2048}$/.test(keyId)) {
43
+ throw new KeyError(`${KMS_VARIABLES.keyId} must be 1 to 2048 printable ASCII characters`);
44
+ }
45
+ let credentials;
46
+ try {
47
+ credentials = sigV4Credentials({
48
+ region: required("region"),
49
+ accessKeyId: required("accessKeyId"),
50
+ secretAccessKey: required("secretAccessKey"),
51
+ }, "kms");
52
+ }
53
+ catch (e) {
54
+ if (!(e instanceof ProtocolError))
55
+ throw e;
56
+ throw new KeyError(`${KMS_VARIABLES[e.field]}: ${e.message}`);
57
+ }
58
+ const sessionToken = value("sessionToken");
59
+ if (sessionToken !== undefined && !/^[\x21-\x7E]{1,8192}$/.test(sessionToken)) {
60
+ throw new KeyError(`${KMS_VARIABLES.sessionToken} must be 1 to 8192 printable ASCII characters`);
61
+ }
62
+ return {
63
+ endpoint: kmsEndpoint(value("endpoint"), credentials.region),
64
+ keyId,
65
+ credentials,
66
+ sessionToken,
67
+ };
68
+ }
69
+ /** HTTPS, or plain HTTP to a loopback IP literal only, so credentials never cross a network in the clear. */
70
+ function kmsEndpoint(raw, region) {
71
+ if (raw === undefined)
72
+ return new URL(`https://kms.${region}.amazonaws.com`);
73
+ const url = URL.parse(raw);
74
+ const loopback = url !== null && (/^127(\.\d{1,3}){3}$/.test(url.hostname) || url.hostname === "[::1]");
75
+ if (url === null ||
76
+ url.href !== `${url.origin}/` ||
77
+ !(url.protocol === "https:" || (url.protocol === "http:" && loopback))) {
78
+ throw new KeyError(`${KMS_VARIABLES.endpoint} must be an https origin, or an http origin on a loopback IP address, with no path`);
79
+ }
80
+ return url;
81
+ }
82
+ /**
83
+ * Returns a signer over the KMS key the environment configures, signing the SHA-256 of each part with `Sign`
84
+ * (`DIGEST`). Every failure rejects with a fixed-text `KeyError`, never an unsigned result.
85
+ */
86
+ export function kmsSigner(env, keyId, timeoutMs) {
87
+ const target = kmsTarget(env);
88
+ return {
89
+ keyId,
90
+ async sign(bytes) {
91
+ // Hashed before any await, as the Signer contract lets the caller reuse `bytes` once this settles.
92
+ const digest = createHash("sha256").update(bytes).digest("base64");
93
+ const body = new TextEncoder().encode(JSON.stringify({
94
+ KeyId: target.keyId,
95
+ Message: digest,
96
+ MessageType: "DIGEST",
97
+ SigningAlgorithm: ALGORITHM,
98
+ }));
99
+ const signal = AbortSignal.timeout(timeoutMs);
100
+ let res;
101
+ let text;
102
+ try {
103
+ res = await awsFetch({
104
+ method: "POST",
105
+ url: target.endpoint,
106
+ headers: {
107
+ "content-type": "application/x-amz-json-1.1",
108
+ "x-amz-target": "TrentService.Sign",
109
+ ...(target.sessionToken === undefined
110
+ ? {}
111
+ : { "x-amz-security-token": target.sessionToken }),
112
+ },
113
+ body,
114
+ }, target.credentials, signal);
115
+ text = await readS3Text(res, BODY_LIMIT);
116
+ }
117
+ catch {
118
+ throw new KeyError(signal.aborted
119
+ ? `KMS Sign timed out after ${timeoutMs} ms`
120
+ : "KMS Sign failed: network error");
121
+ }
122
+ if (res.status !== 200)
123
+ throw new KeyError(failure(res, text));
124
+ const signature = replySignature(text);
125
+ if (signature === undefined) {
126
+ throw new KeyError("KMS Sign returned 200 with an invalid reply");
127
+ }
128
+ return signature;
129
+ },
130
+ };
131
+ }
132
+ /** Returns the signature in a 200's JSON body, or undefined when any field is missing or malformed. */
133
+ function replySignature(text) {
134
+ let json;
135
+ try {
136
+ json = JSON.parse(text ?? "");
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ if (typeof json !== "object" || json === null || Array.isArray(json))
142
+ return undefined;
143
+ const reply = json;
144
+ if (reply.SigningAlgorithm !== ALGORITHM || typeof reply.Signature !== "string")
145
+ return undefined;
146
+ return decodeBase64(reply.Signature);
147
+ }
148
+ /** Returns the fixed message for a non-200, naming the error code only when it is allowlisted. */
149
+ function failure(res, text) {
150
+ const what = `KMS Sign failed: ${res.status}`;
151
+ let raw = res.headers.get("x-amzn-errortype") ?? undefined;
152
+ if (raw === undefined || raw === "") {
153
+ try {
154
+ const json = JSON.parse(text ?? "");
155
+ if (typeof json === "object" && json !== null) {
156
+ const { __type: type, code } = json;
157
+ raw = typeof type === "string" ? type : typeof code === "string" ? code : undefined;
158
+ }
159
+ }
160
+ catch {
161
+ // Not a KMS error document.
162
+ }
163
+ }
164
+ // AWS JSON 1.1 sends `Code:<uri>` in the header and `<namespace>#Code` in the body.
165
+ const code = raw?.split(":")[0]?.split("#").at(-1);
166
+ if (code === undefined || code === "")
167
+ return `${what} without a KMS error document`;
168
+ if (ERROR_CODES.has(code))
169
+ return `${what} ${code}`;
170
+ return `${what} with an unrecognised error code`;
171
+ }
package/dist/keys.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import type { Signer } from "@tide-ota/protocol";
2
+ import type { Bucket } from "./bucket.ts";
3
+ import type { ProjectExport } from "./publish-export.ts";
4
+ /** A refusal to sign. Its message names config fields and variables, never a value or a caught error's text. */
5
+ export declare class KeyError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ /** The code-signing metadata a build embeds, holding nothing else. */
9
+ export interface SigningMetadata {
10
+ readonly keyid: string;
11
+ readonly alg?: "rsa-v1_5-sha256";
12
+ }
13
+ /** What the shipped builds trust: their certificate, its verify key and DER SHA-256, and their key ID. */
14
+ export interface Identity {
15
+ readonly key: CryptoKey;
16
+ readonly keyId: string;
17
+ readonly pem: string;
18
+ readonly sha256: string;
19
+ readonly source: string;
20
+ }
21
+ /** A proven signer and the bucket it may write, with the checks a write command repeats before activating. */
22
+ export interface Writer {
23
+ readonly signer: Signer;
24
+ readonly bucket: Bucket;
25
+ /** Whether a `reply/no-update` signed under this identity was present when opened. */
26
+ readonly noUpdate: boolean;
27
+ /** Re-reads `reply/no-update`: true when present and signed under this identity, false when absent. */
28
+ checkNoUpdate(): Promise<boolean>;
29
+ /** Refuses unless the certificate is valid at epoch milliseconds `at`. */
30
+ checkCertificate(at: number): Promise<void>;
31
+ }
32
+ export type Env = Readonly<Record<string, string | undefined>>;
33
+ export declare const BUILD_KEYID = "TIDE_BUILD_KEYID";
34
+ /**
35
+ * Returns a signer proven against the shipped builds' certificate and the bucket it may write; with `app`, refused
36
+ * unless an export carries that same certificate and key ID. Every refusal about the key or identity comes before the
37
+ * bucket is constructed; the bucket check then only reads replies.
38
+ */
39
+ export declare function openWriter(env: Env, options?: {
40
+ readonly kmsTimeoutMs?: number;
41
+ readonly now?: () => number;
42
+ readonly app?: Pick<ProjectExport, "certificate" | "codeSigningMetadata">;
43
+ }): Promise<Writer>;
44
+ /**
45
+ * Returns the shipped builds' identity: `TIDE_BUILD_KEYID` and the certificate in exactly one of
46
+ * `TIDE_BUILD_CERTIFICATE_FILE` and `TIDE_BUILD_CERTIFICATE`, checked against the profile at epoch milliseconds `now`.
47
+ */
48
+ export declare function buildIdentity(env: Env, now: number): Promise<Identity>;
49
+ /** Returns the certificate checked against the code-signing profile at epoch milliseconds `at`. */
50
+ export declare function validCertificate(pem: string, source: string, at: number): Promise<import("@tide-ota/protocol").CodeSigningCertificate>;
51
+ /**
52
+ * Returns `{keyid}` or `{keyid, alg}` from code-signing metadata, a new object holding no other member. `field` names
53
+ * the metadata in each refusal.
54
+ */
55
+ export declare function signingMetadata(metadata: unknown, field: string): SigningMetadata;
56
+ /**
57
+ * Refuses a bucket whose `reply/no-update` is unreadable or signed under another identity: every build the bucket
58
+ * serves gets that one reply, so all of them trust one certificate and key ID. Without one, every pointer must
59
+ * verify instead, so only a new bucket or one of this identity's gets it repaired. Returns whether it exists.
60
+ */
61
+ export declare function checkBucket(bucket: Bucket, identity: Identity): Promise<boolean>;
62
+ /** Returns the file's bytes if it is a regular file of at most 64 KiB, else undefined. */
63
+ export declare function readSmallFile(path: string): Buffer | undefined;
64
+ /** Returns the variable `name`; empty counts as unset for every signing variable. */
65
+ export declare function read(env: Env, name: string): string | undefined;
66
+ /** Returns the own field `name` of a plain object, or undefined. */
67
+ export declare function member(value: unknown, name: string): unknown;
68
+ /** True for a JSON object: not null and not an array. */
69
+ export declare function isObject(value: unknown): value is Readonly<Record<string, unknown>>;
package/dist/keys.js ADDED
@@ -0,0 +1,238 @@
1
+ import { createPrivateKey } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
3
+ import { NO_UPDATE_KEY, ProtocolError, codeSigningCertificate, cryptoKeySigner, expoSignature, verifyExpoSignature, } from "@tide-ota/protocol";
4
+ import { KMS_VARIABLES, kmsSigner } from "./keys-kms.js";
5
+ import { readRecord } from "./status.js";
6
+ import { bucketFromEnv } from "./storage.js";
7
+ /** A refusal to sign. Its message names config fields and variables, never a value or a caught error's text. */
8
+ export class KeyError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "KeyError";
12
+ }
13
+ }
14
+ const FILE_LIMIT = 64 * 1024;
15
+ const PROBE = new TextEncoder().encode("tide signing probe");
16
+ const RSA = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
17
+ const KEY_FILE = "TIDE_SIGNING_KEY_FILE";
18
+ const KEY_PEM = "TIDE_SIGNING_KEY";
19
+ export const BUILD_KEYID = "TIDE_BUILD_KEYID";
20
+ const KEYID = /^[\x20-\x7E]+$/;
21
+ const CERTIFICATE_FILE = "TIDE_BUILD_CERTIFICATE_FILE";
22
+ const CERTIFICATE_PEM = "TIDE_BUILD_CERTIFICATE";
23
+ /**
24
+ * Returns a signer proven against the shipped builds' certificate and the bucket it may write; with `app`, refused
25
+ * unless an export carries that same certificate and key ID. Every refusal about the key or identity comes before the
26
+ * bucket is constructed; the bucket check then only reads replies.
27
+ */
28
+ export async function openWriter(env, options = {}) {
29
+ const { now = Date.now, app } = options;
30
+ const at = now();
31
+ const identity = await buildIdentity(env, at);
32
+ if (app !== undefined)
33
+ await checkApp(app, identity, at);
34
+ const signer = verifying(keySource(env, identity.keyId, options.kmsTimeoutMs ?? 30_000), identity);
35
+ await signer.sign(PROBE);
36
+ const bucket = bucketFromEnv(env);
37
+ return {
38
+ signer,
39
+ bucket,
40
+ noUpdate: await checkBucket(bucket, identity),
41
+ checkNoUpdate: () => checkBucket(bucket, identity),
42
+ checkCertificate: async (at) => {
43
+ await validCertificate(identity.pem, identity.source, at);
44
+ },
45
+ };
46
+ }
47
+ /**
48
+ * Returns the shipped builds' identity: `TIDE_BUILD_KEYID` and the certificate in exactly one of
49
+ * `TIDE_BUILD_CERTIFICATE_FILE` and `TIDE_BUILD_CERTIFICATE`, checked against the profile at epoch milliseconds `now`.
50
+ */
51
+ export async function buildIdentity(env, now) {
52
+ const keyId = read(env, BUILD_KEYID);
53
+ if (keyId === undefined) {
54
+ throw new KeyError(`${BUILD_KEYID} is not set: set it to the keyid the builds embed`);
55
+ }
56
+ if (!KEYID.test(keyId))
57
+ throw new KeyError(`${BUILD_KEYID} must be printable ASCII`);
58
+ const file = read(env, CERTIFICATE_FILE);
59
+ const value = read(env, CERTIFICATE_PEM);
60
+ if ((file === undefined) === (value === undefined)) {
61
+ throw new KeyError(`set exactly one of ${CERTIFICATE_FILE} and ${CERTIFICATE_PEM}`);
62
+ }
63
+ const source = file === undefined ? CERTIFICATE_PEM : CERTIFICATE_FILE;
64
+ // Invalid UTF-8 decodes to U+FFFD, which the certificate's PEM pattern refuses.
65
+ const pem = file === undefined ? value : readSmallFile(file)?.toString("utf8");
66
+ if (pem === undefined) {
67
+ throw new KeyError(`${CERTIFICATE_FILE} unreadable: not a regular file of at most 64 KiB`);
68
+ }
69
+ const { key, sha256 } = await validCertificate(pem, source, now);
70
+ return { key, keyId, pem, sha256, source };
71
+ }
72
+ /** Refuses an export whose certificate or key ID is not the shipped builds'. */
73
+ async function checkApp(app, identity, now) {
74
+ if (app.codeSigningMetadata.keyid !== identity.keyId) {
75
+ throw new KeyError(`tide-export.json codeSigningMetadata.keyid differs from ${BUILD_KEYID}`);
76
+ }
77
+ const { sha256 } = await validCertificate(app.certificate, "tide-export.json certificate", now);
78
+ if (sha256 !== identity.sha256) {
79
+ throw new KeyError(`tide-export.json certificate differs from ${identity.source}`);
80
+ }
81
+ }
82
+ /** Returns the certificate checked against the code-signing profile at epoch milliseconds `at`. */
83
+ export async function validCertificate(pem, source, at) {
84
+ try {
85
+ return await codeSigningCertificate(pem, new Date(at));
86
+ }
87
+ catch (e) {
88
+ if (!(e instanceof ProtocolError))
89
+ throw e;
90
+ throw new KeyError(`${source}: ${e.message}`);
91
+ }
92
+ }
93
+ /**
94
+ * Returns `{keyid}` or `{keyid, alg}` from code-signing metadata, a new object holding no other member. `field` names
95
+ * the metadata in each refusal.
96
+ */
97
+ export function signingMetadata(metadata, field) {
98
+ const keyid = member(metadata, "keyid");
99
+ // Expo would fall back to "root"; an implicit key ID is refused instead.
100
+ if (keyid === undefined)
101
+ throw new KeyError(`${field}.keyid is missing`);
102
+ if (typeof keyid !== "string" || !KEYID.test(keyid)) {
103
+ throw new KeyError(`${field}.keyid must be printable ASCII`);
104
+ }
105
+ const alg = member(metadata, "alg");
106
+ if (alg === undefined)
107
+ return { keyid };
108
+ if (alg !== "rsa-v1_5-sha256")
109
+ throw new KeyError(`${field}.alg must be rsa-v1_5-sha256`);
110
+ return { keyid, alg };
111
+ }
112
+ /** Returns the signer for the one configured key source. */
113
+ function keySource(env, keyId, kmsTimeoutMs) {
114
+ const file = read(env, KEY_FILE);
115
+ const pem = read(env, KEY_PEM);
116
+ const kms = Object.values(KMS_VARIABLES).filter((name) => read(env, name) !== undefined);
117
+ const sources = [file !== undefined, pem !== undefined, kms.length > 0].filter(Boolean).length;
118
+ if (sources === 0) {
119
+ throw new KeyError(`no signing key: set ${KEY_FILE}, ${KEY_PEM} or ${KMS_VARIABLES.keyId}`);
120
+ }
121
+ if (sources > 1) {
122
+ const named = [file && KEY_FILE, pem && KEY_PEM, ...kms].filter(Boolean);
123
+ throw new KeyError(`more than one signing key: ${named.join(", ")} are set; set one source`);
124
+ }
125
+ if (file !== undefined) {
126
+ const bytes = readSmallFile(file);
127
+ if (bytes === undefined) {
128
+ throw new KeyError(`${KEY_FILE} unreadable: not a regular file of at most 64 KiB`);
129
+ }
130
+ return pemSigner(bytes, KEY_FILE, keyId);
131
+ }
132
+ if (pem !== undefined)
133
+ return pemSigner(pem, KEY_PEM, keyId);
134
+ return kmsSigner(env, keyId, kmsTimeoutMs);
135
+ }
136
+ /** Returns a signer over an unencrypted PKCS#8 or PKCS#1 RSA private key of 2048 to 4096 bits. */
137
+ function pemSigner(pem, source, keyId) {
138
+ // Read from the PEM itself: OpenSSL reports a missing passphrase as a cancelled prompt.
139
+ if (/-----BEGIN ENCRYPTED |^Proc-Type: *4,ENCRYPTED/m.test(pem.toString())) {
140
+ throw new KeyError(`${source} holds an encrypted key: Tide needs it unencrypted`);
141
+ }
142
+ let key;
143
+ try {
144
+ // An empty passphrase, so OpenSSL never prompts on the terminal.
145
+ key = createPrivateKey({ key: pem, format: "pem", passphrase: "" });
146
+ }
147
+ catch {
148
+ // The caught error is dropped: OpenSSL's text can quote the input.
149
+ throw new KeyError(`${source} is not a PEM private key`);
150
+ }
151
+ if (key.asymmetricKeyType !== "rsa") {
152
+ throw new KeyError(`${source} holds a key of type ${key.asymmetricKeyType}: Tide signs with RSA`);
153
+ }
154
+ const bits = key.asymmetricKeyDetails?.modulusLength ?? 0;
155
+ if (bits < 2048 || bits > 4096) {
156
+ throw new KeyError(`${source} must hold an RSA key of 2048 to 4096 bits`);
157
+ }
158
+ return cryptoKeySigner(key.toCryptoKey(RSA, false, ["sign"]), keyId);
159
+ }
160
+ /** Wraps `inner` so no signature resolves unless it verifies under the builds' certificate and key ID. */
161
+ function verifying(inner, { key, keyId }) {
162
+ return {
163
+ keyId,
164
+ async sign(bytes) {
165
+ const sig = await inner.sign(bytes);
166
+ try {
167
+ const header = await expoSignature(bytes, { keyId, sign: () => Promise.resolve(sig) });
168
+ await verifyExpoSignature(bytes, header, key, keyId);
169
+ }
170
+ catch {
171
+ throw new KeyError("the signing key does not match the app's code-signing certificate");
172
+ }
173
+ return sig;
174
+ },
175
+ };
176
+ }
177
+ /**
178
+ * Refuses a bucket whose `reply/no-update` is unreadable or signed under another identity: every build the bucket
179
+ * serves gets that one reply, so all of them trust one certificate and key ID. Without one, every pointer must
180
+ * verify instead, so only a new bucket or one of this identity's gets it repaired. Returns whether it exists.
181
+ */
182
+ export async function checkBucket(bucket, identity) {
183
+ const record = await readRecord(bucket, NO_UPDATE_KEY);
184
+ if (record !== undefined) {
185
+ await checkSigned(NO_UPDATE_KEY, record, identity);
186
+ return true;
187
+ }
188
+ for (const entry of await bucket.list("reply/")) {
189
+ if (!("key" in entry))
190
+ throw new KeyError("reply/ is unreadable: an object name outside the key grammar");
191
+ await checkSigned(entry.key, (await readRecord(bucket, entry.key)) ?? "absent when read", identity);
192
+ }
193
+ return false;
194
+ }
195
+ /** Refuses a record that is unreadable or whose signed part does not verify under `identity`. */
196
+ async function checkSigned(key, record, { key: verifyKey, keyId }) {
197
+ if (typeof record === "string")
198
+ throw new KeyError(`${key} is unreadable: ${record}`);
199
+ try {
200
+ await verifyExpoSignature(record.signed.body, record.signed.signature, verifyKey, keyId);
201
+ }
202
+ catch {
203
+ throw new KeyError("this bucket's replies are signed by a different certificate or key ID: a new signing identity needs a new bucket");
204
+ }
205
+ }
206
+ /** Returns the file's bytes if it is a regular file of at most 64 KiB, else undefined. */
207
+ export function readSmallFile(path) {
208
+ let fd;
209
+ try {
210
+ // Non-blocking, so a FIFO cannot hang the open.
211
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
212
+ }
213
+ catch {
214
+ return undefined;
215
+ }
216
+ try {
217
+ const stat = fstatSync(fd);
218
+ return stat.isFile() && stat.size <= FILE_LIMIT ? readFileSync(fd) : undefined;
219
+ }
220
+ catch {
221
+ return undefined;
222
+ }
223
+ finally {
224
+ closeSync(fd);
225
+ }
226
+ }
227
+ /** Returns the variable `name`; empty counts as unset for every signing variable. */
228
+ export function read(env, name) {
229
+ return env[name] === "" ? undefined : env[name];
230
+ }
231
+ /** Returns the own field `name` of a plain object, or undefined. */
232
+ export function member(value, name) {
233
+ return isObject(value) && Object.hasOwn(value, name) ? value[name] : undefined;
234
+ }
235
+ /** True for a JSON object: not null and not an array. */
236
+ export function isObject(value) {
237
+ return typeof value === "object" && value !== null && !Array.isArray(value);
238
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/main.js ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ import { BucketError } from "./bucket.js";
3
+ import { EXPORT_USAGE, exportProject } from "./export.js";
4
+ import { PROBE_USAGE, probe } from "./probe.js";
5
+ import { REPUBLISH_USAGE, ROLLBACK_USAGE, republish, rollback } from "./publish-rollback.js";
6
+ import { PUBLISH_USAGE, publish } from "./publish.js";
7
+ import { REGISTER_BUILD_USAGE, registerBuild } from "./register-build.js";
8
+ import { status } from "./status.js";
9
+ import { storage } from "./storage-report.js";
10
+ import { bucketFromEnv } from "./storage.js";
11
+ const USAGE = `usage: tide status\nusage: tide storage\n${EXPORT_USAGE}\n${PUBLISH_USAGE}\n${ROLLBACK_USAGE}\n${REPUBLISH_USAGE}\n${REGISTER_BUILD_USAGE}\n${PROBE_USAGE}`;
12
+ // Commands that parse arguments and read their own configuration.
13
+ const COMMANDS = {
14
+ export: exportProject,
15
+ publish,
16
+ rollback,
17
+ republish,
18
+ "register-build": registerBuild,
19
+ probe,
20
+ };
21
+ const READERS = { status, storage };
22
+ /** Runs one command; each command documents its exit codes, and 2 is always a usage error. */
23
+ async function main(args, env) {
24
+ const command = args[0];
25
+ if (command !== undefined && Object.hasOwn(COMMANDS, command)) {
26
+ return await COMMANDS[command](args.slice(1), env, {
27
+ out: (line) => process.stdout.write(`${line}\n`),
28
+ err: (line) => process.stderr.write(`${line}\n`),
29
+ });
30
+ }
31
+ if (args.length !== 1 || command === undefined || !Object.hasOwn(READERS, command)) {
32
+ console.error(USAGE);
33
+ return 2;
34
+ }
35
+ let bucket;
36
+ try {
37
+ bucket = bucketFromEnv(env);
38
+ }
39
+ catch (e) {
40
+ // Configuration messages name variables and rules, never values; nothing has been sent.
41
+ console.error(`tide: ${e.message}`);
42
+ return 2;
43
+ }
44
+ try {
45
+ return await READERS[command](bucket, (line) => process.stdout.write(`${line}\n`), (line) => process.stderr.write(`${line}\n`));
46
+ }
47
+ catch (e) {
48
+ if (!(e instanceof BucketError))
49
+ throw e;
50
+ console.error(`tide: ${e.message}`);
51
+ return 2;
52
+ }
53
+ }
54
+ process.exitCode = await main(process.argv.slice(2), process.env);
@@ -0,0 +1,20 @@
1
+ import type { Bucket } from "./bucket.ts";
2
+ /** A pointer as read before composing: the ETag its write must match and its time, both absent for none. */
3
+ export interface PointerState {
4
+ readonly etag?: string;
5
+ readonly time?: number;
6
+ }
7
+ /** Reads the pointer at `key`, refusing one a signing client could not receive. */
8
+ export declare function readPointer(bucket: Bucket, key: string): Promise<PointerState>;
9
+ /** Returns a time a client accepts as newer than the pointer it replaces, whatever the local clock says. */
10
+ export declare function createdAtFloor(local: number, previous: PointerState): number;
11
+ /**
12
+ * Runs one write to `key`, naming the key in a bucket failure. An unknown outcome may have committed, so the message
13
+ * says so with `unknown`, the reader's next step.
14
+ */
15
+ export declare function writing<T>(key: string, write: () => Promise<T>, unknown?: string): Promise<T>;
16
+ /**
17
+ * Writes the pointer only over the ETag that was read, or only if still absent. A lost race fails at once and
18
+ * leaves the other writer's reply; an unknown outcome may already be live.
19
+ */
20
+ export declare function writePointer(bucket: Bucket, key: string, bytes: Uint8Array<ArrayBuffer>, previous: PointerState): Promise<void>;
@@ -0,0 +1,47 @@
1
+ import { MAX_REPLY_BYTES } from "@tide-ota/protocol";
2
+ import { BucketError } from "./bucket.js";
3
+ import { PublishError } from "./publish-record.js";
4
+ import { checkRecord } from "./status.js";
5
+ /** Reads the pointer at `key`, refusing one a signing client could not receive. */
6
+ export async function readPointer(bucket, key) {
7
+ const object = await bucket.get(key, MAX_REPLY_BYTES);
8
+ if (object === undefined)
9
+ return {};
10
+ const verdict = checkRecord(key, object.bytes);
11
+ if (typeof verdict === "string")
12
+ throw new PublishError(`${key} is unreadable: ${verdict}`);
13
+ if (verdict.time === undefined)
14
+ throw new PublishError(`${key} is unreadable: it has no time`);
15
+ return { etag: object.etag, time: Date.parse(verdict.time) };
16
+ }
17
+ /** Returns a time a client accepts as newer than the pointer it replaces, whatever the local clock says. */
18
+ export function createdAtFloor(local, previous) {
19
+ return previous.time === undefined ? local : Math.max(local, previous.time + 1);
20
+ }
21
+ /**
22
+ * Runs one write to `key`, naming the key in a bucket failure. An unknown outcome may have committed, so the message
23
+ * says so with `unknown`, the reader's next step.
24
+ */
25
+ export async function writing(key, write, unknown = "check with tide status") {
26
+ try {
27
+ return await write();
28
+ }
29
+ catch (e) {
30
+ if (!(e instanceof BucketError))
31
+ throw e;
32
+ const hint = e.outcome === "unknown" ? `; outcome unknown; ${unknown}` : "";
33
+ throw new PublishError(`${key}: ${e.message}${hint}`);
34
+ }
35
+ }
36
+ /**
37
+ * Writes the pointer only over the ETag that was read, or only if still absent. A lost race fails at once and
38
+ * leaves the other writer's reply; an unknown outcome may already be live.
39
+ */
40
+ export async function writePointer(bucket, key, bytes, previous) {
41
+ const etag = await writing(key, () => previous.etag === undefined
42
+ ? bucket.putIfAbsent(key, bytes)
43
+ : bucket.putIfMatch(key, bytes, previous.etag));
44
+ if (etag === undefined) {
45
+ throw new PublishError(`${key} was changed by another writer since it was read; it keeps theirs`);
46
+ }
47
+ }
@@ -0,0 +1,23 @@
1
+ import type { Env } from "./keys.ts";
2
+ /** Exit codes by failure class; 1 is left to Node's exit on an uncaught error, so it always means a bug. */
3
+ export declare const PROBE_EXIT: {
4
+ readonly usage: 2;
5
+ readonly unreachable: 3;
6
+ readonly status: 4;
7
+ readonly unparseable: 5;
8
+ readonly signature: 6;
9
+ readonly bundleMissing: 7;
10
+ readonly bundleHash: 8;
11
+ readonly mismatch: 9;
12
+ };
13
+ export declare const PROBE_USAGE = "usage: tide probe --server-url <url> --channel <name> --runtime-version <version> --platform ios|android [--app-id <id>]";
14
+ /**
15
+ * Fetches `/manifest` as a stock client would and verifies the signed part against the pinned certificate and keyid,
16
+ * then a manifest's launch asset against its hash. Returns 0 or the `PROBE_EXIT` code of the first failure.
17
+ */
18
+ export declare function probe(args: readonly string[], env: Env, io: {
19
+ readonly out: (line: string) => void;
20
+ readonly err: (line: string) => void;
21
+ }, options?: {
22
+ readonly timeoutMs?: number;
23
+ }): Promise<number>;