@instahost/cli 0.0.0-stage → 0.1.2

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,255 @@
1
+ // A verbatim copy of the path rules the InstaHost API enforces on the server. Do not edit it
2
+ // here: changes start in the service, whose tests fail when this copy differs from its source.
3
+
4
+ // Path rules shared by the InstaHost API and the CLI: path normalisation, invisible and
5
+ // control characters, sensitive file names and the directory-walk exclusions.
6
+ //
7
+ // This file must stay self-contained and runtime-neutral (no imports, no Node or Workers
8
+ // APIs). The CLI ships a verbatim copy, with a header naming where it came from, and the
9
+ // service's tests fail if that copy drifts from the rules the API enforces.
10
+ //
11
+ // Paths are only ever D1 lookup keys. They never become part of an R2 key or a filesystem
12
+ // path, so these rules exist for clarity and anti-spoofing, not to prevent traversal.
13
+
14
+ export const MAX_PATH_BYTES = 512;
15
+ export const MAX_SEGMENT_BYTES = 255;
16
+
17
+ export type PathProblem =
18
+ | "empty"
19
+ | "ill_formed_unicode"
20
+ | "too_long"
21
+ | "not_nfc"
22
+ | "control_character"
23
+ | "line_separator"
24
+ | "invisible_character"
25
+ | "backslash"
26
+ | "leading_slash"
27
+ | "trailing_slash"
28
+ | "empty_segment"
29
+ | "dot_segment"
30
+ | "segment_too_long";
31
+
32
+ export type PathCheck = { ok: true } | { ok: false; reason: PathProblem };
33
+
34
+ /** UTF-8 length in bytes. Lone surrogates count as 3 bytes (they encode as U+FFFD). */
35
+ export function utf8ByteLength(s: string): number {
36
+ let bytes = 0;
37
+ for (let i = 0; i < s.length; i++) {
38
+ const c = s.charCodeAt(i);
39
+ if (c < 0x80) bytes += 1;
40
+ else if (c < 0x800) bytes += 2;
41
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
42
+ const d = s.charCodeAt(i + 1);
43
+ if (d >= 0xdc00 && d <= 0xdfff) {
44
+ bytes += 4;
45
+ i++;
46
+ } else bytes += 3;
47
+ } else bytes += 3;
48
+ }
49
+ return bytes;
50
+ }
51
+
52
+ // C0 controls, DEL and C1 controls.
53
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/u;
54
+ // Line and paragraph separators.
55
+ const LINE_SEPARATOR = /[\u2028\u2029]/u;
56
+ // Invisible by definition: Unicode format characters (Cf: bidi controls, zero-width space, soft
57
+ // hyphen, word joiner, BOM, tag characters, ...) and default-ignorable code points (Hangul fillers,
58
+ // combining grapheme joiner, variation selectors, unassigned ignorables, ...).
59
+ const INVISIBLE = /[\p{Cf}\p{Default_Ignorable_Code_Point}]/u;
60
+ const ZWNJ = 0x200c;
61
+ const ZWJ = 0x200d;
62
+ const VS15 = 0xfe0e;
63
+ const VS16 = 0xfe0f;
64
+ const KEYCAP = 0x20e3;
65
+ const JOINER_NEIGHBOUR = /[\p{L}\p{M}\p{Extended_Pictographic}\p{Emoji_Modifier}]/u;
66
+ const EMOJI = /\p{Emoji}/u;
67
+ const LETTER_OR_SYMBOL = /[\p{L}\p{S}]/u;
68
+
69
+ const isVariationSelector = (c: number) => (c >= 0xfe00 && c <= 0xfe0f) || (c >= 0xe0100 && c <= 0xe01ef);
70
+ const isVisible = (c: number | undefined): c is number => c !== undefined && !INVISIBLE.test(String.fromCodePoint(c)) && !CONTROL.test(String.fromCodePoint(c));
71
+ const isAsciiKeycapBase = (c: number) => (c >= 0x30 && c <= 0x39) || c === 0x23 || c === 0x2a;
72
+
73
+ /**
74
+ * True when the path contains an invisible character outside the few contexts where text needs
75
+ * one. ZWNJ/ZWJ (emoji sequences, Persian and Indic scripts) are allowed only between two visible
76
+ * non-ASCII letters, marks or emoji (VS16 may precede a ZWJ, as in heart-on-fire); so
77
+ * "index" + ZWJ + ".html" or runs of joiners are rejected. VS15/VS16 are allowed only after an
78
+ * emoji, or in an ASCII keycap (digit, # or * + VS16 + U+20E3). Other variation selectors
79
+ * (standardised and ideographic variants) are allowed only after a visible non-ASCII letter or
80
+ * symbol. Everything else in INVISIBLE is rejected.
81
+ */
82
+ function hasInvisibleCharacter(path: string): boolean {
83
+ if (!INVISIBLE.test(path)) return false;
84
+ const cps = Array.from(path, (ch) => ch.codePointAt(0) as number);
85
+ for (let i = 0; i < cps.length; i++) {
86
+ const c = cps[i] as number;
87
+ if (!INVISIBLE.test(String.fromCodePoint(c))) continue;
88
+ const prev = cps[i - 1];
89
+ const next = cps[i + 1];
90
+ if (c === ZWNJ || c === ZWJ) {
91
+ const prevOk = prev === VS16 || (isVisible(prev) && prev > 0x7f && JOINER_NEIGHBOUR.test(String.fromCodePoint(prev)));
92
+ const nextOk = isVisible(next) && next > 0x7f && JOINER_NEIGHBOUR.test(String.fromCodePoint(next));
93
+ if (prevOk && nextOk) continue;
94
+ return true;
95
+ }
96
+ if (isVariationSelector(c) && isVisible(prev)) {
97
+ if (c === VS15 || c === VS16) {
98
+ if (prev > 0x7f ? EMOJI.test(String.fromCodePoint(prev)) : isAsciiKeycapBase(prev) && c === VS16 && next === KEYCAP) continue;
99
+ } else if (prev > 0x7f && LETTER_OR_SYMBOL.test(String.fromCodePoint(prev))) continue;
100
+ }
101
+ return true;
102
+ }
103
+ return false;
104
+ }
105
+
106
+ /**
107
+ * Validates a relative path as stored in a manifest. Accepts only well-formed NFC strings of
108
+ * 1 to 512 UTF-8 bytes with `/` separators, no leading or trailing `/`, no empty, `.` or `..`
109
+ * segment, segments of at most 255 bytes, no backslash, no control or line-separator character,
110
+ * and no invisible character outside the contexts hasInvisibleCharacter allows. The server
111
+ * rejects non-NFC input; the CLI normalises first.
112
+ */
113
+ export function validatePath(path: string): PathCheck {
114
+ if (typeof path !== "string" || path.length === 0) return { ok: false, reason: "empty" };
115
+ // Every UTF-16 code unit is at least one UTF-8 byte: reject huge inputs before scanning them.
116
+ if (path.length > MAX_PATH_BYTES) return { ok: false, reason: "too_long" };
117
+ if (!path.isWellFormed()) return { ok: false, reason: "ill_formed_unicode" };
118
+ if (utf8ByteLength(path) > MAX_PATH_BYTES) return { ok: false, reason: "too_long" };
119
+ if (path.normalize("NFC") !== path) return { ok: false, reason: "not_nfc" };
120
+ if (CONTROL.test(path)) return { ok: false, reason: "control_character" };
121
+ if (LINE_SEPARATOR.test(path)) return { ok: false, reason: "line_separator" };
122
+ if (hasInvisibleCharacter(path)) return { ok: false, reason: "invisible_character" };
123
+ if (path.includes("\\")) return { ok: false, reason: "backslash" };
124
+ if (path.startsWith("/")) return { ok: false, reason: "leading_slash" };
125
+ if (path.endsWith("/")) return { ok: false, reason: "trailing_slash" };
126
+ for (const segment of path.split("/")) {
127
+ if (segment === "") return { ok: false, reason: "empty_segment" };
128
+ if (segment === "." || segment === "..") return { ok: false, reason: "dot_segment" };
129
+ if (utf8ByteLength(segment) > MAX_SEGMENT_BYTES) return { ok: false, reason: "segment_too_long" };
130
+ }
131
+ return { ok: true };
132
+ }
133
+
134
+ // Sensitive names, matched case-insensitively.
135
+ const SENSITIVE_DIRECTORIES = new Set([".git", ".svn", ".hg", ".ssh", ".aws", ".gnupg", ".kube", ".docker"]);
136
+ const SENSITIVE_BASENAMES = new Set([
137
+ ".env",
138
+ ".envrc", // direnv: exported secrets
139
+ ".dev.vars",
140
+ ".npmrc",
141
+ ".netrc",
142
+ ".pypirc",
143
+ ".htpasswd",
144
+ ".git-credentials",
145
+ ".pgpass",
146
+ "_netrc", // the name curl and git read on Windows
147
+ "id_rsa",
148
+ "id_dsa",
149
+ "id_ecdsa",
150
+ "id_ed25519",
151
+ "id_ecdsa_sk", // OpenSSH FIDO keys (ssh-keygen -t ecdsa-sk / ed25519-sk)
152
+ "id_ed25519_sk",
153
+ ]);
154
+ const SENSITIVE_BASENAME_PREFIXES = [".env.", ".dev.vars."];
155
+ // Terraform also writes terraform.tfstate.backup and accepts *.tfvars.json; both carry the
156
+ // same secrets as *.tfstate and *.tfvars.
157
+ const SENSITIVE_SUFFIXES = [
158
+ ".pem",
159
+ ".key",
160
+ ".p12",
161
+ ".pfx",
162
+ ".jks",
163
+ ".keystore",
164
+ ".ppk",
165
+ ".tfstate",
166
+ ".tfstate.backup",
167
+ ".tfvars",
168
+ ".tfvars.json",
169
+ ];
170
+
171
+ // Editor and manual backup copies of a listed file are as sensitive as the file itself.
172
+ const BACKUP_SUFFIXES = ["~", ".bak", ".old", ".orig"];
173
+
174
+ /** The basename plus its backup-stripped forms ("id_rsa.bak" -> "id_rsa", "#.env#" -> ".env"). */
175
+ function basenameForms(base: string): string[] {
176
+ const forms = [base];
177
+ if (base.length > 2 && base.startsWith("#") && base.endsWith("#")) forms.push(base.slice(1, -1));
178
+ for (const suffix of BACKUP_SUFFIXES) {
179
+ if (base.endsWith(suffix) && base.length > suffix.length) forms.push(base.slice(0, -suffix.length));
180
+ }
181
+ return forms;
182
+ }
183
+
184
+ /**
185
+ * Returns the rule a path breaks if it looks like a credential or VCS metadata, else null.
186
+ * Name-based only: there is no content scanning.
187
+ */
188
+ export function sensitiveRule(path: string): string | null {
189
+ const segments = path.toLowerCase().split("/");
190
+ for (const segment of segments.slice(0, -1)) {
191
+ if (SENSITIVE_DIRECTORIES.has(segment)) return `directory ${segment}`;
192
+ }
193
+ const last = segments[segments.length - 1] ?? "";
194
+ if (SENSITIVE_DIRECTORIES.has(last)) return `directory ${last}`;
195
+ for (const base of basenameForms(last)) {
196
+ if (SENSITIVE_BASENAMES.has(base)) return `file ${base}`;
197
+ for (const prefix of SENSITIVE_BASENAME_PREFIXES) if (base.startsWith(prefix)) return `file ${prefix}*`;
198
+ for (const suffix of SENSITIVE_SUFFIXES) if (base.endsWith(suffix)) return `extension ${suffix}`;
199
+ }
200
+ return null;
201
+ }
202
+
203
+ export function isSensitivePath(path: string): boolean {
204
+ return sensitiveRule(path) !== null;
205
+ }
206
+
207
+ // Directory-walk exclusions for the CLI: .DS_Store, Thumbs.db, Windows desktop.ini, the macOS
208
+ // custom-icon file "Icon\r" (its name fails validatePath, so it would otherwise abort a publish),
209
+ // AppleDouble "._*" files and the __MACOSX folder (they carry extended attributes such as
210
+ // quarantine data and download URLs).
211
+ const OS_METADATA_BASENAMES = new Set([".ds_store", "thumbs.db", "desktop.ini", `icon${String.fromCharCode(13)}`]);
212
+ const DOTFILE_ALLOWED_SEGMENTS = new Set([".well-known"]);
213
+
214
+ export type WalkExclusion = "sensitive" | "os_metadata" | "dotfile";
215
+
216
+ /**
217
+ * Why `publish` leaves a walked path out, or null to include it. Sensitive paths and OS
218
+ * metadata are always excluded; dot-prefixed segments are excluded unless includeDotfiles,
219
+ * except `.well-known`.
220
+ */
221
+ export function walkExclusion(path: string, includeDotfiles = false): WalkExclusion | null {
222
+ if (isSensitivePath(path)) return "sensitive";
223
+ const segments = path.split("/");
224
+ const base = (segments[segments.length - 1] ?? "").toLowerCase();
225
+ if (OS_METADATA_BASENAMES.has(base) || base.startsWith("._") || segments.includes("__MACOSX")) return "os_metadata";
226
+ if (!includeDotfiles) {
227
+ for (const segment of segments) {
228
+ if (segment.startsWith(".") && !DOTFILE_ALLOWED_SEGMENTS.has(segment.toLowerCase())) return "dotfile";
229
+ }
230
+ }
231
+ return null;
232
+ }
233
+
234
+ export interface DuplicatePath {
235
+ path: string;
236
+ /** The earlier path it collides with (equal after NFC normalisation). */
237
+ duplicateOf: string;
238
+ }
239
+
240
+ /**
241
+ * Paths that collide with an earlier one after NFC normalisation, in input order. On the server,
242
+ * where validatePath already requires NFC, these are exact duplicates; in the CLI walk they also
243
+ * catch two on-disk names (NFC and NFD) that would become the same manifest path.
244
+ */
245
+ export function findDuplicatePaths(paths: readonly string[]): DuplicatePath[] {
246
+ const seen = new Map<string, string>();
247
+ const duplicates: DuplicatePath[] = [];
248
+ for (const path of paths) {
249
+ const key = path.normalize("NFC");
250
+ const first = seen.get(key);
251
+ if (first === undefined) seen.set(key, path);
252
+ else duplicates.push({ path, duplicateOf: first });
253
+ }
254
+ return duplicates;
255
+ }