typevault 0.1.0 → 0.3.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.
Files changed (76) hide show
  1. package/README.md +156 -115
  2. package/package.json +14 -2
  3. package/src/access/env.ts +77 -17
  4. package/src/access/keys.ts +14 -14
  5. package/src/access/schemas.ts +6 -12
  6. package/src/access/scope.ts +14 -9
  7. package/src/access/scoped.ts +118 -44
  8. package/src/access/sealed-access.ts +50 -23
  9. package/src/access/sealed.ts +56 -31
  10. package/src/access/types.ts +27 -30
  11. package/src/admin.ts +68 -0
  12. package/src/audit/log.ts +28 -12
  13. package/src/cli/commands/admin.ts +93 -48
  14. package/src/cli/commands/daemon.ts +42 -17
  15. package/src/cli/commands/entries.ts +195 -60
  16. package/src/cli/commands/grant.ts +24 -22
  17. package/src/cli/commands/members.ts +307 -0
  18. package/src/cli/commands/run.ts +191 -44
  19. package/src/cli/context.ts +163 -15
  20. package/src/cli/index.ts +33 -5
  21. package/src/cli/password.ts +74 -0
  22. package/src/cli/web-prompt.ts +79 -0
  23. package/src/core/admin.ts +144 -76
  24. package/src/core/adopt.ts +40 -9
  25. package/src/core/crypto.ts +6 -4
  26. package/src/core/doctor.ts +15 -16
  27. package/src/core/entries.ts +66 -52
  28. package/src/core/errors.ts +8 -2
  29. package/src/core/fsx.ts +7 -3
  30. package/src/core/holder.ts +87 -0
  31. package/src/core/identity.ts +132 -0
  32. package/src/core/init.ts +73 -23
  33. package/src/core/json-file.ts +20 -0
  34. package/src/core/keyring.ts +100 -56
  35. package/src/core/layout.ts +143 -26
  36. package/src/core/lock.ts +128 -16
  37. package/src/core/naming.ts +150 -50
  38. package/src/core/password.ts +111 -0
  39. package/src/core/payload.ts +42 -38
  40. package/src/core/revisions.ts +11 -6
  41. package/src/core/rotate.ts +59 -42
  42. package/src/core/state.ts +102 -54
  43. package/src/core/txn.ts +9 -7
  44. package/src/core/vault.ts +108 -46
  45. package/src/core/worktrees.ts +51 -0
  46. package/src/daemon/admin-routes.ts +33 -21
  47. package/src/daemon/agent-routes.ts +31 -11
  48. package/src/daemon/client.ts +24 -2
  49. package/src/daemon/daemon.ts +218 -33
  50. package/src/daemon/grants.ts +25 -7
  51. package/src/daemon/http.ts +11 -2
  52. package/src/daemon/live-access.ts +8 -4
  53. package/src/daemon/protocol.ts +17 -12
  54. package/src/daemon/requests.ts +75 -51
  55. package/src/daemon/spawn.ts +218 -9
  56. package/src/export/1password.ts +157 -0
  57. package/src/import/1password-live.ts +399 -0
  58. package/src/import/1password.ts +26 -5
  59. package/src/import/bitwarden.ts +3 -3
  60. package/src/import/csv.ts +1 -1
  61. package/src/import/dotenv.ts +4 -3
  62. package/src/import/index.ts +1 -0
  63. package/src/import/keepass.ts +2 -2
  64. package/src/import/lastpass.ts +2 -2
  65. package/src/import/shared.ts +67 -10
  66. package/src/import/typeclaw.ts +2 -2
  67. package/src/import/types.ts +1 -1
  68. package/src/index.ts +58 -0
  69. package/src/owner.ts +156 -0
  70. package/src/prompt/browser.ts +48 -15
  71. package/src/prompt/index.ts +121 -64
  72. package/src/prompt/page.ts +27 -11
  73. package/src/prompt/styles.ts +64 -34
  74. package/src/prompt/types.ts +7 -4
  75. package/src/redact/index.ts +48 -12
  76. package/src/redact/scrub-file.ts +15 -7
