@hop-top/kit 0.5.0-alpha.12 → 0.5.0-alpha.14

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 (125) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +5 -5
  3. package/dist/bus-D2bAOPYz.d.ts +55 -0
  4. package/dist/bus.d.ts +1 -0
  5. package/dist/bus.js +13 -0
  6. package/dist/chunk-74E6RNOI.js +82 -0
  7. package/dist/chunk-B7XTFDBB.js +17 -0
  8. package/dist/chunk-CAONBSPO.js +497 -0
  9. package/dist/chunk-F7RSL4N4.js +88 -0
  10. package/dist/chunk-I6XDPSXQ.js +75 -0
  11. package/dist/chunk-IDM6YZXN.js +204 -0
  12. package/dist/{chunk-BXJ2J27B.js → chunk-IGKBRNEW.js} +10 -10
  13. package/dist/{chunk-VWGP4NVJ.js → chunk-MDVGMOZO.js} +45 -39
  14. package/dist/{chunk-4FMALWYB.js → chunk-MEF7W3MG.js} +45 -45
  15. package/dist/{chunk-VGOA5Y7S.js → chunk-Q547MHNB.js} +11 -11
  16. package/dist/{chunk-K7E34Q3A.js → chunk-TUU2BY5I.js} +136 -47
  17. package/dist/chunk-VKQCOVKI.js +880 -0
  18. package/dist/cli.js +3 -3
  19. package/dist/index-BqZ7WGQf.d.ts +731 -0
  20. package/dist/index.d.ts +8 -5
  21. package/dist/index.js +32 -18
  22. package/dist/{llm-DYuR7_uX.d.ts → llm-BazFKc_2.d.ts} +95 -9
  23. package/dist/{llm-anthropic-Cd_I2xXB.d.ts → llm-anthropic-BcAitoDV.d.ts} +1 -1
  24. package/dist/llm-anthropic.d.ts +2 -2
  25. package/dist/llm-anthropic.js +4 -4
  26. package/dist/{llm-openai-DyFrucmV.d.ts → llm-openai-CSDvuRH6.d.ts} +1 -1
  27. package/dist/llm-openai.d.ts +2 -2
  28. package/dist/llm-openai.js +4 -4
  29. package/dist/llm.d.ts +1 -1
  30. package/dist/llm.js +8 -2
  31. package/dist/{routellm-B0nv59mH.d.ts → routellm-B9UrONPr.d.ts} +1 -1
  32. package/dist/routellm.d.ts +2 -2
  33. package/dist/routellm.js +5 -5
  34. package/dist/upgrade/drivers/configfile.d.ts +45 -0
  35. package/dist/upgrade/drivers/configfile.js +78 -0
  36. package/dist/upgrade/drivers/fsdir.d.ts +61 -0
  37. package/dist/upgrade/drivers/fsdir.js +170 -0
  38. package/dist/upgrade/drivers/postgres.d.ts +121 -0
  39. package/dist/upgrade/drivers/postgres.js +195 -0
  40. package/dist/upgrade/drivers/sqlite.d.ts +101 -0
  41. package/dist/upgrade/drivers/sqlite.js +241 -0
  42. package/dist/upgrade/index.d.ts +2 -0
  43. package/dist/upgrade/index.js +73 -0
  44. package/dist/uri-IJ_AoY3d.d.ts +144 -0
  45. package/dist/uri.d.ts +1 -0
  46. package/dist/uri.js +37 -0
  47. package/dist/version-DEJ3pbiO.d.ts +10 -0
  48. package/dist/wizard-Bf_qHc31.d.ts +159 -0
  49. package/dist/wizard.d.ts +1 -0
  50. package/dist/wizard.js +39 -0
  51. package/package.json +76 -17
  52. package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
  53. package/skills/hop-top-kit-ts/SKILL.md +117 -0
  54. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
  55. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
  56. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
  57. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
  58. package/skills/hop-top-kit-ts/gym.json +5 -0
  59. package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
  60. package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
  61. package/skills/hop-top-kit-ts/references/coverage.md +56 -0
  62. package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
  63. package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
  64. package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
  65. package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
  66. package/src/index.test.ts +48 -2
  67. package/src/index.ts +6 -1
  68. package/src/llm-anthropic.conformance.test.ts +7 -0
  69. package/src/llm-boundkey.test.ts +260 -0
  70. package/src/llm-choice-hermetic.test.ts +1 -1
  71. package/src/llm-config.test.ts +2 -4
  72. package/src/llm-config.ts +5 -1
  73. package/src/llm-endpoint.ts +25 -5
  74. package/src/llm-keys.ts +47 -15
  75. package/src/llm-openai.test.ts +10 -4
  76. package/src/llm-openai.ts +7 -1
  77. package/src/llm-spec.test.ts +347 -0
  78. package/src/llm-spec.ts +80 -0
  79. package/src/llm-uri.ts +96 -12
  80. package/src/llm.test.ts +2 -2
  81. package/src/llm.ts +10 -0
  82. package/src/published-types.test.ts +8 -0
  83. package/src/serve.stopped-order.test.ts +156 -0
  84. package/src/upgrade/README.md +42 -0
  85. package/src/upgrade/backup.ts +174 -0
  86. package/src/upgrade/conformance.test.ts +310 -0
  87. package/src/upgrade/document.ts +229 -0
  88. package/src/upgrade/driver.ts +66 -0
  89. package/src/upgrade/drivers/README.md +47 -0
  90. package/src/upgrade/drivers/configfile.test.ts +112 -0
  91. package/src/upgrade/drivers/configfile.ts +107 -0
  92. package/src/upgrade/drivers/fsdir.test.ts +188 -0
  93. package/src/upgrade/drivers/fsdir.ts +216 -0
  94. package/src/upgrade/drivers/isolation.test.ts +18 -0
  95. package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
  96. package/src/upgrade/drivers/postgres.test.ts +272 -0
  97. package/src/upgrade/drivers/postgres.ts +284 -0
  98. package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
  99. package/src/upgrade/drivers/sqlite.ts +300 -0
  100. package/src/upgrade/drivers/version.ts +21 -0
  101. package/src/upgrade/errors.ts +117 -0
  102. package/src/upgrade/events.ts +117 -0
  103. package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
  104. package/src/{upgrade.ts → upgrade/index.ts} +20 -0
  105. package/src/upgrade/migration.ts +89 -0
  106. package/src/upgrade/migrator.test.ts +391 -0
  107. package/src/upgrade/migrator.ts +527 -0
  108. package/src/upgrade/options.ts +59 -0
  109. package/src/upgrade/semver.ts +90 -0
  110. package/test/llm/conformance-helpers.ts +3 -0
  111. package/test/skill-snippets.test.ts +60 -0
  112. package/test/upgrade/conformance-migrator.ts +439 -0
  113. package/test/upgrade/conformance-support.ts +44 -0
  114. package/test/upgrade/driver-support.ts +44 -0
  115. package/test/upgrade/pg-container.ts +64 -0
  116. package/test/upgrade/pg-race-worker.ts +48 -0
  117. package/test/upgrade/race-helper.ts +36 -0
  118. package/test/upgrade/sqlite-support.ts +41 -0
  119. package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
  120. package/vitest.config.ts +26 -0
  121. package/dist/chunk-X4E5QGEB.js +0 -171
  122. package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
  123. package/dist/upgrade.d.ts +0 -1
  124. package/dist/upgrade.js +0 -9
  125. package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
