@amritk/nish-x86_64-linux 0.38.0 → 0.40.1

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.
Files changed (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
package/std/release.ts ADDED
@@ -0,0 +1,593 @@
1
+ /**
2
+ * `nish/release` — what the newest release of a project on GitHub is, whether
3
+ * it is newer than the one running, and a small cache so a program asks at
4
+ * most once a day.
5
+ *
6
+ * import { releaseCheckCached, releaseLatest } from "nish/release"
7
+ *
8
+ * const latest: string | null = releaseLatest("https://github.com/owner/repo", 2000)
9
+ * const newer: string | null = releaseCheckCached(
10
+ * "https://github.com/owner/repo", "1.2.0", "/home/me/.cache/app/latest", 86400000, 2000)
11
+ *
12
+ * - `releaseValidVersion(v)` — whether `v` is a version that may go in a URL:
13
+ * it starts with a digit and holds only letters, digits, `.`, `-` and `+`,
14
+ * with no `..`. The same rule as `install.sh`'s `nish_valid_version`.
15
+ * - `releaseParseVersion(v)` and `releaseCompare(a, b)` — semantic versions,
16
+ * `major.minor.patch[-pre][+build]`. A prerelease sorts below its release
17
+ * and build metadata is ignored.
18
+ * - `releaseIsNewer(candidate, current)` — true only when both parse and the
19
+ * candidate is strictly newer, so a version that does not parse is never
20
+ * newer and nothing here ever proposes a downgrade.
21
+ * - `releaseTagFromLocation(base, location)` — the version a
22
+ * `/releases/latest` redirect names, or null for anything that is not
23
+ * exactly `<base>/releases/tag/v<version>`.
24
+ * - `releaseLatest(base, timeoutMs)` — asks `<base>/releases/latest` once,
25
+ * without following the redirect, and answers its version or null. Every
26
+ * failure is null: a server that is down, slow, refuses, or answers
27
+ * anything but a redirect to a release tag.
28
+ * - `releaseCacheRead`, `releaseCacheWrite` and `releaseCheckCached` — the
29
+ * answer kept in a file the program names, believed only when it is a
30
+ * regular file this user owns that no one else can write, and only for
31
+ * `maxAgeMs` (a check dated in the future counts as stale).
32
+ * - `releaseFetchInstaller(rawBase, version, path, timeoutMs)` — the `install.sh` of one
33
+ * release tag, written to a file for the caller to run, never piped into a
34
+ * shell.
35
+ *
36
+ * Nothing here runs under a wasm32 build: it reaches the network and reads file
37
+ * owners. The record of what it defends against is `docs/security/release.md`.
38
+ */
39
+ import { FetchSyncClient, HttpOptions, HttpRequest, HttpResponse } from "./net/fetch"
40
+ import { split } from "./text"
41
+
42
+ /**
43
+ * A parsed semantic version. `pre` is the prerelease after the `-`, empty for a
44
+ * release; build metadata after the `+` is dropped, as it never orders.
45
+ */
46
+ export class ReleaseVersion {
47
+ /** The major number. */
48
+ major: i64 = 0
49
+ /** The minor number. */
50
+ minor: i64 = 0
51
+ /** The patch number. */
52
+ patch: i64 = 0
53
+ /** The prerelease identifiers, dot-separated, or "" for a release. */
54
+ pre: string = ""
55
+ }
56
+
57
+ /**
58
+ * The cache's contents: when the check ran and what it found.
59
+ */
60
+ export class ReleaseCache {
61
+ /** When the check ran, in milliseconds since 1970 (`Date.now()`'s clock). */
62
+ checkedMs: i64 = 0
63
+ /** The version the check found, or "" when it found none. */
64
+ latest: string = ""
65
+ }
66
+
67
+ /**
68
+ * Whether `v` may be put in a URL as a release version: not empty, starting
69
+ * with a digit, holding only ASCII letters, digits, `.`, `-` and `+`, and
70
+ * never `..`. What it rules out is a version that reaches past the tag in a
71
+ * path — a `/`, a `..`, a `?`, a `#`, a `%`, whitespace.
72
+ *
73
+ * @param v The version, without a leading `v`.
74
+ * @returns True when the version is safe to put in a release URL.
75
+ */
76
+ export const releaseValidVersion = (v: string): boolean => {
77
+ const n: i32 = toI32(v.length)
78
+ if (n === 0 || n > 64) {
79
+ return false
80
+ }
81
+ const first: i32 = toI32(v.charCodeAt(0))
82
+ if (first < 48 || first > 57) {
83
+ return false
84
+ }
85
+ if (v.indexOf("..") >= 0) {
86
+ return false
87
+ }
88
+ for (let i: i32 = 0; i < n; i++) {
89
+ const c: i32 = toI32(v.charCodeAt(i))
90
+ const digit: boolean = c >= 48 && c <= 57
91
+ const letter: boolean = (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
92
+ if (!digit && !letter && c !== 46 && c !== 45 && c !== 43) {
93
+ return false
94
+ }
95
+ }
96
+ return true
97
+ }
98
+
99
+ /** A run of ASCII digits as a number, or -1 when it is empty, too long, has a leading zero or holds anything else. */
100
+ const releaseNumber = (s: string): i64 => {
101
+ const n: i32 = toI32(s.length)
102
+ if (n === 0 || n > 15 || (n > 1 && s.charCodeAt(0) === 48)) {
103
+ return -1
104
+ }
105
+ let value: i64 = 0
106
+ for (let i: i32 = 0; i < n; i++) {
107
+ const c: i32 = toI32(s.charCodeAt(i))
108
+ if (c < 48 || c > 57) {
109
+ return -1
110
+ }
111
+ value = value * 10 + toI64(c - 48)
112
+ }
113
+ return value
114
+ }
115
+
116
+ /**
117
+ * Whether every dot-separated identifier of a prerelease or build is non-empty
118
+ * and alphanumeric or `-`; in a prerelease (`pre`) one of digits alone has no
119
+ * leading zero.
120
+ */
121
+ const releasePreWellFormed = (text: string, pre: boolean): boolean => {
122
+ const parts: string[] = split(text, ".")
123
+ for (const part of parts) {
124
+ if (part.length === 0) {
125
+ return false
126
+ }
127
+ let digits: boolean = true
128
+ for (let i: i32 = 0; i < toI32(part.length); i++) {
129
+ const c: i32 = toI32(part.charCodeAt(i))
130
+ const digit: boolean = c >= 48 && c <= 57
131
+ const ok: boolean = digit || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 45
132
+ if (!ok) {
133
+ return false
134
+ }
135
+ digits = digits && digit
136
+ }
137
+ if (pre && digits && part.length > 1 && part.charCodeAt(0) === 48) {
138
+ return false
139
+ }
140
+ }
141
+ return true
142
+ }
143
+
144
+ /**
145
+ * `v` as a semantic version, `major.minor.patch` with an optional `-pre` and
146
+ * `+build`, or null when it is not one. A leading `v` is not accepted; strip
147
+ * it first.
148
+ *
149
+ * @param v The version text.
150
+ * @returns The parsed version, or null.
151
+ */
152
+ export const releaseParseVersion = (v: string): ReleaseVersion | null => {
153
+ if (!releaseValidVersion(v)) {
154
+ return null
155
+ }
156
+ let core: string = v
157
+ const plus: i32 = toI32(core.indexOf("+"))
158
+ if (plus >= 0) {
159
+ if (plus + 1 === toI32(core.length) || !releasePreWellFormed(core.slice(plus + 1), false)) {
160
+ return null
161
+ }
162
+ core = core.slice(0, plus)
163
+ }
164
+ let pre: string = ""
165
+ const dash: i32 = toI32(core.indexOf("-"))
166
+ if (dash >= 0) {
167
+ pre = core.slice(dash + 1)
168
+ core = core.slice(0, dash)
169
+ if (!releasePreWellFormed(pre, true)) {
170
+ return null
171
+ }
172
+ }
173
+ const nums: string[] = split(core, ".")
174
+ if (nums.length !== 3) {
175
+ return null
176
+ }
177
+ const out: ReleaseVersion = new ReleaseVersion()
178
+ out.major = releaseNumber(nums[0])
179
+ out.minor = releaseNumber(nums[1])
180
+ out.patch = releaseNumber(nums[2])
181
+ if (out.major < 0 || out.minor < 0 || out.patch < 0) {
182
+ return null
183
+ }
184
+ out.pre = pre
185
+ return out
186
+ }
187
+
188
+ /** -1, 0 or 1 as `a` is below, equal to or above `b`. */
189
+ const releaseSign = (a: i64, b: i64): i32 => {
190
+ if (a < b) {
191
+ return -1
192
+ }
193
+ return a > b ? 1 : 0
194
+ }
195
+
196
+ /** Whether `s` is a non-empty run of ASCII digits, however long. */
197
+ const releaseAllDigits = (s: string): boolean => {
198
+ const n: i32 = toI32(s.length)
199
+ if (n === 0) {
200
+ return false
201
+ }
202
+ for (let i: i32 = 0; i < n; i++) {
203
+ const c: i32 = toI32(s.charCodeAt(i))
204
+ if (c < 48 || c > 57) {
205
+ return false
206
+ }
207
+ }
208
+ return true
209
+ }
210
+
211
+ /**
212
+ * Two prerelease identifiers in semver's order: numbers below words, words by
213
+ * ASCII, numbers by value. A number has no leading zero (`releasePreWellFormed`
214
+ * refuses one), so the longer is the larger and two of a length compare as
215
+ * text: past what an `i64` holds too.
216
+ */
217
+ const releaseCompareIdent = (a: string, b: string): i32 => {
218
+ const da: boolean = releaseAllDigits(a)
219
+ const db: boolean = releaseAllDigits(b)
220
+ if (da && db && a.length !== b.length) {
221
+ return releaseSign(toI64(a.length), toI64(b.length))
222
+ }
223
+ if (da && !db) {
224
+ return -1
225
+ }
226
+ if (db && !da) {
227
+ return 1
228
+ }
229
+ for (let i: i32 = 0; i < toI32(a.length) && i < toI32(b.length); i++) {
230
+ const d: i32 = toI32(a.charCodeAt(i)) - toI32(b.charCodeAt(i))
231
+ if (d !== 0) {
232
+ return d < 0 ? -1 : 1
233
+ }
234
+ }
235
+ return releaseSign(toI64(a.length), toI64(b.length))
236
+ }
237
+
238
+ /** Two prereleases in semver's order, where "" (a release) is above any prerelease. */
239
+ const releaseComparePre = (a: string, b: string): i32 => {
240
+ if (a === b) {
241
+ return 0
242
+ }
243
+ if (a.length === 0) {
244
+ return 1
245
+ }
246
+ if (b.length === 0) {
247
+ return -1
248
+ }
249
+ const pa: string[] = split(a, ".")
250
+ const pb: string[] = split(b, ".")
251
+ for (let i: i32 = 0; i < toI32(pa.length) && i < toI32(pb.length); i++) {
252
+ const c: i32 = releaseCompareIdent(pa[i], pb[i])
253
+ if (c !== 0) {
254
+ return c
255
+ }
256
+ }
257
+ return releaseSign(toI64(pa.length), toI64(pb.length))
258
+ }
259
+
260
+ /**
261
+ * Two versions in semantic-version order: the numbers, then the prerelease,
262
+ * where a prerelease sorts below its release; build metadata is ignored. A
263
+ * version that does not parse sorts below every one that does, and two that do
264
+ * not parse compare equal.
265
+ *
266
+ * @param a The first version, without a leading `v`.
267
+ * @param b The second version, without a leading `v`.
268
+ * @returns -1, 0 or 1 as `a` is older than, the same as, or newer than `b`.
269
+ */
270
+ export const releaseCompare = (a: string, b: string): i32 => {
271
+ const va: ReleaseVersion | null = releaseParseVersion(a)
272
+ const vb: ReleaseVersion | null = releaseParseVersion(b)
273
+ if (va === null || vb === null) {
274
+ if (va === null && vb === null) {
275
+ return 0
276
+ }
277
+ return va === null ? -1 : 1
278
+ }
279
+ let c: i32 = releaseSign(va.major, vb.major)
280
+ if (c === 0) {
281
+ c = releaseSign(va.minor, vb.minor)
282
+ }
283
+ if (c === 0) {
284
+ c = releaseSign(va.patch, vb.patch)
285
+ }
286
+ if (c === 0) {
287
+ c = releaseComparePre(va.pre, vb.pre)
288
+ }
289
+ return c
290
+ }
291
+
292
+ /**
293
+ * Whether `candidate` is strictly newer than `current`. Both must parse: a
294
+ * version that does not is never newer, and neither is the same release or an
295
+ * older one, so the answer never suggests a downgrade.
296
+ *
297
+ * @param candidate The version that might be newer.
298
+ * @param current The version running now.
299
+ * @returns True only when both parse and `candidate` is the newer.
300
+ */
301
+ export const releaseIsNewer = (candidate: string, current: string): boolean =>
302
+ releaseParseVersion(candidate) !== null &&
303
+ releaseParseVersion(current) !== null &&
304
+ releaseCompare(candidate, current) > 0
305
+
306
+ /**
307
+ * The version a `/releases/latest` redirect names: `location` must be exactly
308
+ * `<base>/releases/tag/v<version>`, and the version must parse. A redirect anywhere else — another repository, a login
309
+ * page, the releases list when there is no release, a query or fragment — names
310
+ * none.
311
+ *
312
+ * @param base The repository URL, e.g. `https://github.com/owner/repo`, with no trailing slash.
313
+ * @param location The redirect's `Location` header.
314
+ * @returns The version, without a `v`, or null.
315
+ */
316
+ export const releaseTagFromLocation = (base: string, location: string): string | null => {
317
+ const prefix: string = `${base}/releases/tag/v`
318
+ if (!location.startsWith(prefix)) {
319
+ return null
320
+ }
321
+ const version: string = location.slice(prefix.length)
322
+ return releaseParseVersion(version) === null ? null : version
323
+ }
324
+
325
+ /** Whether `rest`, what follows a host, is empty, a path, or a port of digits then nothing or a path. */
326
+ const releasePortThenPath = (rest: string): boolean => {
327
+ const n: i32 = toI32(rest.length)
328
+ if (n === 0 || rest.charCodeAt(0) === 47) {
329
+ return true
330
+ }
331
+ if (rest.charCodeAt(0) !== 58) {
332
+ return false
333
+ }
334
+ let i: i32 = 1
335
+ while (i < n && rest.charCodeAt(i) >= 48 && rest.charCodeAt(i) <= 57) {
336
+ i++
337
+ }
338
+ return i > 1 && (i === n || rest.charCodeAt(i) === 47)
339
+ }
340
+
341
+ /**
342
+ * Whether `base` is a URL this module will ask: `https://`, or `http://` only
343
+ * to this machine (`127.0.0.1`, `localhost` or `[::1]`), which is what a test
344
+ * server listens on.
345
+ *
346
+ * @param base The URL.
347
+ * @returns True when the URL may be fetched.
348
+ */
349
+ export const releaseBaseAllowed = (base: string): boolean => {
350
+ if (base.startsWith("https://")) {
351
+ return base.length > 8
352
+ }
353
+ const loopback: string[] = ["http://127.0.0.1", "http://localhost", "http://[::1]"]
354
+ for (const host of loopback) {
355
+ if (base.startsWith(host) && releasePortThenPath(base.slice(host.length))) {
356
+ return true
357
+ }
358
+ }
359
+ return false
360
+ }
361
+
362
+ /** The options both fetches share: no redirect followed, and every wait bounded by `timeoutMs`. */
363
+ const releaseOptions = (timeoutMs: i32, maxBody: i32): HttpOptions => {
364
+ const options: HttpOptions = new HttpOptions()
365
+ options.followRedirects = false
366
+ options.connectTimeoutMs = timeoutMs
367
+ options.readTimeoutMs = timeoutMs
368
+ options.totalTimeoutMs = timeoutMs
369
+ options.maxBodyBytes = toI64(maxBody)
370
+ return options
371
+ }
372
+
373
+ /**
374
+ * The newest release of the repository at `base`, read from where
375
+ * `<base>/releases/latest` redirects. The redirect is not followed and needs
376
+ * no token. Null when the server cannot be reached within `timeoutMs`, answers
377
+ * anything but a 3xx, or redirects anywhere but a release tag of `base`.
378
+ *
379
+ * @param base The repository URL, e.g. `https://github.com/owner/repo`: https, or http to this machine.
380
+ * @param timeoutMs The most milliseconds the whole request may take.
381
+ * @returns The newest version, without a `v`, or null.
382
+ */
383
+ export const releaseLatest = (base: string, timeoutMs: i32): string | null => {
384
+ if (!releaseBaseAllowed(base)) {
385
+ return null
386
+ }
387
+ const client: FetchSyncClient = new FetchSyncClient(releaseOptions(timeoutMs, 65536))
388
+ const res: HttpResponse | null = client.fetch(new HttpRequest("GET", `${base}/releases/latest`))
389
+ let version: string | null = null
390
+ if (res !== null && res.status >= 300 && res.status < 400) {
391
+ const location: string | null = res.header("location")
392
+ if (location !== null) {
393
+ version = releaseTagFromLocation(base, location)
394
+ }
395
+ }
396
+ client.close()
397
+ return version
398
+ }
399
+
400
+ /**
401
+ * The `install.sh` of release `version`, fetched from
402
+ * `<rawBase>/v<version>/install.sh` and written to `path`. It is the script of
403
+ * that tag, never of a branch, and it goes to a file so the caller runs it with
404
+ * `sh <path>` — nothing fetched is ever piped into a shell. `path` should be in
405
+ * a directory only this user can write.
406
+ *
407
+ * @param rawBase The raw-content URL, e.g. `https://raw.githubusercontent.com/owner/repo`: https, or http to this machine.
408
+ * @param version The release to fetch, without a `v`; refused unless `releaseValidVersion`.
409
+ * @param path Where to write the script.
410
+ * @param timeoutMs The most milliseconds the whole request may take.
411
+ * @returns True when a 200 answer was written to `path`.
412
+ */
413
+ export const releaseFetchInstaller = (
414
+ rawBase: string,
415
+ version: string,
416
+ path: string,
417
+ timeoutMs: i32
418
+ ): boolean => {
419
+ if (!releaseBaseAllowed(rawBase) || !releaseValidVersion(version)) {
420
+ return false
421
+ }
422
+ const client: FetchSyncClient = new FetchSyncClient(releaseOptions(timeoutMs, 1048576))
423
+ const res: HttpResponse | null = client.fetch(new HttpRequest("GET", `${rawBase}/v${version}/install.sh`))
424
+ let ok: boolean = false
425
+ if (res !== null && res.status === 200) {
426
+ const body: u8[] | null = res.body.readAll(toI32(1048576))
427
+ if (body !== null && body.length > 0) {
428
+ ok = writeFileBytesSync(path, body) === toI32(body.length)
429
+ }
430
+ }
431
+ client.close()
432
+ return ok
433
+ }
434
+
435
+ /**
436
+ * Whether the file at `path` may be believed: a regular file (a symbolic link
437
+ * is not followed), owned by this process's effective user, and writable by
438
+ * neither its group nor every user.
439
+ *
440
+ * @param path The file.
441
+ * @returns True when the file may be read and believed.
442
+ */
443
+ export const releaseFileTrusted = (path: string): boolean => releaseOwnedPrivate(path, 0x8000)
444
+
445
+ /** Whether `path`, not followed if a link, is of file type `kind`, this user's, and writable by no one else. */
446
+ const releaseOwnedPrivate = (path: string, kind: i64): boolean => {
447
+ const om: i64 = lstatOwnerModeSync(path)
448
+ if (om < 0) {
449
+ return false
450
+ }
451
+ const owner: i64 = (om >> 32) & 0xffffffff
452
+ const mode: i64 = om & 0xffff
453
+ return (mode & 0xf000) === kind && owner === geteuid() && (mode & 0o022) === 0
454
+ }
455
+
456
+ /** Where the last `/` of `path` is, or 0 when it has none after its first byte. */
457
+ const releaseLastSlash = (path: string): i32 => {
458
+ let slash: i32 = toI32(path.length) - 1
459
+ while (slash > 0 && path.charCodeAt(slash) !== 47) {
460
+ slash--
461
+ }
462
+ return slash
463
+ }
464
+
465
+ /**
466
+ * The cache at `path`, or null when there is none, it cannot be believed (see
467
+ * `releaseFileTrusted`; its directory, too, must be a directory this user
468
+ * owns that no one else can write, so nobody else can swap the file between
469
+ * the check and the read) or it does not parse. Its format is two lines,
470
+ * `checked <ms>` and `latest <version>`, the version empty when the check found
471
+ * none.
472
+ *
473
+ * @param path The cache file.
474
+ * @returns What the cache holds, or null.
475
+ */
476
+ export const releaseCacheRead = (path: string): ReleaseCache | null => {
477
+ const slash: i32 = releaseLastSlash(path)
478
+ if (slash > 0 && !releaseOwnedPrivate(path.slice(0, slash), 0x4000)) {
479
+ return null
480
+ }
481
+ if (!releaseFileTrusted(path)) {
482
+ return null
483
+ }
484
+ const text: string | null = readFileSyncOrNull(path)
485
+ if (text === null) {
486
+ return null
487
+ }
488
+ return releaseCacheParse(text)
489
+ }
490
+
491
+ /**
492
+ * The cache's text as a `ReleaseCache`, or null when it is not exactly the two
493
+ * lines `checked <ms>` and `latest <version>` (the version empty or valid),
494
+ * with at most a final newline after them.
495
+ *
496
+ * @param text The file's contents.
497
+ * @returns The parsed cache, or null.
498
+ */
499
+ export const releaseCacheParse = (text: string): ReleaseCache | null => {
500
+ const lines: string[] = split(text, "\n")
501
+ if (lines.length < 2 || lines.length > 3 || (lines.length === 3 && lines[2].length > 0)) {
502
+ return null
503
+ }
504
+ if (!lines[0].startsWith("checked ") || !lines[1].startsWith("latest ")) {
505
+ return null
506
+ }
507
+ const checked: i64 = releaseNumber(lines[0].slice(8))
508
+ const latest: string = lines[1].slice(7)
509
+ if (checked < 0 || (latest.length > 0 && releaseParseVersion(latest) === null)) {
510
+ return null
511
+ }
512
+ const out: ReleaseCache = new ReleaseCache()
513
+ out.checkedMs = checked
514
+ out.latest = latest
515
+ return out
516
+ }
517
+
518
+ /**
519
+ * Whether a cache checked at `checkedMs` still answers at `nowMs`: younger
520
+ * than `maxAgeMs`, and not dated in the future, which a clock set back or a
521
+ * planted file would give.
522
+ *
523
+ * @param cache The cache.
524
+ * @param nowMs The time now, in milliseconds since 1970.
525
+ * @param maxAgeMs How long an answer stays fresh.
526
+ * @returns True when the cache need not be refreshed.
527
+ */
528
+ export const releaseCacheFresh = (cache: ReleaseCache, nowMs: i64, maxAgeMs: i64): boolean =>
529
+ cache.checkedMs <= nowMs && nowMs - cache.checkedMs < maxAgeMs
530
+
531
+ /**
532
+ * Writes the cache at `path`: its directory is created mode 0700 when missing
533
+ * (its parent must exist), the text goes to a new temporary file beside it of
534
+ * mode 0600, and that is renamed over `path`, so a reader sees the old cache or
535
+ * the new one and a link planted at `path` is replaced, never followed.
536
+ *
537
+ * @param path The cache file.
538
+ * @param latest The version found, or "" for none.
539
+ * @param nowMs When the check ran, in milliseconds since 1970.
540
+ * @returns True when the cache was written.
541
+ */
542
+ export const releaseCacheWrite = (path: string, latest: string, nowMs: i64): boolean => {
543
+ const slash: i32 = releaseLastSlash(path)
544
+ if (slash > 0) {
545
+ const made: i32 = mkdirSyncMode(path.slice(0, slash), 0o700)
546
+ if (made !== 0 && made !== -17) {
547
+ return false
548
+ }
549
+ }
550
+ const temp: string = `${path}.${wallClockNanos()}.tmp`
551
+ const text: string = `checked ${nowMs}\nlatest ${latest}\n`
552
+ if (createFileExclusiveSync(temp, text, 0o600) < 0) {
553
+ return false
554
+ }
555
+ if (renameSync(temp, path) !== 0) {
556
+ unlinkSync(temp)
557
+ return false
558
+ }
559
+ return true
560
+ }
561
+
562
+ /**
563
+ * The newest release when it is newer than `current`, from the cache at
564
+ * `cachePath` while it is fresh and believed, else from `releaseLatest`, whose
565
+ * answer (or its failure, as "") is written back so the next call within
566
+ * `maxAgeMs` asks nothing.
567
+ *
568
+ * @param base The repository URL, as `releaseLatest` takes it.
569
+ * @param current The version running now.
570
+ * @param cachePath The cache file; its directory's parent must exist.
571
+ * @param maxAgeMs How long an answer stays fresh, e.g. 86400000 for a day.
572
+ * @param timeoutMs The most milliseconds a check may take.
573
+ * @returns The newer version, or null when there is none or none is known.
574
+ */
575
+ export const releaseCheckCached = (
576
+ base: string,
577
+ current: string,
578
+ cachePath: string,
579
+ maxAgeMs: i64,
580
+ timeoutMs: i32
581
+ ): string | null => {
582
+ const now: i64 = toI64(Date.now())
583
+ const cache: ReleaseCache | null = releaseCacheRead(cachePath)
584
+ let latest: string = ""
585
+ if (cache !== null && releaseCacheFresh(cache, now, maxAgeMs)) {
586
+ latest = cache.latest
587
+ } else {
588
+ const found: string | null = releaseLatest(base, timeoutMs)
589
+ latest = found === null ? "" : found
590
+ releaseCacheWrite(cachePath, latest, now)
591
+ }
592
+ return releaseIsNewer(latest, current) ? latest : null
593
+ }