@@ -1,21 +1,64 @@
1
1
  import { existsSync, lstatSync, readFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
 
4
- import { decodeSecretKey, publicKeyOf, type SecretKey, unseal } from './crypto'
4
+ import { decodeSecretKey, type PublicKey, publicKeyOf, type SecretKey, unseal } from './crypto'
5
5
  import { TypeVaultError } from './errors'
6
6
  import { assertNoSymlinks } from './fsx'
7
7
  import type { Layout } from './layout'
8
8
  import { includersOf, type VaultState } from './state'
9
9
 
10
10
  export type WrapHolder =
11
- | { readonly kind: 'operator' }
12
- | { readonly kind: 'group'; readonly group: string; readonly gen: number }
11
+ | { readonly kind: 'owner' }
12
+ | { readonly kind: 'tier'; readonly tier: string; readonly gen: number }
13
+ | { readonly kind: 'member'; readonly name: string }
13
14
 
14
- /** Vault-relative path of a group key sealed to a holder: the operator, or an including group's key. */
15
- export const wrapPath = (group: string, gen: number, holder: WrapHolder): string =>
16
- join('groups', group, String(gen), holder.kind === 'operator' ? 'operator.age' : `${holder.group}.${holder.gen}.age`)
15
+ /** Vault-relative path of a tier key sealed to a holder: the owner, an including tier's key, or a member. */
16
+ export function wrapPath(tier: string, gen: number, holder: WrapHolder): string {
17
+ const dir = join('tiers', tier, String(gen))
18
+ switch (holder.kind) {
19
+ case 'owner':
20
+ return join(dir, 'owner.age')
21
+ case 'tier':
22
+ return join(dir, `${holder.tier}.${holder.gen}.age`)
23
+ case 'member':
24
+ return join(dir, 'members', `${holder.name}.age`)
25
+ }
26
+ }
17
27
 
18
- /** Resolves group keys from the keys this process holds, unwrapping along includes. */
28
+ export const ownerWrapPath = (member: string): string => join('owner', `${member}.age`)
29
+
30
+ /** The member keys among `keys` that match a member listed in the owner-signed state. */
31
+ export async function heldMembers(
32
+ state: VaultState,
33
+ keys: readonly SecretKey[],
34
+ ): Promise<readonly { readonly name: string; readonly key: SecretKey }[]> {
35
+ const held = await Promise.all(
36
+ keys.map(async (key) => {
37
+ if (key.role.kind !== 'member') return []
38
+ const member = state.members[key.role.name]
39
+ return member !== undefined && samePublic(await publicKeyOf(key), member) ? [{ name: key.role.name, key }] : []
40
+ }),
41
+ )
42
+ return held.flat()
43
+ }
44
+
45
+ /** The owner key, unwrapped through an owner member's key when the owner key itself isn't held. */
46
+ export async function unwrapOwner(
47
+ layout: Layout,
48
+ state: VaultState,
49
+ keys: readonly SecretKey[],
50
+ ): Promise<SecretKey | undefined> {
51
+ const held = keys.find((key) => key.role.kind === 'owner')
52
+ if (held !== undefined) return held
53
+ for (const { name, key } of await heldMembers(state, keys)) {
54
+ if (state.members[name]?.owner !== true) continue
55
+ const owner = await openSealedKey(layout, ownerWrapPath(name), key, state.owner)
56
+ if (owner !== undefined) return owner
57
+ }
58
+ return undefined
59
+ }
60
+
61
+ /** Resolves tier keys from the keys this process holds, unwrapping along includes. */
19
62
  export class Keyring {
20
63
  readonly #layout: Layout
21
64
  readonly #state: VaultState
@@ -28,79 +71,80 @@ export class Keyring {
28
71
  this.#keys = keys
29
72
  }
30
73
 
31
- get operator(): SecretKey | undefined {
32
- return this.#keys.find((key) => key.role.kind === 'operator')
74
+ get owner(): SecretKey | undefined {
75
+ return this.#keys.find((key) => key.role.kind === 'owner')
33
76
  }
34
77
 
35
- /** The current-generation key of `group`, or undefined when no held key reaches it. */
36
- unlock(group: string): Promise<SecretKey | undefined> {
37
- const cached = this.#cache.get(group)
78
+ /** The current-generation key of `tier`, or undefined when no held key reaches it. */
79
+ unlock(tier: string): Promise<SecretKey | undefined> {
80
+ const cached = this.#cache.get(tier)
38
81
  if (cached !== undefined) return cached
39
- const pending = this.#resolve(group)
40
- this.#cache.set(group, pending)
82
+ const pending = this.#resolve(tier)
83
+ this.#cache.set(tier, pending)
41
84
  return pending
42
85
  }
43
86
 
44
- async reachableGroups(): Promise<ReadonlySet<string>> {
45
- const names = Object.keys(this.#state.groups)
87
+ async reachableTiers(): Promise<ReadonlySet<string>> {
88
+ const names = Object.keys(this.#state.tiers)
46
89
  const unlocked = await Promise.all(
47
90
  names.map(async (name) => ((await this.unlock(name)) === undefined ? [] : [name])),
48
91
  )
49
92
  return new Set(unlocked.flat())
50
93
  }
51
94
 
52
- async #resolve(group: string): Promise<SecretKey | undefined> {
53
- const meta = this.#state.groups[group]
95
+ async #resolve(tier: string): Promise<SecretKey | undefined> {
96
+ const meta = this.#state.tiers[tier]
54
97
  if (meta === undefined) return undefined
55
98
  const held = this.#keys.find(
56
- (key) => key.role.kind === 'group' && key.role.group === group && key.role.gen === meta.gen,
99
+ (key) => key.role.kind === 'tier' && key.role.tier === tier && key.role.gen === meta.gen,
57
100
  )
58
101
  if (held !== undefined) return held
59
- const operator = this.operator
60
- if (operator !== undefined) {
61
- const key = await this.#openWrap(group, meta.gen, { kind: 'operator' }, operator)
102
+ const owner = this.owner
103
+ if (owner !== undefined) {
104
+ const key = await this.#openWrap(tier, meta.gen, { kind: 'owner' }, owner)
105
+ if (key !== undefined) return key
106
+ }
107
+ for (const { name, key: memberKey } of await heldMembers(this.#state, this.#keys)) {
108
+ if (this.#state.members[name]?.tiers.includes(tier) !== true) continue
109
+ const key = await this.#openWrap(tier, meta.gen, { kind: 'member', name }, memberKey)
62
110
  if (key !== undefined) return key
63
111
  }
64
- for (const includer of includersOf(this.#state.groups, group)) {
65
- const includerGen = this.#state.groups[includer]?.gen
112
+ for (const includer of includersOf(this.#state.tiers, tier)) {
113
+ const includerGen = this.#state.tiers[includer]?.gen
66
114
  const includerKey = await this.unlock(includer)
67
115
  if (includerGen === undefined || includerKey === undefined) continue
68
- const key = await this.#openWrap(
69
- group,
70
- meta.gen,
71
- { kind: 'group', group: includer, gen: includerGen },
72
- includerKey,
73
- )
116
+ const key = await this.#openWrap(tier, meta.gen, { kind: 'tier', tier: includer, gen: includerGen }, includerKey)
74
117
  if (key !== undefined) return key
75
118
  }
76
119
  return undefined
77
120
  }
78
121
 
79
- async #openWrap(
80
- group: string,
81
- gen: number,
82
- holder: WrapHolder,
83
- holderKey: SecretKey,
84
- ): Promise<SecretKey | undefined> {
85
- const rel = wrapPath(group, gen, holder)
86
- assertNoSymlinks(this.#layout.vault, rel)
87
- const path = join(this.#layout.vault, rel)
88
- if (!existsSync(path) || !lstatSync(path).isFile()) return undefined
89
- // Wrap files aren't signed and the operator's recipient is public, so a planted wrap must fail quietly.
90
- const key = await unseal([holderKey.identity], readFileSync(path))
91
- .then((bytes) => decodeSecretKey(new TextDecoder().decode(bytes)))
92
- .catch((error: unknown) => {
93
- if (error instanceof TypeVaultError) return undefined
94
- throw error
95
- })
96
- if (key === undefined) return undefined
97
- // A wrap that doesn't match the operator-signed public key is ignored rather than trusted.
98
- const expected = this.#state.groups[group]
99
- const actual = await publicKeyOf(key)
100
- return expected !== undefined &&
101
- actual.recipient === expected.recipient &&
102
- actual.signPublic === expected.signPublic
103
- ? key
104
- : undefined
122
+ async #openWrap(tier: string, gen: number, holder: WrapHolder, holderKey: SecretKey): Promise<SecretKey | undefined> {
123
+ const expected = this.#state.tiers[tier]
124
+ if (expected === undefined) return undefined
125
+ return openSealedKey(this.#layout, wrapPath(tier, gen, holder), holderKey, expected)
105
126
  }
106
127
  }
128
+
129
+ const samePublic = (a: PublicKey, b: PublicKey): boolean => a.recipient === b.recipient && a.signPublic === b.signPublic
130
+
131
+ /** Opens a key sealed at `rel`, keeping it only when it matches the owner-signed public key it should be. */
132
+ async function openSealedKey(
133
+ layout: Layout,
134
+ rel: string,
135
+ holderKey: SecretKey,
136
+ expected: PublicKey,
137
+ ): Promise<SecretKey | undefined> {
138
+ assertNoSymlinks(layout.vault, rel)
139
+ const path = join(layout.vault, rel)
140
+ if (!existsSync(path) || !lstatSync(path).isFile()) return undefined
141
+ // Wraps aren't signed and recipients are public, so a planted wrap must fail quietly.
142
+ const key = await unseal([holderKey.identity], readFileSync(path))
143
+ .then((bytes) => decodeSecretKey(new TextDecoder().decode(bytes)))
144
+ .catch((error: unknown) => {
145
+ if (error instanceof TypeVaultError) return undefined
146
+ throw error
147
+ })
148
+ if (key === undefined) return undefined
149
+ return samePublic(await publicKeyOf(key), expected) ? key : undefined
150
+ }
@@ -1,20 +1,36 @@
1
- import { homedir } from 'node:os'
2
- import { join } from 'node:path'
1
+ import { existsSync, realpathSync } from 'node:fs'
2
+ import { homedir, hostname } from 'node:os'
3
+ import { dirname, join, resolve } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import { sha256Hex } from './crypto'
8
+ import { utf8 } from './encoding'
9
+ import { readJsonFile } from './json-file'
3
10
 
4
11
  export type Layout = {
12
+ /** `global`: one vault per user, `~/.typevault/`. `local`: a `.typevault/` committed in a project. */
13
+ readonly scope: 'global' | 'local'
14
+ /** Private state (trust pin, audit, run): `TYPEVAULT_STATE_DIR`, else this checkout's. Never committed. */
5
15
  readonly root: string
16
+ /** The committable part: ciphertext and signed manifests only. */
6
17
  readonly vault: string
7
18
  readonly entries: string
8
- readonly groupsDir: string
9
- readonly operatorFile: string
10
- readonly groupsFile: string
19
+ readonly tiersDir: string
20
+ readonly ownerFile: string
21
+ readonly tiersFile: string
22
+ readonly membersFile: string
23
+ /** Each human member's password-sealed key, so a new device needs only the password and Secret Key. */
24
+ readonly membersDir: string
25
+ /** The owner key wrapped to each owner member. */
26
+ readonly ownerWrapsDir: string
11
27
  readonly signersFile: string
12
28
  readonly ceilingsFile: string
29
+ /** This checkout's audit anchors: one committed file per audit chain, so clones never check each other's. */
13
30
  readonly anchorsFile: string
31
+ /** Anchors from before chains had their own file; still checked against this checkout's log. */
32
+ readonly legacyAnchorsFile: string
14
33
  readonly txnDir: string
15
- readonly keys: string
16
- readonly operatorKey: string
17
- readonly groupKeys: string
18
34
  readonly trustFile: string
19
35
  readonly audit: string
20
36
  readonly auditLog: string
@@ -22,48 +38,149 @@ export type Layout = {
22
38
  readonly lockFile: string
23
39
  readonly auditLock: string
24
40
  readonly grantsFile: string
41
+ /** Held by the daemon from start until its cleanup is done: whether a daemon is still here, without PIDs. */
42
+ readonly daemonLock: string
43
+ /** Which machine's daemon holds `daemonLock` (host id, pid, heartbeat), for openers flock can't reach. */
44
+ readonly daemonHolder: string
45
+ /** Where the sockets live: `TYPEVAULT_RUN_DIR`, else `run`. */
46
+ readonly sockets: string
47
+ /** The unlocked session's grant token, readable only by this user while the daemon runs. */
48
+ readonly sessionFile: string
25
49
  readonly revisionsFile: string
26
50
  readonly agentSocket: string
27
51
  readonly adminSocket: (ceiling: string) => string
52
+ /** Host-only: how `stopDaemon` stops the daemon where there is no SIGTERM (Windows). Never mounted into a sandbox. */
53
+ readonly controlSocket: string
28
54
  }
29
55
 
30
- /** `TYPEVAULT_DIR`, else `$XDG_CONFIG_HOME/typevault`, else `~/.config/typevault`. */
31
- export function resolveRoot(env: Readonly<Record<string, string | undefined>> = process.env): string {
32
- const explicit = env['TYPEVAULT_DIR']
33
- if (explicit !== undefined && explicit !== '') return explicit
56
+ type Env = Readonly<Record<string, string | undefined>>
57
+
58
+ /** The directory a project vault lives in, next to the project's files. */
59
+ export const LOCAL_VAULT_DIR = '.typevault'
60
+
61
+ /**
62
+ * `$XDG_CONFIG_HOME/typevault`, else `~/.config/typevault`: this device's identity and every vault's private state,
63
+ * never any vault itself.
64
+ */
65
+ export function configDir(env: Env = process.env): string {
34
66
  const xdg = env['XDG_CONFIG_HOME']
35
- return join(xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.config'), 'typevault')
67
+ return join(xdg !== undefined && xdg !== '' ? xdg : join(home(env), '.config'), 'typevault')
68
+ }
69
+
70
+ /** `TYPEVAULT_DIR`, else `~/.typevault`. */
71
+ export function globalVaultDir(env: Env = process.env): string {
72
+ const explicit = env['TYPEVAULT_DIR']
73
+ return explicit !== undefined && explicit !== '' ? explicit : join(home(env), LOCAL_VAULT_DIR)
74
+ }
75
+
76
+ function home(env: Env): string {
77
+ const explicit = env['HOME']
78
+ return explicit !== undefined && explicit !== '' ? explicit : homedir()
79
+ }
80
+
81
+ /** The global vault: laid out like a project vault, its private state kept the same way. */
82
+ export const globalLayout = (env: Env = process.env): Layout => vaultLayout('global', globalVaultDir(env), env)
83
+
84
+ /** A project vault at `dir`. */
85
+ export const localLayout = (dir: string, env: Env = process.env): Layout => vaultLayout('local', dir, env)
86
+
87
+ const setting = (env: Env, name: string): string | undefined => {
88
+ const value = env[name]
89
+ return value !== undefined && value !== '' ? resolve(value) : undefined
90
+ }
91
+
92
+ /** This machine, as daemon holders and audit anchors name it: `TYPEVAULT_HOST_ID`, else the hostname. */
93
+ export function hostId(env: Env = process.env): string {
94
+ const explicit = env['TYPEVAULT_HOST_ID']
95
+ return explicit !== undefined && explicit !== '' ? explicit : hostname()
96
+ }
97
+
98
+ /**
99
+ * Trust, audit and run state belong to this checkout (keyed by its path), so a replaced owner.json still meets the
100
+ * old pin and two clones never share a daemon or a transaction journal. `TYPEVAULT_STATE_DIR` names that state
101
+ * directly instead: every opener given it acts as one checkout, whatever path or home it reaches the vault through.
102
+ */
103
+ function vaultLayout(scope: Layout['scope'], dir: string, env: Env): Layout {
104
+ const stateDir = setting(env, 'TYPEVAULT_STATE_DIR')
105
+ const root = stateDir ?? join(configDir(env), 'checkouts', shortHash(resolve(dir)))
106
+ // Without a state directory, a chain is named by where its log lives. With one, it is the vault's single chain,
107
+ // named by its owner key: nothing kept in the state directory can be lost or swapped to escape its anchors.
108
+ const chain =
109
+ stateDir === undefined
110
+ ? () => shortHash(`${hostId(env)}\0${root}`)
111
+ : () => `state-${vaultIdOf(ownerSignPublic(dir))}`
112
+ return build(scope, root, dir, setting(env, 'TYPEVAULT_RUN_DIR'), chain)
113
+ }
114
+
115
+ function ownerSignPublic(vault: string): string {
116
+ return readJsonFile(join(vault, 'owner.json'), z.object({ signPublic: z.string() })).signPublic
117
+ }
118
+
119
+ // A home directory reached through a symlink (macOS's /tmp, say) is still the same directory.
120
+ const canonical = (path: string): string => (existsSync(path) ? realpathSync(path) : resolve(path))
121
+
122
+ const shortHash = (value: string): string => sha256Hex(utf8(value)).slice(0, 16)
123
+
124
+ /** A vault's id, derived from its owner key. */
125
+ export const vaultIdOf = (ownerSignPublic: string): string => shortHash(ownerSignPublic)
126
+
127
+ /**
128
+ * The nearest `.typevault/` holding an initialized vault, from `from` up to the filesystem root. The global vault is
129
+ * one too, in the home directory, but it is never taken for a project's.
130
+ */
131
+ export function findLocalVault(from: string, env: Env = process.env): string | undefined {
132
+ const global = canonical(globalVaultDir(env))
133
+ for (let dir = from; ; dir = dirname(dir)) {
134
+ const candidate = join(dir, LOCAL_VAULT_DIR)
135
+ if (existsSync(join(candidate, 'owner.json')) && canonical(candidate) !== global) return candidate
136
+ if (dirname(dir) === dir) return undefined
137
+ }
36
138
  }
37
139
 
38
- export function layoutOf(root: string): Layout {
39
- const vault = join(root, 'vault')
40
- const keys = join(root, 'keys')
140
+ function build(
141
+ scope: Layout['scope'],
142
+ root: string,
143
+ vault: string,
144
+ runDir: string | undefined,
145
+ chain: () => string,
146
+ ): Layout {
41
147
  const audit = join(root, 'audit')
42
148
  const run = join(root, 'run')
149
+ const sockets = runDir ?? run
43
150
  return {
151
+ scope,
44
152
  root,
45
153
  vault,
46
154
  entries: join(vault, 'entries'),
47
- groupsDir: join(vault, 'groups'),
48
- operatorFile: join(vault, 'operator.json'),
49
- groupsFile: join(vault, 'groups.json'),
155
+ tiersDir: join(vault, 'tiers'),
156
+ ownerFile: join(vault, 'owner.json'),
157
+ tiersFile: join(vault, 'tiers.json'),
158
+ membersFile: join(vault, 'members.json'),
159
+ membersDir: join(vault, 'members'),
160
+ ownerWrapsDir: join(vault, 'owner'),
50
161
  signersFile: join(vault, 'signers.json'),
51
162
  ceilingsFile: join(vault, 'ceilings.json'),
52
- anchorsFile: join(vault, 'audit-anchors.jsonl'),
163
+ // Never named by the log itself: a log rewritten from its first record keeps its anchors.
164
+ get anchorsFile() {
165
+ return join(vault, 'audit-anchors', `${chain()}.jsonl`)
166
+ },
167
+ legacyAnchorsFile: join(vault, 'audit-anchors.jsonl'),
53
168
  // Staging lives in run/, which is never committed: a txn dir from git must not be able to steer deletes.
54
169
  txnDir: join(run, 'txn'),
55
- keys,
56
- operatorKey: join(keys, 'operator.key'),
57
- groupKeys: join(keys, 'groups'),
58
- trustFile: join(keys, 'trust.json'),
170
+ trustFile: join(root, 'trust.json'),
59
171
  audit,
60
172
  auditLog: join(audit, 'log.jsonl'),
61
173
  run,
62
174
  lockFile: join(run, 'lock'),
63
175
  auditLock: join(run, 'audit.lock'),
64
176
  grantsFile: join(run, 'grants.json'),
177
+ daemonLock: join(run, 'daemon.lock'),
178
+ daemonHolder: join(run, 'daemon.holder'),
179
+ sockets,
180
+ sessionFile: join(run, 'session.token'),
65
181
  revisionsFile: join(run, 'revisions.json'),
66
- agentSocket: join(run, 'agent.sock'),
67
- adminSocket: (ceiling: string) => join(run, `admin-${ceiling}.sock`),
182
+ agentSocket: join(sockets, 'agent.sock'),
183
+ adminSocket: (ceiling: string) => join(sockets, `admin-${ceiling}.sock`),
184
+ controlSocket: join(sockets, 'control.sock'),
68
185
  }
69
186
  }
package/src/core/lock.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { dlopen, FFIType } from 'bun:ffi'
1
+ import { dlopen, FFIType, ptr } from 'bun:ffi'
2
2
  import { AsyncLocalStorage } from 'node:async_hooks'
3
3
  import { closeSync, openSync } from 'node:fs'
4
4
  import { dirname } from 'node:path'
@@ -6,32 +6,115 @@ import { dirname } from 'node:path'
6
6
  import { TypeVaultError } from './errors'
7
7
  import { ensureDir } from './fsx'
8
8
 
9
- const LOCK_SH = 1
10
- const LOCK_EX = 2
11
- const LOCK_NB = 4
12
- const LOCK_UN = 8
13
9
  const RETRY_MS = 10
14
10
  const TIMEOUT_MS = 30_000
15
11
 
16
- const libc = dlopen(process.platform === 'darwin' ? '/usr/lib/libSystem.B.dylib' : 'libc.so.6', {
17
- flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
18
- })
19
-
20
12
  export type LockMode = 'shared' | 'exclusive'
21
13
 
14
+ /**
15
+ * An advisory whole-file lock the OS drops when its holder exits, however it exits: flock on Unix, LockFileEx on
16
+ * Windows. Each open handle locks on its own, so two handles in one process conflict like two processes would.
17
+ */
18
+ type FileLocks = {
19
+ /** Opens `path` for locking, creating it unless `existing`; undefined when `existing` and it isn't there. */
20
+ readonly open: (path: string, existing: boolean) => number | undefined
21
+ readonly tryLock: (handle: number, mode: LockMode) => boolean
22
+ readonly unlock: (handle: number) => void
23
+ readonly close: (handle: number) => void
24
+ }
25
+
26
+ function posixLocks(): FileLocks {
27
+ const LOCK_SH = 1
28
+ const LOCK_EX = 2
29
+ const LOCK_NB = 4
30
+ const LOCK_UN = 8
31
+ const libc = dlopen(process.platform === 'darwin' ? '/usr/lib/libSystem.B.dylib' : 'libc.so.6', {
32
+ flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
33
+ })
34
+ return {
35
+ open: (path, existing) => {
36
+ try {
37
+ return openSync(path, existing ? 'r' : 'a', 0o600)
38
+ } catch (error) {
39
+ if (existing && error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
40
+ throw error
41
+ }
42
+ },
43
+ tryLock: (fd, mode) => libc.symbols.flock(fd, (mode === 'exclusive' ? LOCK_EX : LOCK_SH) | LOCK_NB) === 0,
44
+ unlock: (fd) => void libc.symbols.flock(fd, LOCK_UN),
45
+ close: closeSync,
46
+ }
47
+ }
48
+
49
+ function windowsLocks(): FileLocks {
50
+ const GENERIC_READ_WRITE = 0xc0000000
51
+ const FILE_SHARE_ALL = 0x7 // read | write | delete: the lock, not the open, is what excludes
52
+ const OPEN_EXISTING = 3
53
+ const OPEN_ALWAYS = 4
54
+ const FILE_ATTRIBUTE_NORMAL = 0x80
55
+ const INVALID_HANDLE_VALUE = -1
56
+ const LOCKFILE_FAIL_IMMEDIATELY = 0x1
57
+ const LOCKFILE_EXCLUSIVE_LOCK = 0x2
58
+ const ERROR_FILE_NOT_FOUND = 2
59
+ const ERROR_PATH_NOT_FOUND = 3
60
+ const handle = FFIType.i64_fast
61
+ const kernel32 = dlopen('kernel32.dll', {
62
+ CreateFileW: {
63
+ args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.u32, handle],
64
+ returns: handle,
65
+ },
66
+ LockFileEx: {
67
+ args: [handle, FFIType.u32, FFIType.u32, FFIType.u32, FFIType.u32, FFIType.ptr],
68
+ returns: FFIType.i32,
69
+ },
70
+ UnlockFileEx: { args: [handle, FFIType.u32, FFIType.u32, FFIType.u32, FFIType.ptr], returns: FFIType.i32 },
71
+ CloseHandle: { args: [handle], returns: FFIType.i32 },
72
+ GetLastError: { args: [], returns: FFIType.u32 },
73
+ })
74
+ const { CreateFileW, LockFileEx, UnlockFileEx, CloseHandle, GetLastError } = kernel32.symbols
75
+ // A zeroed OVERLAPPED (32 bytes on 64-bit): the locked range starts at offset 0. One byte stands for the whole file.
76
+ const overlapped = () => ptr(new Uint8Array(32))
77
+ return {
78
+ open: (path, existing) => {
79
+ const wide = Buffer.from(`${path}\0`, 'utf16le')
80
+ const disposition = existing ? OPEN_EXISTING : OPEN_ALWAYS
81
+ const h = Number(
82
+ CreateFileW(ptr(wide), GENERIC_READ_WRITE, FILE_SHARE_ALL, null, disposition, FILE_ATTRIBUTE_NORMAL, 0),
83
+ )
84
+ if (h !== INVALID_HANDLE_VALUE) return h
85
+ const code = GetLastError()
86
+ if (existing && (code === ERROR_FILE_NOT_FOUND || code === ERROR_PATH_NOT_FOUND)) return undefined
87
+ throw new TypeVaultError('unavailable', `cannot open the lock file ${path} (Windows error ${code})`)
88
+ },
89
+ tryLock: (h, mode) => {
90
+ const flags = LOCKFILE_FAIL_IMMEDIATELY | (mode === 'exclusive' ? LOCKFILE_EXCLUSIVE_LOCK : 0)
91
+ return LockFileEx(h, flags, 0, 1, 0, overlapped()) !== 0
92
+ },
93
+ unlock: (h) => void UnlockFileEx(h, 0, 1, 0, overlapped()),
94
+ close: (h) => void CloseHandle(h),
95
+ }
96
+ }
97
+
98
+ const locks = process.platform === 'win32' ? windowsLocks() : posixLocks()
99
+
22
100
  /** Locks held by the current async call chain, so nested calls re-enter instead of deadlocking. */
23
101
  const owned = new AsyncLocalStorage<ReadonlyMap<string, LockMode>>()
24
102
  /** In-process queue per lock file: flock alone can't separate two concurrent requests in one daemon. */
25
103
  const tails = new Map<string, Promise<void>>()
26
104
 
27
- async function acquire(path: string, mode: LockMode): Promise<number> {
105
+ function openForLock(path: string): number {
28
106
  ensureDir(dirname(path), 0o700)
29
- const fd = openSync(path, 'a', 0o600)
30
- const operation = (mode === 'exclusive' ? LOCK_EX : LOCK_SH) | LOCK_NB
107
+ const handle = locks.open(path, false)
108
+ if (handle === undefined) throw new TypeVaultError('unavailable', `cannot open the lock file ${path}`)
109
+ return handle
110
+ }
111
+
112
+ async function acquire(path: string, mode: LockMode): Promise<number> {
113
+ const fd = openForLock(path)
31
114
  const deadline = Date.now() + TIMEOUT_MS
32
- while (libc.symbols.flock(fd, operation) !== 0) {
115
+ while (!locks.tryLock(fd, mode)) {
33
116
  if (Date.now() > deadline) {
34
- closeSync(fd)
117
+ locks.close(fd)
35
118
  throw new TypeVaultError('locked', `timed out waiting for the vault lock at ${path}`)
36
119
  }
37
120
  await Bun.sleep(RETRY_MS)
@@ -39,6 +122,35 @@ async function acquire(path: string, mode: LockMode): Promise<number> {
39
122
  return fd
40
123
  }
41
124
 
125
+ /**
126
+ * Takes an exclusive flock on `path` without waiting, and returns its release, or undefined when another holder has
127
+ * it. Held for as long as the holder lives: the kernel drops it when the process exits, however it exits.
128
+ */
129
+ export function holdLock(path: string): (() => void) | undefined {
130
+ const fd = openForLock(path)
131
+ if (!locks.tryLock(fd, 'exclusive')) {
132
+ locks.close(fd)
133
+ return undefined
134
+ }
135
+ return () => {
136
+ locks.unlock(fd)
137
+ locks.close(fd)
138
+ }
139
+ }
140
+
141
+ /** Whether some holder has `path` locked right now. A lock that can't be tested counts as held. */
142
+ export function isLockHeld(path: string): boolean {
143
+ const fd = locks.open(path, true)
144
+ if (fd === undefined) return false
145
+ try {
146
+ if (!locks.tryLock(fd, 'exclusive')) return true
147
+ locks.unlock(fd)
148
+ return false
149
+ } finally {
150
+ locks.close(fd)
151
+ }
152
+ }
153
+
42
154
  /**
43
155
  * Runs `fn` under a cross-process flock: shared for readers, exclusive for writers.
44
156
  * Within one process, callers are serialized. The kernel drops the lock if the process dies,
@@ -63,8 +175,8 @@ export async function withLock<T>(path: string, mode: LockMode, fn: () => Promis
63
175
  try {
64
176
  return await owned.run(new Map([...(mine ?? []), [path, mode]]), fn)
65
177
  } finally {
66
- libc.symbols.flock(fd, LOCK_UN)
67
- closeSync(fd)
178
+ locks.unlock(fd)
179
+ locks.close(fd)
68
180
  }
69
181
  } finally {
70
182
  release()