typevault 0.1.0 → 0.2.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.
- package/README.md +156 -115
- package/package.json +14 -2
- package/src/access/env.ts +77 -17
- package/src/access/keys.ts +14 -14
- package/src/access/schemas.ts +6 -12
- package/src/access/scope.ts +7 -7
- package/src/access/scoped.ts +100 -44
- package/src/access/sealed-access.ts +45 -23
- package/src/access/sealed.ts +33 -21
- package/src/access/types.ts +25 -30
- package/src/admin.ts +68 -0
- package/src/audit/log.ts +14 -9
- package/src/cli/commands/admin.ts +87 -47
- package/src/cli/commands/daemon.ts +33 -15
- package/src/cli/commands/entries.ts +166 -55
- package/src/cli/commands/grant.ts +12 -20
- package/src/cli/commands/members.ts +281 -0
- package/src/cli/commands/run.ts +61 -24
- package/src/cli/context.ts +155 -15
- package/src/cli/index.ts +27 -4
- package/src/cli/password.ts +74 -0
- package/src/cli/web-prompt.ts +65 -0
- package/src/core/admin.ts +125 -74
- package/src/core/adopt.ts +40 -9
- package/src/core/crypto.ts +6 -4
- package/src/core/doctor.ts +9 -9
- package/src/core/entries.ts +66 -52
- package/src/core/errors.ts +6 -0
- package/src/core/fsx.ts +7 -3
- package/src/core/holder.ts +84 -0
- package/src/core/identity.ts +130 -0
- package/src/core/init.ts +73 -23
- package/src/core/keyring.ts +100 -56
- package/src/core/layout.ts +145 -26
- package/src/core/lock.ts +128 -16
- package/src/core/naming.ts +146 -49
- package/src/core/password.ts +111 -0
- package/src/core/payload.ts +42 -38
- package/src/core/revisions.ts +8 -4
- package/src/core/rotate.ts +59 -42
- package/src/core/state.ts +88 -48
- package/src/core/txn.ts +5 -4
- package/src/core/vault.ts +108 -46
- package/src/core/worktrees.ts +39 -0
- package/src/daemon/admin-routes.ts +33 -21
- package/src/daemon/agent-routes.ts +29 -11
- package/src/daemon/client.ts +15 -0
- package/src/daemon/daemon.ts +210 -32
- package/src/daemon/grants.ts +21 -4
- package/src/daemon/http.ts +3 -0
- package/src/daemon/live-access.ts +4 -4
- package/src/daemon/protocol.ts +17 -12
- package/src/daemon/requests.ts +17 -22
- package/src/daemon/spawn.ts +188 -9
- package/src/export/1password.ts +157 -0
- package/src/import/1password-live.ts +399 -0
- package/src/import/1password.ts +26 -5
- package/src/import/bitwarden.ts +3 -3
- package/src/import/csv.ts +1 -1
- package/src/import/dotenv.ts +2 -2
- package/src/import/index.ts +1 -0
- package/src/import/keepass.ts +2 -2
- package/src/import/lastpass.ts +2 -2
- package/src/import/shared.ts +67 -10
- package/src/import/typeclaw.ts +2 -2
- package/src/import/types.ts +1 -1
- package/src/index.ts +58 -0
- package/src/owner.ts +156 -0
- package/src/prompt/browser.ts +48 -15
- package/src/prompt/page.ts +19 -11
- package/src/prompt/styles.ts +64 -34
- package/src/prompt/types.ts +3 -3
package/src/core/keyring.ts
CHANGED
|
@@ -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: '
|
|
12
|
-
| { readonly kind: '
|
|
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
|
|
15
|
-
export
|
|
16
|
-
join('
|
|
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
|
-
|
|
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
|
|
32
|
-
return this.#keys.find((key) => key.role.kind === '
|
|
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 `
|
|
36
|
-
unlock(
|
|
37
|
-
const cached = this.#cache.get(
|
|
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(
|
|
40
|
-
this.#cache.set(
|
|
82
|
+
const pending = this.#resolve(tier)
|
|
83
|
+
this.#cache.set(tier, pending)
|
|
41
84
|
return pending
|
|
42
85
|
}
|
|
43
86
|
|
|
44
|
-
async
|
|
45
|
-
const names = Object.keys(this.#state.
|
|
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(
|
|
53
|
-
const meta = this.#state.
|
|
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 === '
|
|
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
|
|
60
|
-
if (
|
|
61
|
-
const key = await this.#openWrap(
|
|
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.
|
|
65
|
-
const includerGen = this.#state.
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
holder
|
|
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
|
+
}
|
package/src/core/layout.ts
CHANGED
|
@@ -1,20 +1,34 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
2
|
+
import { homedir, hostname } from 'node:os'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { sha256Hex } from './crypto'
|
|
6
|
+
import { utf8 } from './encoding'
|
|
7
|
+
import { TypeVaultError } from './errors'
|
|
3
8
|
|
|
4
9
|
export type Layout = {
|
|
10
|
+
/** `global`: one vault per user, `~/.typevault/`. `local`: a `.typevault/` committed in a project. */
|
|
11
|
+
readonly scope: 'global' | 'local'
|
|
12
|
+
/** Private state (trust pin, audit, run): `TYPEVAULT_STATE_DIR`, else this checkout's. Never committed. */
|
|
5
13
|
readonly root: string
|
|
14
|
+
/** The committable part: ciphertext and signed manifests only. */
|
|
6
15
|
readonly vault: string
|
|
7
16
|
readonly entries: string
|
|
8
|
-
readonly
|
|
9
|
-
readonly
|
|
10
|
-
readonly
|
|
17
|
+
readonly tiersDir: string
|
|
18
|
+
readonly ownerFile: string
|
|
19
|
+
readonly tiersFile: string
|
|
20
|
+
readonly membersFile: string
|
|
21
|
+
/** Each human member's password-sealed key, so a new device needs only the password and Secret Key. */
|
|
22
|
+
readonly membersDir: string
|
|
23
|
+
/** The owner key wrapped to each owner member. */
|
|
24
|
+
readonly ownerWrapsDir: string
|
|
11
25
|
readonly signersFile: string
|
|
12
26
|
readonly ceilingsFile: string
|
|
27
|
+
/** This checkout's audit anchors: one committed file per audit chain, so clones never check each other's. */
|
|
13
28
|
readonly anchorsFile: string
|
|
29
|
+
/** Anchors from before chains had their own file; still checked against this checkout's log. */
|
|
30
|
+
readonly legacyAnchorsFile: string
|
|
14
31
|
readonly txnDir: string
|
|
15
|
-
readonly keys: string
|
|
16
|
-
readonly operatorKey: string
|
|
17
|
-
readonly groupKeys: string
|
|
18
32
|
readonly trustFile: string
|
|
19
33
|
readonly audit: string
|
|
20
34
|
readonly auditLog: string
|
|
@@ -22,48 +36,153 @@ export type Layout = {
|
|
|
22
36
|
readonly lockFile: string
|
|
23
37
|
readonly auditLock: string
|
|
24
38
|
readonly grantsFile: string
|
|
39
|
+
/** Held by the daemon from start until its cleanup is done: whether a daemon is still here, without PIDs. */
|
|
40
|
+
readonly daemonLock: string
|
|
41
|
+
/** Which machine's daemon holds `daemonLock` (host id, pid, heartbeat), for openers flock can't reach. */
|
|
42
|
+
readonly daemonHolder: string
|
|
43
|
+
/** Where the sockets live: `TYPEVAULT_RUN_DIR`, else `run`. */
|
|
44
|
+
readonly sockets: string
|
|
45
|
+
/** The unlocked session's grant token, readable only by this user while the daemon runs. */
|
|
46
|
+
readonly sessionFile: string
|
|
25
47
|
readonly revisionsFile: string
|
|
26
48
|
readonly agentSocket: string
|
|
27
49
|
readonly adminSocket: (ceiling: string) => string
|
|
50
|
+
/** Host-only: how `stopDaemon` stops the daemon where there is no SIGTERM (Windows). Never mounted into a sandbox. */
|
|
51
|
+
readonly controlSocket: string
|
|
28
52
|
}
|
|
29
53
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
54
|
+
type Env = Readonly<Record<string, string | undefined>>
|
|
55
|
+
|
|
56
|
+
/** The directory a project vault lives in, next to the project's files. */
|
|
57
|
+
export const LOCAL_VAULT_DIR = '.typevault'
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* `$XDG_CONFIG_HOME/typevault`, else `~/.config/typevault`: this device's identity and every vault's private state,
|
|
61
|
+
* never any vault itself.
|
|
62
|
+
*/
|
|
63
|
+
export function configDir(env: Env = process.env): string {
|
|
34
64
|
const xdg = env['XDG_CONFIG_HOME']
|
|
35
|
-
return join(xdg !== undefined && xdg !== '' ? xdg : join(
|
|
65
|
+
return join(xdg !== undefined && xdg !== '' ? xdg : join(home(env), '.config'), 'typevault')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `TYPEVAULT_DIR`, else `~/.typevault`. */
|
|
69
|
+
export function globalVaultDir(env: Env = process.env): string {
|
|
70
|
+
const explicit = env['TYPEVAULT_DIR']
|
|
71
|
+
return explicit !== undefined && explicit !== '' ? explicit : join(home(env), LOCAL_VAULT_DIR)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function home(env: Env): string {
|
|
75
|
+
const explicit = env['HOME']
|
|
76
|
+
return explicit !== undefined && explicit !== '' ? explicit : homedir()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The global vault: laid out like a project vault, its private state kept the same way. */
|
|
80
|
+
export const globalLayout = (env: Env = process.env): Layout => vaultLayout('global', globalVaultDir(env), env)
|
|
81
|
+
|
|
82
|
+
/** A project vault at `dir`. */
|
|
83
|
+
export const localLayout = (dir: string, env: Env = process.env): Layout => vaultLayout('local', dir, env)
|
|
84
|
+
|
|
85
|
+
const setting = (env: Env, name: string): string | undefined => {
|
|
86
|
+
const value = env[name]
|
|
87
|
+
return value !== undefined && value !== '' ? resolve(value) : undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** This machine, as daemon holders and audit anchors name it: `TYPEVAULT_HOST_ID`, else the hostname. */
|
|
91
|
+
export function hostId(env: Env = process.env): string {
|
|
92
|
+
const explicit = env['TYPEVAULT_HOST_ID']
|
|
93
|
+
return explicit !== undefined && explicit !== '' ? explicit : hostname()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Trust, audit and run state belong to this checkout (keyed by its path), so a replaced owner.json still meets the
|
|
98
|
+
* old pin and two clones never share a daemon or a transaction journal. `TYPEVAULT_STATE_DIR` names that state
|
|
99
|
+
* directly instead: every opener given it acts as one checkout, whatever path or home it reaches the vault through.
|
|
100
|
+
*/
|
|
101
|
+
function vaultLayout(scope: Layout['scope'], dir: string, env: Env): Layout {
|
|
102
|
+
const stateDir = setting(env, 'TYPEVAULT_STATE_DIR')
|
|
103
|
+
const root = stateDir ?? join(configDir(env), 'checkouts', shortHash(resolve(dir)))
|
|
104
|
+
// Without a state directory, a chain is named by where its log lives. With one, it is the vault's single chain,
|
|
105
|
+
// named by its owner key: nothing kept in the state directory can be lost or swapped to escape its anchors.
|
|
106
|
+
const chain =
|
|
107
|
+
stateDir === undefined
|
|
108
|
+
? () => shortHash(`${hostId(env)}\0${root}`)
|
|
109
|
+
: () => `state-${vaultIdOf(ownerSignPublic(dir))}`
|
|
110
|
+
return build(scope, root, dir, setting(env, 'TYPEVAULT_RUN_DIR'), chain)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function ownerSignPublic(vault: string): string {
|
|
114
|
+
const owner: unknown = JSON.parse(readFileSync(join(vault, 'owner.json'), 'utf8'))
|
|
115
|
+
if (typeof owner !== 'object' || owner === null || !('signPublic' in owner) || typeof owner.signPublic !== 'string') {
|
|
116
|
+
throw new TypeVaultError('tampered', `${join(vault, 'owner.json')} is malformed`)
|
|
117
|
+
}
|
|
118
|
+
return owner.signPublic
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// A home directory reached through a symlink (macOS's /tmp, say) is still the same directory.
|
|
122
|
+
const canonical = (path: string): string => (existsSync(path) ? realpathSync(path) : resolve(path))
|
|
123
|
+
|
|
124
|
+
const shortHash = (value: string): string => sha256Hex(utf8(value)).slice(0, 16)
|
|
125
|
+
|
|
126
|
+
/** A vault's id, derived from its owner key. */
|
|
127
|
+
export const vaultIdOf = (ownerSignPublic: string): string => shortHash(ownerSignPublic)
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The nearest `.typevault/` holding an initialized vault, from `from` up to the filesystem root. The global vault is
|
|
131
|
+
* one too, in the home directory, but it is never taken for a project's.
|
|
132
|
+
*/
|
|
133
|
+
export function findLocalVault(from: string, env: Env = process.env): string | undefined {
|
|
134
|
+
const global = canonical(globalVaultDir(env))
|
|
135
|
+
for (let dir = from; ; dir = dirname(dir)) {
|
|
136
|
+
const candidate = join(dir, LOCAL_VAULT_DIR)
|
|
137
|
+
if (existsSync(join(candidate, 'owner.json')) && canonical(candidate) !== global) return candidate
|
|
138
|
+
if (dirname(dir) === dir) return undefined
|
|
139
|
+
}
|
|
36
140
|
}
|
|
37
141
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
142
|
+
function build(
|
|
143
|
+
scope: Layout['scope'],
|
|
144
|
+
root: string,
|
|
145
|
+
vault: string,
|
|
146
|
+
runDir: string | undefined,
|
|
147
|
+
chain: () => string,
|
|
148
|
+
): Layout {
|
|
41
149
|
const audit = join(root, 'audit')
|
|
42
150
|
const run = join(root, 'run')
|
|
151
|
+
const sockets = runDir ?? run
|
|
43
152
|
return {
|
|
153
|
+
scope,
|
|
44
154
|
root,
|
|
45
155
|
vault,
|
|
46
156
|
entries: join(vault, 'entries'),
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
157
|
+
tiersDir: join(vault, 'tiers'),
|
|
158
|
+
ownerFile: join(vault, 'owner.json'),
|
|
159
|
+
tiersFile: join(vault, 'tiers.json'),
|
|
160
|
+
membersFile: join(vault, 'members.json'),
|
|
161
|
+
membersDir: join(vault, 'members'),
|
|
162
|
+
ownerWrapsDir: join(vault, 'owner'),
|
|
50
163
|
signersFile: join(vault, 'signers.json'),
|
|
51
164
|
ceilingsFile: join(vault, 'ceilings.json'),
|
|
52
|
-
|
|
165
|
+
// Never named by the log itself: a log rewritten from its first record keeps its anchors.
|
|
166
|
+
get anchorsFile() {
|
|
167
|
+
return join(vault, 'audit-anchors', `${chain()}.jsonl`)
|
|
168
|
+
},
|
|
169
|
+
legacyAnchorsFile: join(vault, 'audit-anchors.jsonl'),
|
|
53
170
|
// Staging lives in run/, which is never committed: a txn dir from git must not be able to steer deletes.
|
|
54
171
|
txnDir: join(run, 'txn'),
|
|
55
|
-
|
|
56
|
-
operatorKey: join(keys, 'operator.key'),
|
|
57
|
-
groupKeys: join(keys, 'groups'),
|
|
58
|
-
trustFile: join(keys, 'trust.json'),
|
|
172
|
+
trustFile: join(root, 'trust.json'),
|
|
59
173
|
audit,
|
|
60
174
|
auditLog: join(audit, 'log.jsonl'),
|
|
61
175
|
run,
|
|
62
176
|
lockFile: join(run, 'lock'),
|
|
63
177
|
auditLock: join(run, 'audit.lock'),
|
|
64
178
|
grantsFile: join(run, 'grants.json'),
|
|
179
|
+
daemonLock: join(run, 'daemon.lock'),
|
|
180
|
+
daemonHolder: join(run, 'daemon.holder'),
|
|
181
|
+
sockets,
|
|
182
|
+
sessionFile: join(run, 'session.token'),
|
|
65
183
|
revisionsFile: join(run, 'revisions.json'),
|
|
66
|
-
agentSocket: join(
|
|
67
|
-
adminSocket: (ceiling: string) => join(
|
|
184
|
+
agentSocket: join(sockets, 'agent.sock'),
|
|
185
|
+
adminSocket: (ceiling: string) => join(sockets, `admin-${ceiling}.sock`),
|
|
186
|
+
controlSocket: join(sockets, 'control.sock'),
|
|
68
187
|
}
|
|
69
188
|
}
|
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
|
-
|
|
105
|
+
function openForLock(path: string): number {
|
|
28
106
|
ensureDir(dirname(path), 0o700)
|
|
29
|
-
const
|
|
30
|
-
|
|
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 (
|
|
115
|
+
while (!locks.tryLock(fd, mode)) {
|
|
33
116
|
if (Date.now() > deadline) {
|
|
34
|
-
|
|
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
|
-
|
|
67
|
-
|
|
178
|
+
locks.unlock(fd)
|
|
179
|
+
locks.close(fd)
|
|
68
180
|
}
|
|
69
181
|
} finally {
|
|
70
182
|
release()
|