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
@@ -57,10 +57,10 @@ export async function parseKeepass(bytes: Uint8Array, password?: string): Promis
57
57
  const url = fields['URL']
58
58
  items.push({
59
59
  title: fields['Title'] ?? '',
60
- type: login ? 'password' : 'note',
60
+ preset: login ? 'password' : 'note',
61
61
  fields: login
62
62
  ? { username: fields['UserName'], password: fields['Password'], url, totp: fields['otp'] }
63
- : { text: fields['Notes'] },
63
+ : { $default: fields['Notes'] },
64
64
  tags: parseExternal(entry.tags, z.array(z.string()).readonly(), 'KeePass tags'),
65
65
  ...(container === undefined ? {} : { container }),
66
66
  ...(url === undefined ? {} : { url }),
@@ -21,9 +21,9 @@ export function parseLastpass(text: string): ImportResult {
21
21
  {
22
22
  title: row['name'] ?? '',
23
23
  container: row['grouping'] ?? '',
24
- type: note ? ('note' as const) : ('password' as const),
24
+ preset: note ? ('note' as const) : ('password' as const),
25
25
  fields: note
26
- ? { text: extra }
26
+ ? { $default: extra }
27
27
  : { username: row['username'], password: row['password'], totp: row['totp'], url: row['url'] },
28
28
  ...(note || row['url'] === undefined ? {} : { url: row['url'] }),
29
29
  },
@@ -1,14 +1,23 @@
1
1
  import { z } from 'zod'
2
2
 
3
3
  import { TypeVaultError } from '../core/errors'
4
- import { ENTRY_TYPES, parseEntryName, slugifySegment, type EntryType } from '../core/naming'
4
+ import {
5
+ isFieldName,
6
+ parseEntryName,
7
+ slugifySegment,
8
+ PRESETS,
9
+ type Preset,
10
+ type Field,
11
+ type FieldType,
12
+ fieldStrings,
13
+ } from '../core/naming'
5
14
  import type { ImportedEntry, ImportResult } from './types'
6
15
 
7
16
  export type ImportItem = {
8
17
  readonly title: string
9
18
  readonly container?: string
10
- readonly type: EntryType
11
- readonly fields: Readonly<Record<string, string | undefined>>
19
+ readonly preset: Preset
20
+ readonly fields: Readonly<Record<string, string | Field | undefined>>
12
21
  readonly url?: string
13
22
  readonly tags?: readonly string[]
14
23
  readonly env?: string
@@ -26,17 +35,36 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
26
35
  while (used.has(name)) name = `${base}-${suffix++}`
27
36
  used.add(name)
28
37
  if (name !== base) messages.push(`name collision: "${base}" renamed to "${name}"`)
29
- const allowed: readonly string[] = ENTRY_TYPES[item.type].fields
30
- const fields = Object.fromEntries(
31
- Object.entries(item.fields).filter(
32
- (pair): pair is [string, string] => allowed.includes(pair[0]) && pair[1] !== undefined && pair[1] !== '',
33
- ),
34
- )
38
+ const fields: Record<string, Field> = {}
39
+ for (const [field, value] of Object.entries(item.fields)) {
40
+ if (
41
+ value === undefined ||
42
+ value === '' ||
43
+ (typeof value !== 'string' && fieldStrings(value).every((part) => part === ''))
44
+ )
45
+ continue
46
+ if (isFieldName(field)) {
47
+ if (typeof value === 'string') {
48
+ const types: Readonly<Record<string, FieldType>> = PRESETS[item.preset].fields
49
+ const type = types[field] ?? 'secret'
50
+ switch (type) {
51
+ case 'secret':
52
+ case 'text':
53
+ case 'totp':
54
+ fields[field] = { type, value }
55
+ break
56
+ case 'oauth':
57
+ throw new TypeVaultError('invalid', 'OAuth import requires typed fields')
58
+ default:
59
+ throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
60
+ }
61
+ } else fields[field] = value
62
+ } else messages.push(`${name}: skipped a field with an unusable name`)
63
+ }
35
64
  const url = item.url === undefined ? null : URL.parse(item.url)
36
65
  const origin = url && (url.protocol === 'http:' || url.protocol === 'https:') ? url.origin : undefined
37
66
  entries.push({
38
67
  name: parseEntryName(name),
39
- type: item.type,
40
68
  fields,
41
69
  tags: item.tags ?? [],
42
70
  ...(origin === undefined ? {} : { origin }),
@@ -46,6 +74,35 @@ export function collectEntries(items: readonly ImportItem[], warnings: readonly
46
74
  return { entries, warnings: messages }
47
75
  }
48
76
 
77
+ /**
78
+ * The template fields plus every labeled field the mapper didn't place, kept under its own label. A value already
79
+ * in a template field is skipped, so an API credential's `credential` doesn't land twice.
80
+ */
81
+ export function withCustomFields(
82
+ mapped: Readonly<Record<string, string | Field | undefined>>,
83
+ labeled: readonly (readonly [label: string, value: string | Field | undefined])[],
84
+ ): Record<string, string | Field | undefined> {
85
+ const used = new Set(
86
+ Object.values(mapped).flatMap((value) =>
87
+ value === undefined ? [] : typeof value === 'string' ? [value] : fieldStrings(value),
88
+ ),
89
+ )
90
+ const custom: Record<string, string | Field> = {}
91
+ for (const [label, value] of labeled) {
92
+ const field = label.trim()
93
+ if (
94
+ field === '' ||
95
+ value === undefined ||
96
+ value === '' ||
97
+ (typeof value === 'string' ? used.has(value) : fieldStrings(value).every((part) => used.has(part)))
98
+ )
99
+ continue
100
+ if (Object.hasOwn(mapped, field) || Object.hasOwn(custom, field)) continue
101
+ custom[field] = value
102
+ }
103
+ return { ...custom, ...mapped }
104
+ }
105
+
49
106
  export function parseJson<T>(text: string, schema: z.ZodType<T>, format: string): T {
50
107
  let value: unknown
51
108
  try {
@@ -11,8 +11,8 @@ export function parseTypeclaw(text: string): ImportResult {
11
11
  .filter(({ name }) => name.startsWith(PREFIX) && name.length > PREFIX.length)
12
12
  .map(({ name, value }) => ({
13
13
  title: name.slice(PREFIX.length),
14
- type: 'password',
15
- fields: { password: value },
14
+ preset: 'api_key',
15
+ fields: { $default: value },
16
16
  ...(isUsableEnvName(name) ? { env: name } : {}),
17
17
  })),
18
18
  )
@@ -1,6 +1,6 @@
1
1
  import type { EntryPayload } from '../core/payload'
2
2
 
3
- export type ImportedEntry = Pick<EntryPayload, 'name' | 'type' | 'fields' | 'origin' | 'tags' | 'env'>
3
+ export type ImportedEntry = Pick<EntryPayload, 'name' | 'fields' | 'origin' | 'tags' | 'env'>
4
4
 
5
5
  export type ImportResult = {
6
6
  readonly entries: readonly ImportedEntry[]
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { Access } from './access/types'
2
+ import { type Env, resolveAccess } from './cli/context'
3
+ import { TypeVaultError } from './core/errors'
4
+
5
+ export type { Access, EntrySummary, EntryValue, SetInput } from './access/types'
6
+ export { type ErrorCode, TypeVaultError } from './core/errors'
7
+ export {
8
+ type EntryName,
9
+ type EntryRef,
10
+ type FieldType,
11
+ type Field,
12
+ type Preset,
13
+ PRESETS,
14
+ defaultField,
15
+ resolveField,
16
+ parseEntryName,
17
+ parseEntryRef,
18
+ parsePreset,
19
+ } from './core/naming'
20
+
21
+ export type ClientOptions = {
22
+ /** A live (`tvl1.…`), sealed (`tvg1:…`) or `@path` grant. Defaults to `TYPEVAULT_GRANT`. */
23
+ readonly grant?: string
24
+ /** The global vault's directory. Defaults to `TYPEVAULT_DIR`; without one the vault is chosen like the CLI's. */
25
+ readonly dir?: string
26
+ /** Use the global vault instead of the project's, like the CLI's `-g`. Defaults to `TYPEVAULT_GLOBAL`. */
27
+ readonly global?: boolean
28
+ /** Without a grant, open the vault with this machine's own keys (owner, issuers). Off by default. */
29
+ readonly direct?: boolean
30
+ /** The vault's private state (trust pin, audit, run). Defaults to `TYPEVAULT_STATE_DIR`, else this user's config. */
31
+ readonly stateDir?: string
32
+ /** Where the daemon's sockets live, for a `stateDir` too deep for one. Defaults to `TYPEVAULT_RUN_DIR`. */
33
+ readonly runDir?: string
34
+ /** Where the defaults above are read from. Defaults to `process.env`. */
35
+ readonly env?: Env
36
+ }
37
+
38
+ /**
39
+ * The same access the CLI has: a live grant goes through the daemon (started if needed), a sealed grant is read
40
+ * in-process. Values returned here are not redacted anywhere: pass `readValues()` to `typevault/redact` if they
41
+ * can reach output.
42
+ */
43
+ export async function createClient(options: ClientOptions = {}): Promise<Access> {
44
+ const base = options.env ?? process.env
45
+ const grant = (options.grant ?? base['TYPEVAULT_GRANT'])?.trim()
46
+ if ((grant === undefined || grant === '') && options.direct !== true) {
47
+ throw new TypeVaultError('denied', 'no grant given (pass `grant`, set TYPEVAULT_GRANT, or opt into `direct`)')
48
+ }
49
+ const env: Env = {
50
+ ...base,
51
+ TYPEVAULT_GRANT: grant,
52
+ ...(options.dir === undefined ? {} : { TYPEVAULT_DIR: options.dir }),
53
+ ...(options.global === undefined ? {} : { TYPEVAULT_GLOBAL: options.global ? '1' : '' }),
54
+ ...(options.stateDir === undefined ? {} : { TYPEVAULT_STATE_DIR: options.stateDir }),
55
+ ...(options.runDir === undefined ? {} : { TYPEVAULT_RUN_DIR: options.runDir }),
56
+ }
57
+ return (await resolveAccess(env)).access
58
+ }
package/src/owner.ts ADDED
@@ -0,0 +1,156 @@
1
+ import { existsSync } from 'node:fs'
2
+
3
+ import { ScopedVault } from './access/scoped'
4
+ import type { Access } from './access/types'
5
+ import { Admin } from './core/admin'
6
+ import { decodeSecretKey, encodeSecretKey } from './core/crypto'
7
+ import { TypeVaultError } from './core/errors'
8
+ import { claimDaemon } from './core/holder'
9
+ import { createIdentity, decodeMemberPublic, encodeMemberPublic, memberPublicOfIdentity } from './core/identity'
10
+ import { initLocalVault } from './core/init'
11
+ import { localLayout } from './core/layout'
12
+ import { holdLock } from './core/lock'
13
+ import type { MemberKind } from './core/state'
14
+ import { Vault } from './core/vault'
15
+
16
+ export type { Access, EntrySummary, EntryValue, SetInput } from './access/types'
17
+ export { type ErrorCode, TypeVaultError } from './core/errors'
18
+
19
+ /** A machine member: no password, its key held by whoever runs it. */
20
+ export type MachineIdentity = {
21
+ readonly name: string
22
+ /** The secret member key (what `TYPEVAULT_KEY` takes). Keep it private. */
23
+ readonly key: string
24
+ /** The `tvp1:` public key an owner adds as a member. */
25
+ readonly publicKey: string
26
+ }
27
+
28
+ /** Where a vault and its private state live. Nothing is read from or written to this user's config. */
29
+ export type VaultLocation = {
30
+ /** The vault directory, e.g. `<project>/.typevault`. */
31
+ readonly dir: string
32
+ /** The vault's private state (trust pin, audit, run). One machine at a time may use it. */
33
+ readonly stateDir: string
34
+ /** Where the daemon's sockets live, for a `stateDir` too deep for a socket path. */
35
+ readonly runDir?: string
36
+ }
37
+
38
+ export type TierInfo = { readonly name: string; readonly gen: number; readonly includes: readonly string[] }
39
+ export type MemberInfo = {
40
+ readonly name: string
41
+ readonly kind: MemberKind
42
+ readonly owner: boolean
43
+ readonly tiers: readonly string[]
44
+ }
45
+
46
+ export type OwnerVault = {
47
+ readonly member: string
48
+ readonly tiers: {
49
+ add(name: string): Promise<void>
50
+ /** `tier` reaches everything `included` reaches. */
51
+ include(tier: string, included: string): Promise<void>
52
+ list(): Promise<readonly TierInfo[]>
53
+ }
54
+ readonly ceilings: {
55
+ /** The most the admin socket `name` may grant. */
56
+ set(name: string, tier: string): Promise<void>
57
+ }
58
+ readonly members: {
59
+ list(): Promise<readonly MemberInfo[]>
60
+ }
61
+ /** Entries, read and written with this member's own keys (direct mode, audited). */
62
+ readonly entries: Access
63
+ }
64
+
65
+ /** A new machine identity, returned only: no file is written. */
66
+ export async function createMachineIdentity(options: { readonly name: string }): Promise<MachineIdentity> {
67
+ const { identity, key } = await createIdentity(options.name, 'machine')
68
+ return {
69
+ name: identity.name,
70
+ key: encodeSecretKey(key),
71
+ publicKey: encodeMemberPublic(memberPublicOfIdentity(identity)),
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Creates an empty vault at `dir` owned by a machine `founder`. Fails with `conflict` when a vault is already there
77
+ * (it never initializes over one) or a daemon is using `stateDir`, and `in_use` when one on another machine is.
78
+ */
79
+ export async function initVault(
80
+ options: VaultLocation & { readonly founder: Pick<MachineIdentity, 'name' | 'publicKey'> },
81
+ ): Promise<void> {
82
+ const member = decodeMemberPublic(options.founder.publicKey)
83
+ if (member.kind !== 'machine') throw new TypeVaultError('invalid', 'the founder must be a machine identity')
84
+ const env = envOf(options)
85
+ const layout = localLayout(options.dir, env)
86
+ // Initializing resets the state directory's runtime state: no daemon may be using it, here or on another machine.
87
+ const release = holdLock(layout.daemonLock)
88
+ if (release === undefined) {
89
+ throw new TypeVaultError('conflict', `a typevault daemon is using ${options.stateDir}; stop it first`)
90
+ }
91
+ try {
92
+ const claim = claimDaemon(layout, env)
93
+ try {
94
+ await initLocalVault(options.dir, { name: options.founder.name, member }, env)
95
+ } finally {
96
+ claim.release()
97
+ }
98
+ } finally {
99
+ release()
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Opens the vault at `dir` with a member key held in memory. Fails with `no_vault` when there is no vault at `dir`,
105
+ * and `not_member` when there is one but `key` is not among its members. Tier and ceiling changes need an owner.
106
+ */
107
+ export async function openVault(options: VaultLocation & { readonly key: string }): Promise<OwnerVault> {
108
+ const env = envOf(options)
109
+ const layout = localLayout(options.dir, env)
110
+ if (!existsSync(layout.ownerFile)) throw new TypeVaultError('no_vault', `no vault at ${options.dir}`)
111
+ const key = decodeSecretKey(options.key)
112
+ if (key.role.kind !== 'member') throw new TypeVaultError('invalid', 'the key must be a member key')
113
+ const vault = await Vault.open(layout, [key], env)
114
+ const member = vault.member
115
+ if (member === undefined) {
116
+ throw new TypeVaultError('not_member', `"${key.role.name}" is not a member of the vault at ${options.dir}`)
117
+ }
118
+ const admin = (): Admin => new Admin(vault)
119
+ const current = async () => {
120
+ vault.refresh()
121
+ return vault.state
122
+ }
123
+ return {
124
+ member,
125
+ tiers: {
126
+ add: (name) => admin().addTier(name),
127
+ include: (tier, included) => admin().include(tier, included),
128
+ list: async () =>
129
+ Object.entries((await current()).tiers).map(([name, tier]) => ({
130
+ name,
131
+ gen: tier.gen,
132
+ includes: tier.includes,
133
+ })),
134
+ },
135
+ ceilings: { set: (name, tier) => admin().setCeiling(name, tier) },
136
+ members: {
137
+ list: async () =>
138
+ Object.entries((await current()).members).map(([name, m]) => ({
139
+ name,
140
+ kind: m.kind,
141
+ owner: m.owner,
142
+ tiers: m.tiers,
143
+ })),
144
+ },
145
+ entries: new ScopedVault(vault, [], { mode: 'direct', ownTiers: vault.state.members[member]?.tiers ?? [] }),
146
+ }
147
+ }
148
+
149
+ function envOf(location: VaultLocation): Readonly<Record<string, string | undefined>> {
150
+ if (location.stateDir === '') throw new TypeVaultError('invalid', 'stateDir is required')
151
+ return {
152
+ TYPEVAULT_STATE_DIR: location.stateDir,
153
+ ...(location.runDir === undefined ? {} : { TYPEVAULT_RUN_DIR: location.runDir }),
154
+ ...(process.env['TYPEVAULT_HOST_ID'] === undefined ? {} : { TYPEVAULT_HOST_ID: process.env['TYPEVAULT_HOST_ID'] }),
155
+ }
156
+ }
@@ -2,12 +2,13 @@ import { Encrypter } from 'age-encryption'
2
2
  import { z } from 'zod'
3
3
 
4
4
  import { TypeVaultError } from '../core/errors'
5
- import { ENTRY_TYPES, parseEntryName, parseEntryType } from '../core/naming'
5
+ import { PRESETS, parseEntryName, parsePreset, type Field, type FieldType } from '../core/naming'
6
+ import { FieldSchema } from '../core/payload'
6
7
  import type { EntryPayload } from '../core/payload'
7
8
 
8
9
  const ViewSchema = z.object({
9
10
  name: z.string(),
10
- type: z.string(),
11
+ preset: z.string().optional(),
11
12
  recipients: z.array(z.string()).min(1),
12
13
  })
13
14
 
@@ -17,6 +18,8 @@ function requiredElement<T extends HTMLElement>(selector: string, kind: { new ()
17
18
  throw new TypeVaultError('invalid', 'The request page is incomplete. Open a new request.')
18
19
  }
19
20
 
21
+ const ACRONYMS = new Set(['url', 'totp', 'id', 'api', 'ssh'])
22
+
20
23
  const form = requiredElement('#prompt', HTMLFormElement)
21
24
  const fieldsRoot = requiredElement('#fields', HTMLDivElement)
22
25
  const status = requiredElement('#status', HTMLParagraphElement)
@@ -26,27 +29,44 @@ const success = requiredElement('#success', HTMLElement)
26
29
  function initialize(): void {
27
30
  const data = requiredElement('#tv-data', HTMLScriptElement)
28
31
  const view = ViewSchema.parse(JSON.parse(data.textContent ?? ''))
29
- const type = parseEntryType(view.type)
32
+ const preset =
33
+ view.preset === undefined
34
+ ? { fields: { $default: 'secret' } as const, input: '$default' }
35
+ : PRESETS[parsePreset(view.preset)]
30
36
  const name = parseEntryName(view.name)
31
37
  const inputs: (HTMLInputElement | HTMLTextAreaElement)[] = []
32
- const publicFields = new Set(['username', 'url', 'expires_at', 'token_url', 'client_id', 'public_key', 'text'])
33
- for (const field of ENTRY_TYPES[type].fields) {
34
- const secret = !publicFields.has(field)
38
+ const types: Readonly<Record<string, FieldType>> = preset.fields
39
+ for (const [field, type] of Object.entries(types)) {
40
+ const secret = type !== 'text'
35
41
  const wrapper = document.createElement('div')
36
42
  wrapper.className = 'field'
37
43
  const label = document.createElement('label')
38
44
  label.htmlFor = `field-${field}`
39
- label.textContent = field.replaceAll('_', ' ').replace(/^./, (char) => char.toUpperCase())
45
+ const fieldName = (field === '$default' ? (type === 'oauth' ? 'OAuth JSON' : 'Secret') : field)
46
+ .split('_')
47
+ .map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word))
48
+ .join(' ')
49
+ .replace(/^./, (char) => char.toUpperCase())
50
+ label.textContent = fieldName
40
51
  const row = document.createElement('div')
41
52
  row.className = 'input-row'
42
- const input = ['text', 'private_key', 'public_key'].includes(field)
43
- ? document.createElement('textarea')
44
- : document.createElement('input')
53
+ const input =
54
+ type === 'oauth' ||
55
+ (field === '$default' && view.preset === 'note') ||
56
+ ['text', 'private_key', 'public_key'].includes(field)
57
+ ? document.createElement('textarea')
58
+ : document.createElement('input')
45
59
  input.id = label.htmlFor
46
60
  input.name = field
47
61
  input.autocomplete = 'off'
48
62
  input.spellcheck = false
49
- input.required = field === ENTRY_TYPES[type].primary
63
+ input.required = field === preset.input
64
+ if (!input.required) {
65
+ const optional = document.createElement('span')
66
+ optional.className = 'optional'
67
+ optional.textContent = 'Optional'
68
+ label.append(optional)
69
+ }
50
70
  if (input instanceof HTMLInputElement) input.type = secret ? 'password' : 'text'
51
71
  else if (secret) input.classList.add('concealed')
52
72
  inputs.push(input)
@@ -56,14 +76,14 @@ function initialize(): void {
56
76
  toggle.type = 'button'
57
77
  toggle.className = 'toggle'
58
78
  toggle.textContent = 'Show'
59
- toggle.setAttribute('aria-label', `Show ${label.textContent.toLowerCase()}`)
79
+ toggle.setAttribute('aria-label', `Show ${fieldName.toLowerCase()}`)
60
80
  toggle.setAttribute('aria-pressed', 'false')
61
81
  toggle.addEventListener('click', () => {
62
82
  const show = toggle.getAttribute('aria-pressed') !== 'true'
63
83
  if (input instanceof HTMLInputElement) input.type = show ? 'text' : 'password'
64
84
  else input.classList.toggle('concealed', !show)
65
85
  toggle.setAttribute('aria-pressed', String(show))
66
- toggle.setAttribute('aria-label', `${show ? 'Hide' : 'Show'} ${label.textContent?.toLowerCase()}`)
86
+ toggle.setAttribute('aria-label', `${show ? 'Hide' : 'Show'} ${fieldName.toLowerCase()}`)
67
87
  toggle.textContent = show ? 'Hide' : 'Show'
68
88
  })
69
89
  row.append(toggle)
@@ -83,9 +103,22 @@ function initialize(): void {
83
103
  const payload: EntryPayload = {
84
104
  v: 1,
85
105
  name,
86
- type,
87
106
  fields: Object.fromEntries(
88
- inputs.filter((input) => input.value !== '').map((input) => [input.name, input.value]),
107
+ inputs
108
+ .filter((input) => input.value !== '')
109
+ .map((input): [string, Field] => {
110
+ const type = types[input.name] ?? 'secret'
111
+ switch (type) {
112
+ case 'oauth':
113
+ return [input.name, FieldSchema.parse({ type, value: JSON.parse(input.value) })]
114
+ case 'secret':
115
+ case 'text':
116
+ case 'totp':
117
+ return [input.name, { type, value: input.value }]
118
+ default:
119
+ throw new TypeVaultError('invalid', `unexpected field type ${type satisfies never}`)
120
+ }
121
+ }),
89
122
  ),
90
123
  tags: [],
91
124
  created: now,