typevault 0.2.0 → 0.4.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 +13 -12
- package/package.json +2 -2
- package/src/access/env.ts +3 -3
- package/src/access/schemas.ts +3 -1
- package/src/access/scope.ts +7 -2
- package/src/access/scoped.ts +47 -10
- package/src/access/sealed-access.ts +12 -1
- package/src/access/sealed.ts +25 -12
- package/src/access/types.ts +7 -0
- package/src/audit/log.ts +15 -4
- package/src/cli/commands/admin.ts +7 -2
- package/src/cli/commands/daemon.ts +10 -3
- package/src/cli/commands/entries.ts +21 -7
- package/src/cli/commands/grant.ts +12 -2
- package/src/cli/commands/members.ts +40 -14
- package/src/cli/commands/run.ts +141 -44
- package/src/cli/context.ts +14 -4
- package/src/cli/index.ts +6 -1
- package/src/cli/output.ts +5 -1
- package/src/cli/web-prompt.ts +28 -14
- package/src/core/admin.ts +23 -6
- package/src/core/doctor.ts +6 -7
- package/src/core/errors.ts +2 -2
- package/src/core/holder.ts +25 -9
- package/src/core/identity.ts +5 -3
- package/src/core/json-file.ts +20 -0
- package/src/core/layout.ts +51 -8
- package/src/core/naming.ts +40 -32
- package/src/core/payload.ts +7 -3
- package/src/core/revisions.ts +3 -2
- package/src/core/state.ts +16 -8
- package/src/core/txn.ts +4 -3
- package/src/core/vault.ts +45 -5
- package/src/core/version.ts +9 -0
- package/src/core/worktrees.ts +18 -6
- package/src/daemon/agent-routes.ts +80 -3
- package/src/daemon/client.ts +20 -2
- package/src/daemon/daemon.ts +9 -2
- package/src/daemon/grants.ts +4 -3
- package/src/daemon/http.ts +8 -2
- package/src/daemon/live-access.ts +19 -0
- package/src/daemon/protocol.ts +7 -0
- package/src/daemon/requests.ts +65 -36
- package/src/daemon/spawn.ts +68 -14
- package/src/import/1password-live.ts +55 -16
- package/src/import/1password.ts +6 -4
- package/src/import/bitwarden.ts +3 -8
- package/src/import/dotenv.ts +2 -1
- package/src/import/keepass.ts +4 -5
- package/src/import/lastpass.ts +0 -1
- package/src/import/shared.ts +57 -5
- package/src/import/types.ts +1 -1
- package/src/prompt/index.ts +121 -64
- package/src/prompt/page.ts +8 -0
- package/src/prompt/types.ts +4 -1
- package/src/redact/index.ts +48 -12
- package/src/redact/scrub-file.ts +15 -7
package/src/import/bitwarden.ts
CHANGED
|
@@ -6,9 +6,9 @@ import type { ImportResult } from './types'
|
|
|
6
6
|
|
|
7
7
|
const TextSchema = z.string().nullish()
|
|
8
8
|
const ItemSchema = z.object({
|
|
9
|
+
id: TextSchema,
|
|
9
10
|
type: z.number().int(),
|
|
10
11
|
name: z.string(),
|
|
11
|
-
folderId: TextSchema,
|
|
12
12
|
notes: TextSchema,
|
|
13
13
|
login: z
|
|
14
14
|
.object({
|
|
@@ -20,10 +20,7 @@ const ItemSchema = z.object({
|
|
|
20
20
|
.nullish(),
|
|
21
21
|
sshKey: z.object({ privateKey: TextSchema, publicKey: TextSchema }).nullish(),
|
|
22
22
|
})
|
|
23
|
-
const ExportSchema = z.object({
|
|
24
|
-
folders: z.array(z.object({ id: z.string(), name: z.string() })).default([]),
|
|
25
|
-
items: z.array(ItemSchema),
|
|
26
|
-
})
|
|
23
|
+
const ExportSchema = z.object({ items: z.array(ItemSchema) })
|
|
27
24
|
|
|
28
25
|
export function parseBitwarden(text: string): ImportResult {
|
|
29
26
|
const raw = parseJson(text, z.object({ encrypted: z.boolean().optional() }).passthrough(), 'Bitwarden')
|
|
@@ -31,12 +28,10 @@ export function parseBitwarden(text: string): ImportResult {
|
|
|
31
28
|
throw new TypeVaultError('invalid', 'encrypted Bitwarden exports are not supported; export unencrypted JSON')
|
|
32
29
|
}
|
|
33
30
|
const data = parseExternal(raw, ExportSchema, 'Bitwarden')
|
|
34
|
-
const folders = new Map(data.folders.map((folder) => [folder.id, folder.name]))
|
|
35
31
|
const items: ImportItem[] = []
|
|
36
32
|
const warnings: string[] = []
|
|
37
33
|
for (const item of data.items) {
|
|
38
|
-
const
|
|
39
|
-
const common = { title: item.name, ...(container === undefined ? {} : { container }) }
|
|
34
|
+
const common = { title: item.name, ...(item.id ? { source: `bitwarden:${item.id}` } : {}) }
|
|
40
35
|
switch (item.type) {
|
|
41
36
|
case 1: {
|
|
42
37
|
const url = item.login?.uris?.find((uri) => uri.uri)?.uri ?? undefined
|
package/src/import/dotenv.ts
CHANGED
|
@@ -8,8 +8,9 @@ import type { ImportResult } from './types'
|
|
|
8
8
|
const VariableSchema = z.object({ name: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), value: z.string() }).readonly()
|
|
9
9
|
|
|
10
10
|
export function parseDotenv(text: string): ImportResult {
|
|
11
|
+
const variables = new Map(parseDotenvVariables(text).map((variable) => [variable.name, variable]))
|
|
11
12
|
return collectEntries(
|
|
12
|
-
|
|
13
|
+
[...variables.values()].map(({ name, value }) => ({
|
|
13
14
|
title: name,
|
|
14
15
|
preset: 'api_key',
|
|
15
16
|
fields: { $default: value },
|
package/src/import/keepass.ts
CHANGED
|
@@ -38,9 +38,8 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
|
|
|
38
38
|
}
|
|
39
39
|
const items: ImportItem[] = []
|
|
40
40
|
const warnings: string[] = []
|
|
41
|
-
const visit = (group: KdbxGroup
|
|
41
|
+
const visit = (group: KdbxGroup) => {
|
|
42
42
|
if (group.uuid.equals(db.meta.recycleBinUuid)) return
|
|
43
|
-
const container = root ? undefined : parseExternal(group.name, z.string().optional(), 'KeePass group')
|
|
44
43
|
for (const entry of group.entries) {
|
|
45
44
|
const fields = parseExternal(
|
|
46
45
|
Object.fromEntries(
|
|
@@ -62,12 +61,12 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
|
|
|
62
61
|
? { username: fields['UserName'], password: fields['Password'], url, totp: fields['otp'] }
|
|
63
62
|
: { $default: fields['Notes'] },
|
|
64
63
|
tags: parseExternal(entry.tags, z.array(z.string()).readonly(), 'KeePass tags'),
|
|
65
|
-
|
|
64
|
+
source: `keepass:${entry.uuid.id}`,
|
|
66
65
|
...(url === undefined ? {} : { url }),
|
|
67
66
|
})
|
|
68
67
|
}
|
|
69
|
-
for (const child of group.groups) visit(child
|
|
68
|
+
for (const child of group.groups) visit(child)
|
|
70
69
|
}
|
|
71
|
-
for (const group of db.groups) visit(group
|
|
70
|
+
for (const group of db.groups) visit(group)
|
|
72
71
|
return collectEntries(items, warnings)
|
|
73
72
|
}
|
package/src/import/lastpass.ts
CHANGED
package/src/import/shared.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
|
|
3
|
+
import { sha256Hex } from '../core/crypto'
|
|
4
|
+
import { utf8 } from '../core/encoding'
|
|
3
5
|
import { TypeVaultError } from '../core/errors'
|
|
4
6
|
import {
|
|
5
7
|
isFieldName,
|
|
8
|
+
type EntryName,
|
|
6
9
|
parseEntryName,
|
|
7
|
-
slugifySegment,
|
|
8
10
|
PRESETS,
|
|
9
11
|
type Preset,
|
|
10
12
|
type Field,
|
|
@@ -15,22 +17,47 @@ import type { ImportedEntry, ImportResult } from './types'
|
|
|
15
17
|
|
|
16
18
|
export type ImportItem = {
|
|
17
19
|
readonly title: string
|
|
18
|
-
|
|
20
|
+
/** The login on the service, naming the entry's account segment. Read from the `username` field when unset. */
|
|
21
|
+
readonly login?: string
|
|
19
22
|
readonly preset: Preset
|
|
20
23
|
readonly fields: Readonly<Record<string, string | Field | undefined>>
|
|
21
24
|
readonly url?: string
|
|
22
25
|
readonly tags?: readonly string[]
|
|
23
26
|
readonly env?: string
|
|
27
|
+
/** The item's id in its password manager (`bitwarden:<id>`), when the source has stable ids. */
|
|
28
|
+
readonly source?: string
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
export function collectEntries(items: readonly ImportItem[], warnings: readonly string[] = []): ImportResult {
|
|
27
32
|
const entries: ImportedEntry[] = []
|
|
28
33
|
const messages = [...warnings]
|
|
29
34
|
const used = new Set<string>()
|
|
35
|
+
const accounts = new Map<string, string>()
|
|
36
|
+
// A login whose name mixes scripts still keeps its entries apart, under a stable stand-in, rather than taking down
|
|
37
|
+
// every item signed in with it.
|
|
38
|
+
const accountSegment = (raw: string): string => {
|
|
39
|
+
const known = accounts.get(raw)
|
|
40
|
+
if (known !== undefined) return known
|
|
41
|
+
let segment = toSegment(raw)
|
|
42
|
+
if (segment !== '' && entryNameOf(segment) === undefined) {
|
|
43
|
+
const standIn = sha256Hex(utf8(segment)).slice(0, 8)
|
|
44
|
+
messages.push(`"${raw}" makes no usable name segment; its entries use "${standIn}"`)
|
|
45
|
+
segment = standIn
|
|
46
|
+
}
|
|
47
|
+
accounts.set(raw, segment)
|
|
48
|
+
return segment
|
|
49
|
+
}
|
|
30
50
|
for (const item of items) {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
51
|
+
const title = toSegment(item.title)
|
|
52
|
+
// The account segment names the login on the service, never the password manager's vault or folder.
|
|
53
|
+
const account = accountSegment(item.login ?? loginOf(item.fields) ?? '')
|
|
54
|
+
// Collisions are checked on the canonical name, so two spellings of one name can't land on the same entry.
|
|
55
|
+
const base = entryNameOf(account === '' ? title : `${title}/${account}`)
|
|
56
|
+
if (base === undefined) {
|
|
57
|
+
messages.push(`skipped "${item.title}": its title makes no usable entry name`)
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
60
|
+
let name: string = base
|
|
34
61
|
let suffix = 2
|
|
35
62
|
while (used.has(name)) name = `${base}-${suffix++}`
|
|
36
63
|
used.add(name)
|
|
@@ -68,12 +95,37 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
|
|
|
68
95
|
fields,
|
|
69
96
|
tags: item.tags ?? [],
|
|
70
97
|
...(origin === undefined ? {} : { origin }),
|
|
98
|
+
...(item.source === undefined ? {} : { source: item.source }),
|
|
71
99
|
...(item.env === undefined ? {} : { env: item.env }),
|
|
72
100
|
})
|
|
73
101
|
}
|
|
74
102
|
return { entries, warnings: messages }
|
|
75
103
|
}
|
|
76
104
|
|
|
105
|
+
export function loginOf(fields: ImportItem['fields']): string | undefined {
|
|
106
|
+
const username = fields['username']
|
|
107
|
+
return typeof username === 'string' || username === undefined ? username : fieldStrings(username)[0]
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A title or login as a name segment: lowercase, with each run of spaces and other punctuation one `-`. */
|
|
111
|
+
const toSegment = (raw: string): string =>
|
|
112
|
+
raw
|
|
113
|
+
.toLowerCase()
|
|
114
|
+
.normalize('NFC')
|
|
115
|
+
.replace(/[^\p{L}\p{M}\p{N}.@+]+/gu, '-')
|
|
116
|
+
.replace(/[.-]*-[.-]*/g, '-')
|
|
117
|
+
.replace(/\.{2,}/g, '.')
|
|
118
|
+
.replace(/^[.-]+|[.-]+$/g, '')
|
|
119
|
+
|
|
120
|
+
function entryNameOf(name: string): EntryName | undefined {
|
|
121
|
+
try {
|
|
122
|
+
return parseEntryName(name)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof TypeVaultError) return undefined
|
|
125
|
+
throw error
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
77
129
|
/**
|
|
78
130
|
* The template fields plus every labeled field the mapper didn't place, kept under its own label. A value already
|
|
79
131
|
* in a template field is skipped, so an API credential's `credential` doesn't land twice.
|
package/src/import/types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { EntryPayload } from '../core/payload'
|
|
2
2
|
|
|
3
|
-
export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'tags' | 'env'>
|
|
3
|
+
export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'source' | 'tags' | 'env'>
|
|
4
4
|
|
|
5
5
|
export type ImportResult = {
|
|
6
6
|
readonly entries: readonly ImportedEntry[]
|
package/src/prompt/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto'
|
|
2
2
|
|
|
3
3
|
import { TypeVaultError } from '../core/errors'
|
|
4
|
-
import { pageAssets, promptPage, expiredPage } from './page'
|
|
4
|
+
import { pageAssets, promptPage, expiredPage, rejectedPage } from './page'
|
|
5
5
|
import type { PromptHandle, PromptServer, PromptView } from './types'
|
|
6
6
|
|
|
7
7
|
export type { PromptHandle, PromptServer, PromptView } from './types'
|
|
@@ -11,7 +11,13 @@ type Pending = {
|
|
|
11
11
|
readonly view: PromptView
|
|
12
12
|
readonly resolve: (bytes: Uint8Array) => void
|
|
13
13
|
readonly reject: (error: TypeVaultError) => void
|
|
14
|
+
readonly accepted: Promise<void>
|
|
15
|
+
readonly accept: () => void
|
|
16
|
+
readonly refuse: (error: TypeVaultError) => void
|
|
17
|
+
readonly responded: Promise<void>
|
|
18
|
+
readonly respond: () => void
|
|
14
19
|
timer: ReturnType<typeof setTimeout> | undefined
|
|
20
|
+
submitted: boolean
|
|
15
21
|
}
|
|
16
22
|
|
|
17
23
|
const MAX_BODY = 64 * 1024
|
|
@@ -46,7 +52,9 @@ export async function startPromptServer(
|
|
|
46
52
|
|
|
47
53
|
function expire(token: string, entry: Pending): void {
|
|
48
54
|
retire(token, entry)
|
|
49
|
-
|
|
55
|
+
const error = new TypeVaultError('expired', 'Prompt expired or was cancelled')
|
|
56
|
+
entry.reject(error)
|
|
57
|
+
if (entry.submitted) entry.refuse(error)
|
|
50
58
|
}
|
|
51
59
|
|
|
52
60
|
function schedule(token: string, entry: Pending): void {
|
|
@@ -58,69 +66,96 @@ export async function startPromptServer(
|
|
|
58
66
|
entry.timer = setTimeout(() => schedule(token, entry), Math.min(remaining, 2_147_483_647))
|
|
59
67
|
}
|
|
60
68
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return response(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
69
|
+
let server: Bun.Server<undefined>
|
|
70
|
+
try {
|
|
71
|
+
server = Bun.serve({
|
|
72
|
+
hostname: '127.0.0.1',
|
|
73
|
+
port: options.port ?? 0,
|
|
74
|
+
// Enforce the limit while streaming so Bun's automatic 413 cannot omit security headers.
|
|
75
|
+
maxRequestBodySize: Number.MAX_SAFE_INTEGER,
|
|
76
|
+
async fetch(request) {
|
|
77
|
+
const path = new URL(request.url).pathname
|
|
78
|
+
const match = /^\/r\/([A-Za-z0-9_-]{22})$/.exec(path)
|
|
79
|
+
const token = match?.[1]
|
|
80
|
+
if (token === undefined || (request.method !== 'GET' && request.method !== 'POST')) return response(404)
|
|
81
|
+
const entry = pending.get(token)
|
|
82
|
+
if (entry === undefined) return gone.has(token) ? response(410, expiredPage()) : response(404)
|
|
83
|
+
if (entry.view.expiresAt.getTime() <= Date.now()) {
|
|
84
|
+
expire(token, entry)
|
|
85
|
+
return response(410, expiredPage())
|
|
86
|
+
}
|
|
87
|
+
if (request.method === 'GET') return response(200, promptPage(entry.view, assets.script))
|
|
88
|
+
if (entry.submitted) return response(410, expiredPage())
|
|
89
|
+
if (Number(request.headers.get('content-length')) > MAX_BODY) return response(413)
|
|
90
|
+
if (request.headers.get('content-type')?.split(';')[0]?.trim() !== 'application/octet-stream') {
|
|
91
|
+
return response(415)
|
|
92
|
+
}
|
|
93
|
+
const reader = request.body?.getReader()
|
|
94
|
+
const chunks: Uint8Array[] = []
|
|
95
|
+
let size = 0
|
|
96
|
+
try {
|
|
97
|
+
if (reader !== undefined) {
|
|
98
|
+
while (true) {
|
|
99
|
+
const chunk = await reader.read()
|
|
100
|
+
if (chunk.done) break
|
|
101
|
+
size += chunk.value.byteLength
|
|
102
|
+
if (size > MAX_BODY) {
|
|
103
|
+
await reader.cancel()
|
|
104
|
+
return response(413)
|
|
105
|
+
}
|
|
106
|
+
chunks.push(chunk.value)
|
|
94
107
|
}
|
|
95
|
-
chunks.push(chunk.value)
|
|
96
108
|
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof Error) return response(400)
|
|
111
|
+
throw error
|
|
112
|
+
} finally {
|
|
113
|
+
reader?.releaseLock()
|
|
97
114
|
}
|
|
98
|
-
|
|
99
|
-
if (
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
115
|
+
// Another upload, cancellation or expiry may win while the body is being read.
|
|
116
|
+
if (entry.submitted) return response(410, expiredPage())
|
|
117
|
+
if (pending.get(token) !== entry) return response(410, expiredPage())
|
|
118
|
+
if (entry.view.expiresAt.getTime() <= Date.now()) {
|
|
119
|
+
expire(token, entry)
|
|
120
|
+
return response(410, expiredPage())
|
|
121
|
+
}
|
|
122
|
+
const bytes = new Uint8Array(size)
|
|
123
|
+
let offset = 0
|
|
124
|
+
for (const chunk of chunks) {
|
|
125
|
+
bytes.set(chunk, offset)
|
|
126
|
+
offset += chunk.byteLength
|
|
127
|
+
}
|
|
128
|
+
entry.submitted = true
|
|
129
|
+
clearTimeout(entry.timer)
|
|
130
|
+
entry.timer = undefined
|
|
131
|
+
entry.resolve(bytes)
|
|
132
|
+
try {
|
|
133
|
+
await entry.accepted
|
|
134
|
+
retire(token, entry)
|
|
135
|
+
const accepted = response(204)
|
|
136
|
+
entry.respond()
|
|
137
|
+
return accepted
|
|
138
|
+
} catch (error) {
|
|
139
|
+
retire(token, entry)
|
|
140
|
+
if (error instanceof TypeVaultError) {
|
|
141
|
+
const rejected = response(error.code === 'tampered' ? 422 : 403, rejectedPage())
|
|
142
|
+
entry.respond()
|
|
143
|
+
return rejected
|
|
144
|
+
}
|
|
145
|
+
throw error
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
error() {
|
|
149
|
+
return response(500)
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!(error instanceof Error) || !('code' in error) || typeof error.code !== 'string') throw error
|
|
154
|
+
throw new TypeVaultError(
|
|
155
|
+
'unavailable',
|
|
156
|
+
`The secret page could not listen on 127.0.0.1:${options.port ?? 0} (${error.code}); set TYPEVAULT_PROMPT_PORT to use another port`,
|
|
157
|
+
)
|
|
158
|
+
}
|
|
124
159
|
|
|
125
160
|
const port = server.port
|
|
126
161
|
if (port === undefined) {
|
|
@@ -129,23 +164,45 @@ export async function startPromptServer(
|
|
|
129
164
|
}
|
|
130
165
|
return {
|
|
131
166
|
port,
|
|
132
|
-
open(view): PromptHandle {
|
|
167
|
+
open(view, openOptions = {}): PromptHandle {
|
|
133
168
|
if (stopped) throw new TypeVaultError('unavailable', 'Prompt server is stopped')
|
|
134
169
|
if (!Number.isFinite(view.expiresAt.getTime())) throw new TypeVaultError('invalid', 'Invalid prompt expiry')
|
|
135
170
|
const token = randomBytes(16).toString('base64url')
|
|
136
171
|
const id = randomBytes(16).toString('base64url')
|
|
137
172
|
const { promise: done, resolve, reject } = Promise.withResolvers<Uint8Array>()
|
|
173
|
+
const { promise: accepted, resolve: accept, reject: refuse } = Promise.withResolvers<void>()
|
|
174
|
+
const { promise: responded, resolve: respond } = Promise.withResolvers<void>()
|
|
138
175
|
const entry: Pending = {
|
|
139
176
|
id,
|
|
140
177
|
view: { ...view, recipients: [...view.recipients], expiresAt: new Date(view.expiresAt) },
|
|
141
178
|
resolve,
|
|
142
179
|
reject,
|
|
180
|
+
accepted,
|
|
181
|
+
accept,
|
|
182
|
+
refuse,
|
|
183
|
+
responded,
|
|
184
|
+
respond,
|
|
143
185
|
timer: undefined,
|
|
186
|
+
submitted: false,
|
|
144
187
|
}
|
|
145
188
|
pending.set(token, entry)
|
|
146
189
|
ids.set(id, token)
|
|
147
190
|
schedule(token, entry)
|
|
148
|
-
|
|
191
|
+
if (openOptions.validate !== true) accept()
|
|
192
|
+
return {
|
|
193
|
+
id,
|
|
194
|
+
url: `${options.publicUrl ?? `http://127.0.0.1:${port}`}/r/${token}`,
|
|
195
|
+
done,
|
|
196
|
+
accept: async () => {
|
|
197
|
+
accept()
|
|
198
|
+
await responded
|
|
199
|
+
},
|
|
200
|
+
reject: async (error) => {
|
|
201
|
+
if (!entry.submitted) return
|
|
202
|
+
refuse(error)
|
|
203
|
+
await responded
|
|
204
|
+
},
|
|
205
|
+
}
|
|
149
206
|
},
|
|
150
207
|
cancel(id) {
|
|
151
208
|
const token = ids.get(id)
|
package/src/prompt/page.ts
CHANGED
|
@@ -92,3 +92,11 @@ export function expiredPage(): string {
|
|
|
92
92
|
<p class="reason">This one-time request is no longer available. Ask the agent for a new link and match code.</p>`,
|
|
93
93
|
)
|
|
94
94
|
}
|
|
95
|
+
|
|
96
|
+
export function rejectedPage(): string {
|
|
97
|
+
return shell(
|
|
98
|
+
'Submission rejected',
|
|
99
|
+
`<p class="eyebrow">Secret request</p><h1>Secret not accepted</h1>
|
|
100
|
+
<p class="reason">The encrypted submission did not match this request. Ask the agent for a new link and match code.</p>`,
|
|
101
|
+
)
|
|
102
|
+
}
|
package/src/prompt/types.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { TypeVaultError } from '../core/errors'
|
|
1
2
|
import type { Preset } from '../core/naming'
|
|
2
3
|
|
|
3
4
|
export type PromptView = {
|
|
@@ -15,11 +16,13 @@ export type PromptHandle = {
|
|
|
15
16
|
readonly id: string
|
|
16
17
|
readonly url: string
|
|
17
18
|
readonly done: Promise<Uint8Array>
|
|
19
|
+
readonly accept: () => Promise<void>
|
|
20
|
+
readonly reject: (error: TypeVaultError) => Promise<void>
|
|
18
21
|
}
|
|
19
22
|
|
|
20
23
|
export type PromptServer = {
|
|
21
24
|
readonly port: number
|
|
22
|
-
readonly open: (view: PromptView) => PromptHandle
|
|
25
|
+
readonly open: (view: PromptView, options?: { readonly validate?: boolean }) => PromptHandle
|
|
23
26
|
readonly cancel: (id: string) => void
|
|
24
27
|
readonly stop: () => Promise<void>
|
|
25
28
|
}
|
package/src/redact/index.ts
CHANGED
|
@@ -31,8 +31,10 @@ export function createRedactor(values: readonly string[], options?: { readonly r
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
const patterns: readonly string[] = [...variants].sort((left, right) => right.length - left.length)
|
|
34
|
-
const longest = patterns[0]?.length ?? 1
|
|
35
34
|
const replacement = options?.replacement ?? '[redacted]'
|
|
35
|
+
const bytePatterns = patterns.map((pattern) => Buffer.from(pattern)).sort((left, right) => right.length - left.length)
|
|
36
|
+
const replacementBytes = Buffer.from(replacement)
|
|
37
|
+
const expansion = Math.max(1, ...bytePatterns.map((pattern) => replacementBytes.length / pattern.length))
|
|
36
38
|
|
|
37
39
|
// Consume whole matches, even when they extend beyond the safe emission boundary.
|
|
38
40
|
const consume = (text: string, limit: number): { readonly output: string; readonly rest: string } => {
|
|
@@ -56,21 +58,55 @@ export function createRedactor(values: readonly string[], options?: { readonly r
|
|
|
56
58
|
return {
|
|
57
59
|
redact: (text) => consume(text, text.length).output,
|
|
58
60
|
stream: () => {
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
61
|
+
let pending = Buffer.alloc(0)
|
|
62
|
+
const emit = (input: Buffer, final: boolean, controller: TransformStreamDefaultController<Uint8Array>) => {
|
|
63
|
+
let limit = input.length
|
|
64
|
+
if (!final) {
|
|
65
|
+
for (const pattern of bytePatterns) {
|
|
66
|
+
const start = Math.max(0, input.length - pattern.length + 1)
|
|
67
|
+
for (let index = input.indexOf(pattern.subarray(0, 1), start); index >= 0 && index < limit;) {
|
|
68
|
+
if (input.subarray(index).equals(pattern.subarray(0, input.length - index))) {
|
|
69
|
+
limit = index
|
|
70
|
+
break
|
|
71
|
+
}
|
|
72
|
+
index = input.indexOf(pattern.subarray(0, 1), index + 1)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
let index = 0
|
|
77
|
+
const output = Buffer.allocUnsafe(Math.ceil(input.length * expansion))
|
|
78
|
+
let written = 0
|
|
79
|
+
const matches = bytePatterns.map((pattern) => ({ pattern, at: input.indexOf(pattern) }))
|
|
80
|
+
while (index < limit) {
|
|
81
|
+
let next = input.length
|
|
82
|
+
let match: Buffer | undefined
|
|
83
|
+
for (const candidate of matches) {
|
|
84
|
+
if (candidate.at >= 0 && candidate.at < index) candidate.at = input.indexOf(candidate.pattern, index)
|
|
85
|
+
if (candidate.at >= 0 && candidate.at < next) {
|
|
86
|
+
next = candidate.at
|
|
87
|
+
match = candidate.pattern
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (match === undefined || next >= limit) {
|
|
91
|
+
written += input.copy(output, written, index, limit)
|
|
92
|
+
index = limit
|
|
93
|
+
} else {
|
|
94
|
+
written += input.copy(output, written, index, next)
|
|
95
|
+
written += replacementBytes.copy(output, written)
|
|
96
|
+
index = next + match.length
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (written > 0) controller.enqueue(output.subarray(0, written))
|
|
100
|
+
// Copy only the undecided suffix, so it cannot retain a large input buffer.
|
|
101
|
+
pending = Buffer.from(input.subarray(index))
|
|
102
|
+
}
|
|
62
103
|
return new TransformStream<Uint8Array, Uint8Array>({
|
|
63
104
|
transform(chunk, controller) {
|
|
64
|
-
pending
|
|
65
|
-
|
|
66
|
-
const result = consume(pending, limit)
|
|
67
|
-
pending = result.rest
|
|
68
|
-
if (result.output.length > 0) controller.enqueue(encoder.encode(result.output))
|
|
105
|
+
const input = pending.length > 0 ? Buffer.concat([pending, chunk]) : Buffer.from(chunk)
|
|
106
|
+
emit(input, false, controller)
|
|
69
107
|
},
|
|
70
108
|
flush(controller) {
|
|
71
|
-
pending
|
|
72
|
-
const result = consume(pending, pending.length)
|
|
73
|
-
if (result.output.length > 0) controller.enqueue(encoder.encode(result.output))
|
|
109
|
+
emit(pending, true, controller)
|
|
74
110
|
},
|
|
75
111
|
})
|
|
76
112
|
},
|
package/src/redact/scrub-file.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import { open, rename, rm } from 'node:fs/promises'
|
|
2
|
+
import { lstat, open, rename, rm } from 'node:fs/promises'
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
4
|
|
|
5
5
|
import { TypeVaultError } from '../core/errors'
|
|
@@ -9,22 +9,28 @@ export async function scrubFile(path: string, redactor: Redactor): Promise<boole
|
|
|
9
9
|
let temporary: string | undefined
|
|
10
10
|
try {
|
|
11
11
|
try {
|
|
12
|
+
const info = await lstat(path)
|
|
13
|
+
if (info.isSymbolicLink())
|
|
14
|
+
throw new TypeVaultError('invalid', 'Refusing to scrub a symbolic link; name its target')
|
|
15
|
+
if (!info.isFile()) throw new TypeVaultError('invalid', 'Not a regular file')
|
|
12
16
|
const original = await open(path, 'r')
|
|
13
17
|
const snapshot = await (async () => {
|
|
14
18
|
try {
|
|
15
|
-
return {
|
|
19
|
+
return { bytes: await original.readFile(), mode: (await original.stat()).mode & 0o7777 }
|
|
16
20
|
} finally {
|
|
17
21
|
await original.close()
|
|
18
22
|
}
|
|
19
23
|
})()
|
|
20
|
-
const redacted =
|
|
21
|
-
|
|
24
|
+
const redacted = Buffer.from(
|
|
25
|
+
await new Response(new Blob([snapshot.bytes]).stream().pipeThrough(redactor.stream())).arrayBuffer(),
|
|
26
|
+
)
|
|
27
|
+
if (redacted.equals(snapshot.bytes)) return false
|
|
22
28
|
|
|
23
29
|
const candidate = join(dirname(path), `.typevault-redact-${randomUUID()}`)
|
|
24
30
|
const file = await open(candidate, 'wx', 0o600)
|
|
25
31
|
temporary = candidate
|
|
26
32
|
try {
|
|
27
|
-
await file.writeFile(redacted
|
|
33
|
+
await file.writeFile(redacted)
|
|
28
34
|
await file.chmod(snapshot.mode)
|
|
29
35
|
await file.sync()
|
|
30
36
|
} finally {
|
|
@@ -37,7 +43,9 @@ export async function scrubFile(path: string, redactor: Redactor): Promise<boole
|
|
|
37
43
|
if (temporary !== undefined) await rm(temporary, { force: true })
|
|
38
44
|
}
|
|
39
45
|
} catch (error) {
|
|
40
|
-
|
|
41
|
-
|
|
46
|
+
throw new TypeVaultError(
|
|
47
|
+
error instanceof TypeVaultError ? error.code : 'unavailable',
|
|
48
|
+
`${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
49
|
+
)
|
|
42
50
|
}
|
|
43
51
|
}
|