@@ -0,0 +1,112 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+
6
+ import { tempDir } from '../../../test/upgrade/driver-support';
7
+ import { Migrator, Registry, isNotRestored, readVersionFile, type SchemaDriver } from '../index';
8
+ import { ConfigFileDriver, backupFileName } from './configfile';
9
+
10
+ let tmp: ReturnType<typeof tempDir>;
11
+ beforeEach(() => {
12
+ tmp = tempDir();
13
+ });
14
+ afterEach(() => tmp.cleanup());
15
+
16
+ describe('ConfigFileDriver', () => {
17
+ it('names the schema "config" unless told otherwise', () => {
18
+ const asDriver: SchemaDriver = new ConfigFileDriver([]); // the fit the class does not declare
19
+ expect(asDriver.name()).toBe('config');
20
+ expect(new ConfigFileDriver([], { name: 'app' }).name()).toBe('app');
21
+ });
22
+
23
+ it('backs a file up and restores it', async () => {
24
+ const cfg = join(tmp.dir, 'config.yaml');
25
+ writeFileSync(cfg, 'key: value');
26
+ const d = new ConfigFileDriver([cfg]);
27
+ const backup = join(tmp.dir, 'backup');
28
+ await d.backup(backup);
29
+ expect(readFileSync(join(backup, backupFileName(cfg)), 'utf8')).toBe('key: value');
30
+
31
+ writeFileSync(cfg, 'key: changed');
32
+ await d.restore(backup);
33
+ expect(readFileSync(cfg, 'utf8')).toBe('key: value');
34
+ });
35
+
36
+ it('keeps same-named files in different directories apart', async () => {
37
+ mkdirSync(join(tmp.dir, 'a'));
38
+ mkdirSync(join(tmp.dir, 'b'));
39
+ const a = join(tmp.dir, 'a', 'config.yaml');
40
+ const b = join(tmp.dir, 'b', 'config.yaml');
41
+ writeFileSync(a, 'a');
42
+ writeFileSync(b, 'b');
43
+ const backup = join(tmp.dir, 'backup');
44
+ await new ConfigFileDriver([a, b]).backup(backup);
45
+ expect(readFileSync(join(backup, backupFileName(a)), 'utf8')).toBe('a');
46
+ expect(readFileSync(join(backup, backupFileName(b)), 'utf8')).toBe('b');
47
+ });
48
+
49
+ it('flattens a path like Go: separators become underscores', () => {
50
+ expect(backupFileName('/etc/foo/config.yaml')).toBe('_etc_foo_config.yaml');
51
+ expect(backupFileName('/etc//foo/./config.yaml/')).toBe('_etc_foo_config.yaml');
52
+ });
53
+
54
+ it('skips a missing file on backup and a file absent from the backup on restore', async () => {
55
+ const d = new ConfigFileDriver([join(tmp.dir, 'nope.yaml')]);
56
+ const backup = join(tmp.dir, 'backup');
57
+ await d.backup(backup);
58
+ await d.restore(backup);
59
+ expect(existsSync(join(tmp.dir, 'nope.yaml'))).toBe(false);
60
+ });
61
+
62
+ it('reads the version file under dataDir', async () => {
63
+ mkdirSync(join(tmp.dir, 'config'));
64
+ writeFileSync(join(tmp.dir, 'config', 'version'), '2.0.0\n');
65
+ expect(await new ConfigFileDriver([], { dataDir: tmp.dir }).version()).toBe('2.0.0');
66
+ expect(await new ConfigFileDriver([], { dataDir: join(tmp.dir, 'none') }).version()).toBe('');
67
+ });
68
+ });
69
+
70
+ describe('through the Migrator', () => {
71
+ it('restores the file when a later migration fails and the earlier one has no down', async () => {
72
+ const data = join(tmp.dir, 'data');
73
+ const cfg = join(tmp.dir, 'config.yaml');
74
+ mkdirSync(join(data, 'config'), { recursive: true });
75
+ writeFileSync(join(data, 'config', 'version'), '1.0.0');
76
+ writeFileSync(cfg, 'v: 1');
77
+
78
+ const reg = new Registry();
79
+ reg.register({ version: '1.1.0', schema: 'config', up: () => writeFileSync(cfg, 'v: 2') });
80
+ reg.register({
81
+ version: '1.2.0',
82
+ schema: 'config',
83
+ up: () => {
84
+ throw new Error('simulated failure');
85
+ },
86
+ });
87
+ const m = new Migrator('tool', '1.2.0', { registry: reg, dataDir: data, warn: () => {} });
88
+ m.addDriver(new ConfigFileDriver([cfg], { dataDir: data }));
89
+
90
+ const err = await m.run().then(
91
+ () => undefined,
92
+ (e: unknown) => e as Error,
93
+ );
94
+ expect(err?.message).toContain('simulated failure');
95
+ expect(isNotRestored(err)).toBe(false);
96
+ expect(readFileSync(cfg, 'utf8')).toBe('v: 1');
97
+ expect(await readVersionFile(data, 'config')).toBe('1.0.0');
98
+ });
99
+
100
+ it('applies every migration and keeps the new content on success', async () => {
101
+ const data = join(tmp.dir, 'data');
102
+ const cfg = join(tmp.dir, 'config.yaml');
103
+ writeFileSync(cfg, 'v: 1');
104
+ const reg = new Registry();
105
+ reg.register({ version: '1.0.0', schema: 'config', up: () => writeFileSync(cfg, 'v: 2') });
106
+ const m = new Migrator('tool', '1.0.0', { registry: reg, dataDir: data });
107
+ m.addDriver(new ConfigFileDriver([cfg], { dataDir: data }));
108
+ await m.run();
109
+ expect(readFileSync(cfg, 'utf8')).toBe('v: 2');
110
+ expect(readFileSync(join(data, 'backups', 'config', 'pre-1.0.0', backupFileName(cfg)), 'utf8')).toBe('v: 1');
111
+ });
112
+ });
@@ -0,0 +1,107 @@
1
+ /**
2
+ * A {@link SchemaDriver} for configuration files, ported from Go
3
+ * `core/upgrade/driver/configfile`: backup copies each managed file into
4
+ * the backup directory, restore copies them back. The version lives in
5
+ * the Migrator's version file.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+
10
+ import { promises as fs } from 'node:fs';
11
+ import * as path from 'node:path';
12
+
13
+ import { versionOf, type DriverOptions } from './version';
14
+
15
+ /** Options of a {@link ConfigFileDriver}. */
16
+ export interface ConfigFileOptions extends DriverOptions {
17
+ /** The schema name (default `"config"`). */
18
+ name?: string;
19
+ }
20
+
21
+ const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
22
+ const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
23
+
24
+ /**
25
+ * The backup file name of a managed path: the cleaned path with every
26
+ * separator turned into `_` (`/etc/foo/config.yaml` becomes
27
+ * `_etc_foo_config.yaml`), so two files named alike never collide.
28
+ */
29
+ export function backupFileName(p: string): string {
30
+ let clean = path.normalize(p);
31
+ if (clean.length > 1 && clean.endsWith(path.sep)) clean = clean.slice(0, -1);
32
+ return clean.split(path.sep).join('_');
33
+ }
34
+
35
+ /**
36
+ * Backs up and restores one or more configuration files.
37
+ *
38
+ * A `SchemaDriver`; not declared with `implements` so the bundled declarations
39
+ * keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
40
+ * check the fit).
41
+ */
42
+ export class ConfigFileDriver {
43
+ private readonly schema: string;
44
+ private readonly paths: readonly string[];
45
+ private readonly opts: DriverOptions;
46
+
47
+ constructor(paths: readonly string[], options: ConfigFileOptions = {}) {
48
+ this.paths = [...paths];
49
+ this.schema = options.name ?? 'config';
50
+ this.opts = { dataDir: options.dataDir, tool: options.tool };
51
+ }
52
+
53
+ name(): string {
54
+ return this.schema;
55
+ }
56
+
57
+ version(): Promise<string> {
58
+ return versionOf(this.opts, this.schema);
59
+ }
60
+
61
+ /** The Migrator writes the version file; nothing to do here. */
62
+ setVersion(): void {}
63
+
64
+ /** Copies each managed file into `dest`; a file that does not exist is skipped. */
65
+ async backup(dest: string): Promise<void> {
66
+ try {
67
+ await fs.mkdir(dest, { recursive: true, mode: 0o750 });
68
+ } catch (e) {
69
+ throw new Error(`create backup dir: ${msg(e)}`, { cause: e });
70
+ }
71
+ for (const p of this.paths) {
72
+ const name = backupFileName(p);
73
+ try {
74
+ await copyFile(p, path.join(dest, name));
75
+ } catch (e) {
76
+ if (isMissing(e)) continue;
77
+ throw new Error(`backup ${name}: ${msg(e)}`, { cause: e });
78
+ }
79
+ }
80
+ }
81
+
82
+ /** Copies each backed-up file back to its place; a file absent from `src` is skipped. */
83
+ async restore(src: string): Promise<void> {
84
+ for (const p of this.paths) {
85
+ const name = backupFileName(p);
86
+ const file = path.join(src, name);
87
+ try {
88
+ await fs.stat(file);
89
+ } catch (e) {
90
+ if (isMissing(e)) continue;
91
+ throw new Error(`restore ${name}: ${msg(e)}`, { cause: e });
92
+ }
93
+ try {
94
+ await copyFile(file, p);
95
+ } catch (e) {
96
+ throw new Error(`restore ${name}: ${msg(e)}`, { cause: e });
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ /** Copies `src` over `dst`, creating `dst`'s directory. An existing `dst` keeps its mode. */
103
+ async function copyFile(src: string, dst: string): Promise<void> {
104
+ const data = await fs.readFile(src);
105
+ await fs.mkdir(path.dirname(dst), { recursive: true, mode: 0o750 });
106
+ await fs.writeFile(dst, data);
107
+ }
@@ -0,0 +1,188 @@
1
+ import {
2
+ copyFileSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ symlinkSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { dirname, join } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ import * as tar from 'tar';
15
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
16
+
17
+ import { tempDir, writeRawTarGz, type RawMember } from '../../../test/upgrade/driver-support';
18
+ import { Migrator, Registry, isNotRestored, readVersionFile, type SchemaDriver } from '../index';
19
+ import { FsDirDriver, unsafeName } from './fsdir';
20
+
21
+ const FIXTURE = join(dirname(fileURLToPath(import.meta.url)), '../../../test/upgrade/testdata/go-fsdir-mydata.tar.gz');
22
+
23
+ let tmp: ReturnType<typeof tempDir>;
24
+ let dir: string; // the managed directory
25
+ let backup: string;
26
+ beforeEach(() => {
27
+ tmp = tempDir();
28
+ dir = join(tmp.dir, 'mydata');
29
+ backup = join(tmp.dir, 'backup');
30
+ mkdirSync(join(dir, 'sub'), { recursive: true });
31
+ writeFileSync(join(dir, 'file.txt'), 'hello');
32
+ writeFileSync(join(dir, 'sub', 'nested.txt'), 'world');
33
+ });
34
+ afterEach(() => tmp.cleanup());
35
+
36
+ const names = async (archive: string): Promise<string[]> => {
37
+ const out: string[] = [];
38
+ await tar.t({ file: archive, onReadEntry: (e) => void out.push(e.path.replace(/\/$/, '')) });
39
+ return out.sort();
40
+ };
41
+
42
+ describe('FsDirDriver backup and restore', () => {
43
+ it('fits SchemaDriver', () => {
44
+ const d: SchemaDriver = new FsDirDriver('mydata', dir);
45
+ expect(d.name()).toBe('mydata');
46
+ });
47
+
48
+ it('round trips a directory', async () => {
49
+ const d = new FsDirDriver('mydata', dir);
50
+ await d.backup(backup);
51
+ expect(existsSync(join(backup, 'mydata.tar.gz'))).toBe(true);
52
+
53
+ writeFileSync(join(dir, 'file.txt'), 'changed');
54
+ writeFileSync(join(dir, 'extra.txt'), 'new');
55
+ await d.restore(backup);
56
+
57
+ expect(readFileSync(join(dir, 'file.txt'), 'utf8')).toBe('hello');
58
+ expect(readFileSync(join(dir, 'sub', 'nested.txt'), 'utf8')).toBe('world');
59
+ expect(existsSync(join(dir, 'extra.txt'))).toBe(false);
60
+ expect(readdirSync(tmp.dir).sort()).toEqual(['backup', 'mydata']); // no temp leftovers
61
+ });
62
+
63
+ it('backs up nothing for a missing directory', async () => {
64
+ await new FsDirDriver('missing', join(tmp.dir, 'nope')).backup(backup);
65
+ expect(readdirSync(backup)).toEqual([]);
66
+ });
67
+
68
+ it('fails a restore without an archive', async () => {
69
+ await expect(new FsDirDriver('mydata', dir).restore(tmp.dir)).rejects.toThrow(/backup archive not found/);
70
+ expect(readFileSync(join(dir, 'file.txt'), 'utf8')).toBe('hello');
71
+ });
72
+
73
+ it('restores into a directory that no longer exists', async () => {
74
+ const d = new FsDirDriver('mydata', dir);
75
+ await d.backup(backup);
76
+ execFileSync('rm', ['-rf', dir]);
77
+ await d.restore(backup);
78
+ expect(readFileSync(join(dir, 'sub', 'nested.txt'), 'utf8')).toBe('world');
79
+ });
80
+
81
+ it('refuses to back up a symbolic link instead of dropping it', async () => {
82
+ symlinkSync('file.txt', join(dir, 'link'));
83
+ await expect(new FsDirDriver('mydata', dir).backup(backup)).rejects.toThrow(/only files and directories/);
84
+ expect(existsSync(join(backup, 'mydata.tar.gz'))).toBe(false);
85
+ });
86
+ });
87
+
88
+ describe('archive layout shared with Go', () => {
89
+ it('writes Go-style member names: relative, "." for the directory', async () => {
90
+ await new FsDirDriver('mydata', dir).backup(backup);
91
+ expect(await names(join(backup, 'mydata.tar.gz'))).toEqual(['.', 'file.txt', 'sub', 'sub/nested.txt']);
92
+ });
93
+
94
+ it('restores an archive written by the Go driver', async () => {
95
+ mkdirSync(backup);
96
+ copyFileSync(FIXTURE, join(backup, 'mydata.tar.gz'));
97
+ writeFileSync(join(dir, 'file.txt'), 'stale');
98
+ await new FsDirDriver('mydata', dir).restore(backup);
99
+ expect(readFileSync(join(dir, 'file.txt'), 'utf8')).toBe('hello');
100
+ expect(readFileSync(join(dir, 'sub', 'nested.txt'), 'utf8')).toBe('world');
101
+ expect(readdirSync(join(dir, 'empty'))).toEqual([]);
102
+ });
103
+ });
104
+
105
+ describe('traversal guard', () => {
106
+ const restoreOf = async (members: RawMember[]): Promise<Error> => {
107
+ mkdirSync(backup, { recursive: true });
108
+ writeRawTarGz(join(backup, 'mydata.tar.gz'), members);
109
+ const err = await new FsDirDriver('mydata', dir).restore(backup).then(
110
+ () => undefined,
111
+ (e: unknown) => e as Error,
112
+ );
113
+ expect(err, 'restore should have been refused').toBeDefined();
114
+ // Nothing escaped, and the directory is as it was.
115
+ expect(existsSync(join(tmp.dir, 'evil.txt'))).toBe(false);
116
+ expect(readFileSync(join(dir, 'file.txt'), 'utf8')).toBe('hello');
117
+ expect(readdirSync(tmp.dir).sort()).toEqual(['backup', 'mydata']);
118
+ return err as Error;
119
+ };
120
+
121
+ it('rejects a ".." member', async () => {
122
+ const err = await restoreOf([{ path: 'ok.txt', body: 'x' }, { path: '../evil.txt', body: 'x' }]);
123
+ expect(err.message).toBe('path traversal blocked: ../evil.txt');
124
+ });
125
+
126
+ it('rejects ".." in the middle of a name', async () => {
127
+ const err = await restoreOf([{ path: 'a/../../evil.txt', body: 'x' }]);
128
+ expect(err.message).toMatch(/^path traversal blocked: /);
129
+ });
130
+
131
+ it('rejects an absolute name', async () => {
132
+ const err = await restoreOf([{ path: join(tmp.dir, 'evil.txt'), body: 'x' }]);
133
+ expect(err.message).toMatch(/^path traversal blocked: /);
134
+ });
135
+
136
+ it('rejects a symbolic link member, escaping or not', async () => {
137
+ const err = await restoreOf([{ path: 'link', type: 'SymbolicLink', linkpath: '../../etc' }]);
138
+ expect(err.message).toMatch(/^special member blocked: link \(SymbolicLink\)/);
139
+ const inside = await restoreOf([{ path: 'link2', type: 'SymbolicLink', linkpath: 'file.txt' }]);
140
+ expect(inside.message).toMatch(/special member blocked: link2/);
141
+ });
142
+
143
+ it('rejects a hard link member', async () => {
144
+ const err = await restoreOf([{ path: 'h', type: 'Link', linkpath: '/etc/passwd' }]);
145
+ expect(err.message).toMatch(/^special member blocked: h \(Link\)/);
146
+ });
147
+
148
+ it('rejects a device or fifo member', async () => {
149
+ const err = await restoreOf([{ path: 'dev', type: 'CharacterDevice' }]);
150
+ expect(err.message).toMatch(/^special member blocked: dev/);
151
+ const fifo = await restoreOf([{ path: 'pipe', type: 'FIFO' }]);
152
+ expect(fifo.message).toMatch(/^special member blocked: pipe/);
153
+ });
154
+
155
+ it('unsafeName accepts plain relative names only', () => {
156
+ for (const ok of ['.', 'a', 'a/b.txt', 'sub/', '..foo', 'a..b/c']) expect(unsafeName(ok), ok).toBeUndefined();
157
+ for (const bad of ['..', '../x', 'a/../b', '/x', '\\x', 'C:x', 'a\\..\\b', 'a\0b']) {
158
+ expect(unsafeName(bad), bad).toBeDefined();
159
+ }
160
+ });
161
+ });
162
+
163
+ describe('through the Migrator', () => {
164
+ it('restores the directory when a migration fails and nothing can undo it', async () => {
165
+ const data = join(tmp.dir, 'data');
166
+ mkdirSync(join(data, 'mydata'), { recursive: true });
167
+ writeFileSync(join(data, 'mydata', 'version'), '1.0.0');
168
+ const reg = new Registry();
169
+ reg.register({ version: '1.1.0', schema: 'mydata', up: () => writeFileSync(join(dir, 'file.txt'), 'migrated') });
170
+ reg.register({
171
+ version: '1.2.0',
172
+ schema: 'mydata',
173
+ up: () => {
174
+ throw new Error('simulated failure');
175
+ },
176
+ });
177
+ const m = new Migrator('tool', '1.2.0', { registry: reg, dataDir: data, warn: () => {} });
178
+ m.addDriver(new FsDirDriver('mydata', dir, { dataDir: data }));
179
+ const err = await m.run().then(
180
+ () => undefined,
181
+ (e: unknown) => e as Error,
182
+ );
183
+ expect(err?.message).toContain('simulated failure');
184
+ expect(isNotRestored(err)).toBe(false);
185
+ expect(readFileSync(join(dir, 'file.txt'), 'utf8')).toBe('hello');
186
+ expect(await readVersionFile(data, 'mydata')).toBe('1.0.0');
187
+ });
188
+ });
@@ -0,0 +1,216 @@
1
+ /**
2
+ * A {@link SchemaDriver} for a filesystem directory, ported from Go
3
+ * `core/upgrade/driver/fsdir`: backup writes `<name>.tar.gz` into the
4
+ * backup directory, restore replaces the directory with its contents.
5
+ * The archive layout is Go's (entries relative to the directory, `.` for
6
+ * the directory itself, gzip), so either port restores the other's.
7
+ *
8
+ * Imports the `tar` package: import this module only where it is used
9
+ * (`@hop-top/kit/upgrade/drivers/fsdir`); the main entry never loads it.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+
14
+ import { promises as fs } from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import { randomBytes } from 'node:crypto';
17
+
18
+ import * as tar from 'tar';
19
+
20
+ import { versionOf, type DriverOptions } from './version';
21
+
22
+ /** Options of an {@link FsDirDriver}. */
23
+ export type FsDirOptions = DriverOptions;
24
+
25
+ const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
26
+ const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
27
+
28
+ /** Member types a backup holds and a restore accepts: files and directories only. */
29
+ const PLAIN = new Set(['File', 'OldFile', 'ContiguousFile', 'Directory']);
30
+
31
+ /**
32
+ * Why a member name must not be extracted under the target directory, or
33
+ * `undefined` when it is a plain relative path inside it. Rejects absolute
34
+ * names (POSIX, backslash and drive-letter forms), any `..` segment and
35
+ * NUL bytes, on top of what the `tar` package does by default (it strips
36
+ * a leading `/` and skips `..` members with a warning instead of failing).
37
+ */
38
+ export function unsafeName(name: string): string | undefined {
39
+ if (name.includes('\0')) return 'NUL in name';
40
+ if (name.startsWith('/') || name.startsWith('\\') || /^[A-Za-z]:/.test(name)) return 'absolute path';
41
+ if (name.split(/[\\/]/).includes('..')) return 'parent directory reference';
42
+ return undefined;
43
+ }
44
+
45
+ /**
46
+ * Backs up and restores one directory as a tar.gz archive.
47
+ *
48
+ * A `SchemaDriver`; not declared with `implements` so the bundled declarations
49
+ * keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
50
+ * check the fit).
51
+ */
52
+ export class FsDirDriver {
53
+ private readonly opts: DriverOptions;
54
+
55
+ constructor(
56
+ private readonly schema: string,
57
+ private readonly dirPath: string,
58
+ options: FsDirOptions = {},
59
+ ) {
60
+ this.opts = { dataDir: options.dataDir, tool: options.tool };
61
+ }
62
+
63
+ name(): string {
64
+ return this.schema;
65
+ }
66
+
67
+ version(): Promise<string> {
68
+ return versionOf(this.opts, this.schema);
69
+ }
70
+
71
+ /** The Migrator writes the version file; nothing to do here. */
72
+ setVersion(): void {}
73
+
74
+ private archiveName(): string {
75
+ return this.schema + '.tar.gz';
76
+ }
77
+
78
+ /**
79
+ * Writes `<dest>/<name>.tar.gz` of the directory; a missing directory is
80
+ * "nothing to back up" (no archive, no error). Symbolic links and special
81
+ * files are not archived: they make the backup fail rather than be lost.
82
+ */
83
+ async backup(dest: string): Promise<void> {
84
+ try {
85
+ await fs.mkdir(dest, { recursive: true, mode: 0o750 });
86
+ } catch (e) {
87
+ throw new Error(`create backup dir: ${msg(e)}`, { cause: e });
88
+ }
89
+ try {
90
+ await fs.stat(this.dirPath);
91
+ } catch (e) {
92
+ if (isMissing(e)) return;
93
+ throw new Error(`stat dir: ${msg(e)}`, { cause: e });
94
+ }
95
+ await requirePlain(this.dirPath);
96
+
97
+ const archive = path.join(dest, this.archiveName());
98
+ const tmp = archive + '.tmp';
99
+ try {
100
+ await tar.c(
101
+ {
102
+ file: tmp,
103
+ cwd: this.dirPath,
104
+ gzip: true,
105
+ // Go's names: relative to the directory, `.` for the directory.
106
+ onWriteEntry: (entry) => {
107
+ entry.path = entry.path.replace(/^\.\//, '') || '.';
108
+ },
109
+ },
110
+ ['.'],
111
+ );
112
+ await fs.rename(tmp, archive);
113
+ } catch (e) {
114
+ await fs.rm(tmp, { force: true });
115
+ throw new Error(`create archive: ${msg(e)}`, { cause: e });
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Replaces the directory with the archive in `src`. Every member is
121
+ * checked first (see {@link unsafeName}; links, devices and other
122
+ * special members are refused: `path traversal blocked: <name>`,
123
+ * `special member blocked: <name>`); the
124
+ * archive is then extracted into a temporary directory beside the target
125
+ * and swapped in, so a refused or failed restore leaves the directory
126
+ * as it was.
127
+ */
128
+ async restore(src: string): Promise<void> {
129
+ const archive = path.join(src, this.archiveName());
130
+ try {
131
+ await fs.stat(archive);
132
+ } catch (e) {
133
+ if (isMissing(e)) throw new Error(`backup archive not found: ${archive}`, { cause: e });
134
+ throw new Error(`open archive: ${msg(e)}`, { cause: e });
135
+ }
136
+
137
+ const hasRoot = await checkMembers(archive);
138
+
139
+ const target = path.resolve(this.dirPath);
140
+ const parent = path.dirname(target);
141
+ const base = path.basename(target);
142
+ await fs.mkdir(parent, { recursive: true, mode: 0o750 });
143
+ const tmp = await fs.mkdtemp(path.join(parent, `.${base}.restore-`));
144
+ let old: string | undefined;
145
+ try {
146
+ try {
147
+ await tar.x({
148
+ file: archive,
149
+ cwd: tmp,
150
+ strict: true,
151
+ preservePaths: false,
152
+ preserveOwner: false,
153
+ filter: (_p, entry) => PLAIN.has((entry as tar.ReadEntry).type),
154
+ });
155
+ } catch (e) {
156
+ throw new Error(`tar read: ${msg(e)}`, { cause: e });
157
+ }
158
+ if (!hasRoot) await fs.chmod(tmp, 0o750);
159
+
160
+ try {
161
+ old = path.join(parent, `.${base}.old-${randomBytes(6).toString('hex')}`);
162
+ await fs.rename(target, old);
163
+ } catch (e) {
164
+ if (!isMissing(e)) throw new Error(`remove dir: ${msg(e)}`, { cause: e });
165
+ old = undefined;
166
+ }
167
+ try {
168
+ await fs.rename(tmp, target);
169
+ } catch (e) {
170
+ if (old !== undefined) await fs.rename(old, target).catch(() => undefined);
171
+ throw new Error(`recreate dir: ${msg(e)}`, { cause: e });
172
+ }
173
+ } finally {
174
+ await fs.rm(tmp, { recursive: true, force: true });
175
+ }
176
+ if (old !== undefined) await fs.rm(old, { recursive: true, force: true });
177
+ }
178
+ }
179
+
180
+ /** Throws when the tree holds anything but files and directories. */
181
+ async function requirePlain(dir: string): Promise<void> {
182
+ const entries = await fs.readdir(dir, { withFileTypes: true, recursive: true });
183
+ for (const e of entries) {
184
+ if (e.isFile() || e.isDirectory()) continue;
185
+ const rel = path.relative(dir, path.join(e.parentPath, e.name));
186
+ throw new Error(`create archive: ${rel}: only files and directories can be backed up`);
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Reads the archive's headers and throws on the first member that must not
192
+ * be extracted. Resolves whether the archive has an entry for the
193
+ * directory itself (`.`).
194
+ */
195
+ async function checkMembers(archive: string): Promise<boolean> {
196
+ let problem: string | undefined;
197
+ let hasRoot = false;
198
+ try {
199
+ await tar.t({
200
+ file: archive,
201
+ strict: true,
202
+ onReadEntry: (entry) => {
203
+ entry.resume();
204
+ if (problem !== undefined) return;
205
+ const bad = unsafeName(entry.path);
206
+ if (bad !== undefined) problem = `path traversal blocked: ${entry.path}`;
207
+ else if (!PLAIN.has(entry.type)) problem = `special member blocked: ${entry.path} (${entry.type})`;
208
+ else if (path.posix.normalize(entry.path) === './' || path.posix.normalize(entry.path) === '.') hasRoot = true;
209
+ },
210
+ });
211
+ } catch (e) {
212
+ throw new Error(`tar read: ${msg(e)}`, { cause: e });
213
+ }
214
+ if (problem !== undefined) throw new Error(problem);
215
+ return hasRoot;
216
+ }
@@ -0,0 +1,18 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ const src = join(dirname(fileURLToPath(import.meta.url)), '../..');
8
+
9
+ // The drivers import `better-sqlite3` and `tar`. They are reachable only
10
+ // through their own subpath exports, so importing the main entry or
11
+ // `@hop-top/kit/upgrade` never loads either module.
12
+ describe('driver isolation', () => {
13
+ it.each(['index.ts', 'upgrade/index.ts', 'upgrade/migrator.ts'])('%s does not import the drivers', (file) => {
14
+ const text = readFileSync(join(src, file), 'utf8');
15
+ expect(text).not.toMatch(/^\s*(import|export)\b[^;]*\bfrom\s+['"][^'"]*\/drivers\//m);
16
+ expect(text).not.toMatch(/\bfrom\s+['"](better-sqlite3|tar)['"]/);
17
+ });
18
+ });