@shieldfive/cli 0.1.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/LICENSE +201 -0
- package/README.md +144 -0
- package/SECURITY.md +84 -0
- package/package.json +52 -0
- package/src/auth.mjs +35 -0
- package/src/cli.mjs +211 -0
- package/src/sfCrypto.mjs +77 -0
- package/src/sync.mjs +205 -0
- package/src/unlock.mjs +107 -0
- package/src/upload.mjs +342 -0
- package/src/uploadCrypto.mjs +207 -0
- package/src/vault.mjs +45 -0
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ShieldFive CLI (`sf`) — scaffold.
|
|
3
|
+
//
|
|
4
|
+
// sf encrypt <folder> encrypt each file locally (verified core demo)
|
|
5
|
+
// sf push <folder> login -> unlock -> encrypt -> upload once
|
|
6
|
+
// sf sync <folder> [--watch] keep the folder mirrored into your vault
|
|
7
|
+
//
|
|
8
|
+
// The offline crypto chain (unlock -> identity -> encrypt) is VERIFIED
|
|
9
|
+
// (`npm test`), and the full upload pipeline (direct + multipart) is wired and
|
|
10
|
+
// tested. Configure the live commands with env vars (see README) and run them
|
|
11
|
+
// against your own ShieldFive account.
|
|
12
|
+
|
|
13
|
+
import { webcrypto } from 'node:crypto'
|
|
14
|
+
import { readFile, readdir, stat } from 'node:fs/promises'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
|
|
17
|
+
import { deriveVaultIdentity, encryptFileForVault } from './sfCrypto.mjs'
|
|
18
|
+
|
|
19
|
+
function usage() {
|
|
20
|
+
process.stdout.write(
|
|
21
|
+
[
|
|
22
|
+
'sf <command>',
|
|
23
|
+
'',
|
|
24
|
+
' encrypt <folder> encrypt each file in <folder> locally (verified core)',
|
|
25
|
+
' push <folder> login -> unlock -> encrypt -> upload to your vault',
|
|
26
|
+
' sync <folder> [--watch] mirror new/changed files into your vault',
|
|
27
|
+
' [--interval=<seconds>] poll interval for --watch (default 5)',
|
|
28
|
+
' --help',
|
|
29
|
+
'',
|
|
30
|
+
'push / sync need only your ShieldFive account:',
|
|
31
|
+
' SF_EMAIL, SF_PASSWORD [SF_VAULT_PASSWORD if your vault password differs]',
|
|
32
|
+
'SF_API_BASE_URL, SF_SUPABASE_URL, SF_SUPABASE_ANON_KEY default to ShieldFive',
|
|
33
|
+
'(override only for a development backend).',
|
|
34
|
+
'',
|
|
35
|
+
].join('\n') + '\n',
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function* filesIn(folder) {
|
|
40
|
+
for (const name of await readdir(folder)) {
|
|
41
|
+
const path = join(folder, name)
|
|
42
|
+
const info = await stat(path)
|
|
43
|
+
if (info.isFile()) yield { name, path, size: info.size }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Demonstrates the verified encryption end to end with an EPHEMERAL identity.
|
|
48
|
+
async function cmdEncrypt(folder) {
|
|
49
|
+
const identity = await deriveVaultIdentity(
|
|
50
|
+
webcrypto.getRandomValues(new Uint8Array(32)),
|
|
51
|
+
)
|
|
52
|
+
for await (const { name, path } of filesIn(folder)) {
|
|
53
|
+
const bytes = new Uint8Array(await readFile(path))
|
|
54
|
+
const { encryptedBlob, fileId } = await encryptFileForVault(
|
|
55
|
+
bytes,
|
|
56
|
+
identity.mlKemPublicKey,
|
|
57
|
+
)
|
|
58
|
+
process.stdout.write(
|
|
59
|
+
`encrypted ${name} -> fileId ${Buffer.from(fileId).toString('hex')} ` +
|
|
60
|
+
`(${encryptedBlob.size} bytes ciphertext)\n`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ShieldFive's PUBLIC client configuration — the same values the website ships
|
|
66
|
+
// to every browser and the mobile app embeds. The anon key is a Supabase JWT
|
|
67
|
+
// with role=anon, gated by row-level security; it is designed to be public.
|
|
68
|
+
// All three default here and are overridable via env for development or a
|
|
69
|
+
// staging backend, so a normal user only needs SF_EMAIL + SF_PASSWORD.
|
|
70
|
+
const DEFAULTS = {
|
|
71
|
+
apiBaseUrl: 'https://shieldfive.com',
|
|
72
|
+
supabaseUrl: 'https://dskbmjpanehckhqzkclp.supabase.co',
|
|
73
|
+
anonKey:
|
|
74
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRza2JtanBhbmVoY2tocXprY2xwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzAxMTc3MzEsImV4cCI6MjA4NTY5MzczMX0.AK7K8tyrAWFWgfaa6vvTveqmKiMrL2nY1m7qS9TII9U',
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function readLiveConfig() {
|
|
78
|
+
const e = process.env
|
|
79
|
+
const email = e.SF_EMAIL
|
|
80
|
+
const password = e.SF_PASSWORD
|
|
81
|
+
const missing = []
|
|
82
|
+
if (!email) missing.push('SF_EMAIL')
|
|
83
|
+
if (!password) missing.push('SF_PASSWORD')
|
|
84
|
+
if (missing.length) {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`this command needs your ShieldFive account: set ${missing.join(' and ')}. ` +
|
|
87
|
+
'(SF_API_BASE_URL, SF_SUPABASE_URL, and SF_SUPABASE_ANON_KEY default to ' +
|
|
88
|
+
'ShieldFive; override them only for a development backend.)',
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
apiBaseUrl: e.SF_API_BASE_URL || DEFAULTS.apiBaseUrl,
|
|
93
|
+
supabaseUrl: e.SF_SUPABASE_URL || DEFAULTS.supabaseUrl,
|
|
94
|
+
anonKey: e.SF_SUPABASE_ANON_KEY || DEFAULTS.anonKey,
|
|
95
|
+
email,
|
|
96
|
+
password,
|
|
97
|
+
vaultPassword: e.SF_VAULT_PASSWORD || password,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Sign in (Supabase -> Bearer) then fetch + unlock the vault root key. Shared by
|
|
102
|
+
// `push` and `sync`. Network deps are imported lazily so `sf encrypt` runs
|
|
103
|
+
// without @supabase/supabase-js.
|
|
104
|
+
async function authAndUnlock(cfg) {
|
|
105
|
+
const { signIn } = await import('./auth.mjs')
|
|
106
|
+
const { fetchAndUnlockVault } = await import('./vault.mjs')
|
|
107
|
+
|
|
108
|
+
process.stderr.write('signing in…\n')
|
|
109
|
+
const { accessToken } = await signIn({
|
|
110
|
+
supabaseUrl: cfg.supabaseUrl,
|
|
111
|
+
anonKey: cfg.anonKey,
|
|
112
|
+
email: cfg.email,
|
|
113
|
+
password: cfg.password,
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
process.stderr.write('unlocking vault…\n')
|
|
117
|
+
const rootKey = await fetchAndUnlockVault({
|
|
118
|
+
apiBaseUrl: cfg.apiBaseUrl,
|
|
119
|
+
accessToken,
|
|
120
|
+
password: cfg.vaultPassword,
|
|
121
|
+
})
|
|
122
|
+
return { accessToken, rootKey }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// login -> unlock -> encrypt -> upload every file in the folder, once.
|
|
126
|
+
async function cmdPush(folder) {
|
|
127
|
+
const cfg = readLiveConfig()
|
|
128
|
+
const { uploadFile } = await import('./upload.mjs')
|
|
129
|
+
const { accessToken, rootKey } = await authAndUnlock(cfg)
|
|
130
|
+
|
|
131
|
+
for await (const { name, path, size } of filesIn(folder)) {
|
|
132
|
+
await uploadFile({
|
|
133
|
+
apiBaseUrl: cfg.apiBaseUrl,
|
|
134
|
+
accessToken,
|
|
135
|
+
rootKey,
|
|
136
|
+
name,
|
|
137
|
+
path,
|
|
138
|
+
size,
|
|
139
|
+
})
|
|
140
|
+
process.stdout.write(`pushed ${name}\n`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// login -> unlock -> mirror new/changed files into the vault, once or on a loop.
|
|
145
|
+
async function cmdSync(folder, { watch, intervalMs }) {
|
|
146
|
+
const cfg = readLiveConfig()
|
|
147
|
+
const { uploadFile } = await import('./upload.mjs')
|
|
148
|
+
const { runSync } = await import('./sync.mjs')
|
|
149
|
+
|
|
150
|
+
await runSync({
|
|
151
|
+
cfg,
|
|
152
|
+
folder,
|
|
153
|
+
watch,
|
|
154
|
+
intervalMs,
|
|
155
|
+
authAndUnlock,
|
|
156
|
+
uploadFn: uploadFile,
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Minimal parse: first non-flag arg after the command is the positional; --flag
|
|
161
|
+
// and --flag=value are collected. Enough for `sf sync <folder> --watch
|
|
162
|
+
// --interval=10`.
|
|
163
|
+
function parseArgs(argv) {
|
|
164
|
+
const positionals = []
|
|
165
|
+
const flags = {}
|
|
166
|
+
for (const token of argv) {
|
|
167
|
+
if (token.startsWith('--')) {
|
|
168
|
+
const [key, value] = token.slice(2).split('=')
|
|
169
|
+
flags[key] = value === undefined ? true : value
|
|
170
|
+
} else {
|
|
171
|
+
positionals.push(token)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { positionals, flags }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const argv = process.argv.slice(2)
|
|
178
|
+
const cmd = argv[0]
|
|
179
|
+
|
|
180
|
+
async function main() {
|
|
181
|
+
const { positionals, flags } = parseArgs(argv.slice(1))
|
|
182
|
+
const folder = positionals[0]
|
|
183
|
+
|
|
184
|
+
if (!cmd || cmd === '--help' || cmd === '-h') {
|
|
185
|
+
usage()
|
|
186
|
+
} else if (cmd === 'encrypt') {
|
|
187
|
+
if (!folder) throw new Error('encrypt needs a <folder>')
|
|
188
|
+
await cmdEncrypt(folder)
|
|
189
|
+
} else if (cmd === 'push') {
|
|
190
|
+
if (!folder) throw new Error('push needs a <folder>')
|
|
191
|
+
await cmdPush(folder)
|
|
192
|
+
} else if (cmd === 'sync') {
|
|
193
|
+
if (!folder) throw new Error('sync needs a <folder>')
|
|
194
|
+
const intervalSec = flags.interval ? Number(flags.interval) : 5
|
|
195
|
+
if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
|
|
196
|
+
throw new Error('--interval must be a positive number of seconds')
|
|
197
|
+
}
|
|
198
|
+
await cmdSync(folder, {
|
|
199
|
+
watch: Boolean(flags.watch),
|
|
200
|
+
intervalMs: Math.round(intervalSec * 1000),
|
|
201
|
+
})
|
|
202
|
+
} else {
|
|
203
|
+
usage()
|
|
204
|
+
process.exitCode = 1
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
main().catch((err) => {
|
|
209
|
+
process.stderr.write(`error: ${err.message}\n`)
|
|
210
|
+
process.exit(1)
|
|
211
|
+
})
|
package/src/sfCrypto.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// ShieldFive CLI — file encryption core (suite 0x03, PQ-hybrid).
|
|
2
|
+
//
|
|
3
|
+
// This is the VERIFIED part of the CLI: it produces ciphertext that the web and
|
|
4
|
+
// mobile apps decrypt, using the same published @shieldfive/crypto library they
|
|
5
|
+
// run. It is exercised by an encrypt -> decrypt round-trip test
|
|
6
|
+
// (test/crypto.roundtrip.test.mjs) and needs no backend to verify.
|
|
7
|
+
//
|
|
8
|
+
// Mirrors the reference offline decryptor (crypto/examples/decrypt-one.mjs):
|
|
9
|
+
// rootKey -> createIdentity (ML-KEM keypair); per-file csk is the classical
|
|
10
|
+
// "envelope key"; encryptBlob/autoDecryptBlob run suite 0x03.
|
|
11
|
+
|
|
12
|
+
import { webcrypto } from 'node:crypto'
|
|
13
|
+
|
|
14
|
+
import { autoDecryptBlob } from '@shieldfive/crypto'
|
|
15
|
+
import { createIdentity } from '@shieldfive/crypto/identity'
|
|
16
|
+
import { encryptBlob } from '@shieldfive/crypto/pq-hybrid-v1'
|
|
17
|
+
|
|
18
|
+
const CONTENT_KEY_BYTES = 32
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Derive the vault owner's ML-KEM identity from the vault root key.
|
|
22
|
+
* `rootKey` comes from unlocking the vault (see auth/unlock — needs the live
|
|
23
|
+
* API). `userId` is metadata only and does not affect the derived key bytes.
|
|
24
|
+
* @param {Uint8Array} rootKey 32-byte vault root key
|
|
25
|
+
*/
|
|
26
|
+
export async function deriveVaultIdentity(rootKey) {
|
|
27
|
+
const id = await createIdentity({
|
|
28
|
+
userId: 'shieldfive-cli',
|
|
29
|
+
masterSecret: rootKey,
|
|
30
|
+
})
|
|
31
|
+
return {
|
|
32
|
+
mlKemPublicKey: id.publicBundle.mlKemPublicKey,
|
|
33
|
+
mlKemSecretKey: id.mlKemSecretKey,
|
|
34
|
+
publicBundleBytes: id.publicBundleBytes,
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Encrypt one file's bytes for the owner's vault.
|
|
40
|
+
* Returns the encrypted blob plus the fresh per-file content key (`csk`); the
|
|
41
|
+
* app wraps `csk` under the parent folder/root key for storage.
|
|
42
|
+
* @param {Uint8Array} plaintext
|
|
43
|
+
* @param {Uint8Array} mlKemPublicKey owner identity public key (1568 bytes)
|
|
44
|
+
*/
|
|
45
|
+
export async function encryptFileForVault(plaintext, mlKemPublicKey) {
|
|
46
|
+
const csk = webcrypto.getRandomValues(new Uint8Array(CONTENT_KEY_BYTES))
|
|
47
|
+
const result = await encryptBlob({
|
|
48
|
+
blob: new Blob([plaintext]),
|
|
49
|
+
recipientPublicKey: mlKemPublicKey,
|
|
50
|
+
envelopeKey: csk,
|
|
51
|
+
})
|
|
52
|
+
return {
|
|
53
|
+
encryptedBlob: result.blob,
|
|
54
|
+
csk,
|
|
55
|
+
fileId: result.fileId,
|
|
56
|
+
suite: result.suite,
|
|
57
|
+
totalChunks: result.totalChunks,
|
|
58
|
+
plaintextSize: result.plaintextSize,
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Decrypt an encrypted blob (used for round-trip verification and reads).
|
|
64
|
+
* @param {Blob} encryptedBlob
|
|
65
|
+
* @param {Uint8Array} csk per-file content key (the classical envelope key)
|
|
66
|
+
* @param {Uint8Array} mlKemSecretKey owner identity secret key
|
|
67
|
+
* @returns {Promise<Uint8Array>}
|
|
68
|
+
*/
|
|
69
|
+
export async function decryptFileFromVault(encryptedBlob, csk, mlKemSecretKey) {
|
|
70
|
+
const result = await autoDecryptBlob({
|
|
71
|
+
blob: encryptedBlob,
|
|
72
|
+
envelopeKey: csk,
|
|
73
|
+
recipientSecretKey: mlKemSecretKey,
|
|
74
|
+
})
|
|
75
|
+
const out = result?.blob ?? result
|
|
76
|
+
return new Uint8Array(await out.arrayBuffer())
|
|
77
|
+
}
|
package/src/sync.mjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// ShieldFive CLI — `sf sync`: keep a folder mirrored into your vault.
|
|
2
|
+
//
|
|
3
|
+
// One reconcile pass uploads every file that is new or changed since the last
|
|
4
|
+
// run; `--watch` repeats the pass on an interval until interrupted. The upload
|
|
5
|
+
// protocol is unchanged — sync reuses uploadFile (direct + multipart). The new
|
|
6
|
+
// logic here is change detection: a local manifest (.shieldfive-sync.json in
|
|
7
|
+
// the synced folder) records each file's size + mtime + resulting vault fileId,
|
|
8
|
+
// so unchanged files are skipped and a crash mid-sync doesn't re-upload
|
|
9
|
+
// everything.
|
|
10
|
+
//
|
|
11
|
+
// Scope notes: change is detected by (size, mtimeMs) — the rsync default, cheap
|
|
12
|
+
// and good enough; a same-size same-mtime edit is not re-uploaded. Deletions
|
|
13
|
+
// and renames are NOT mirrored (a file removed locally stays in the vault); sync
|
|
14
|
+
// is append-only for now. Each changed file becomes a new vault upload (the
|
|
15
|
+
// server does not overwrite by name), which is the intended versioning
|
|
16
|
+
// behaviour.
|
|
17
|
+
|
|
18
|
+
import { open, readFile, readdir, rename, stat } from 'node:fs/promises'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
|
|
21
|
+
export const MANIFEST_NAME = '.shieldfive-sync.json'
|
|
22
|
+
const MANIFEST_VERSION = 1
|
|
23
|
+
|
|
24
|
+
// A file's change signature. Same string => treated as unchanged.
|
|
25
|
+
export function signatureOf({ size, mtimeMs }) {
|
|
26
|
+
return `${size}:${mtimeMs}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// List regular files to consider for sync: skips directories, dotfiles (which
|
|
30
|
+
// includes the manifest itself), and any explicitly excluded names.
|
|
31
|
+
export async function scanFiles(folder, { exclude = [] } = {}) {
|
|
32
|
+
const skip = new Set(exclude)
|
|
33
|
+
const entries = []
|
|
34
|
+
for (const name of await readdir(folder)) {
|
|
35
|
+
if (name.startsWith('.') || skip.has(name)) continue
|
|
36
|
+
const path = join(folder, name)
|
|
37
|
+
const info = await stat(path)
|
|
38
|
+
if (info.isFile()) {
|
|
39
|
+
entries.push({ name, path, size: info.size, mtimeMs: info.mtimeMs })
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return entries
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function loadManifest(manifestPath) {
|
|
46
|
+
let raw
|
|
47
|
+
try {
|
|
48
|
+
raw = await readFile(manifestPath, 'utf8')
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (err.code === 'ENOENT') return { version: MANIFEST_VERSION, files: {} }
|
|
51
|
+
throw err
|
|
52
|
+
}
|
|
53
|
+
const parsed = JSON.parse(raw)
|
|
54
|
+
return {
|
|
55
|
+
version: MANIFEST_VERSION,
|
|
56
|
+
files: parsed && typeof parsed.files === 'object' ? parsed.files : {},
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Atomic-ish write: write a temp sibling then rename over the target, so a crash
|
|
61
|
+
// during the write can't leave a half-written manifest.
|
|
62
|
+
export async function saveManifest(manifestPath, manifest) {
|
|
63
|
+
const body = JSON.stringify(
|
|
64
|
+
{ version: MANIFEST_VERSION, files: manifest.files },
|
|
65
|
+
null,
|
|
66
|
+
2,
|
|
67
|
+
)
|
|
68
|
+
const tmp = `${manifestPath}.tmp`
|
|
69
|
+
const handle = await open(tmp, 'w')
|
|
70
|
+
try {
|
|
71
|
+
await handle.writeFile(body)
|
|
72
|
+
await handle.sync()
|
|
73
|
+
} finally {
|
|
74
|
+
await handle.close()
|
|
75
|
+
}
|
|
76
|
+
await rename(tmp, manifestPath)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Pure: split scanned entries into what must upload vs what's unchanged, by
|
|
80
|
+
// comparing each entry's signature to the manifest.
|
|
81
|
+
export function planSync(entries, manifest) {
|
|
82
|
+
const toUpload = []
|
|
83
|
+
const unchanged = []
|
|
84
|
+
for (const entry of entries) {
|
|
85
|
+
const prev = manifest.files[entry.name]
|
|
86
|
+
if (prev && prev.signature === signatureOf(entry)) {
|
|
87
|
+
unchanged.push(entry)
|
|
88
|
+
} else {
|
|
89
|
+
toUpload.push(entry)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return { toUpload, unchanged }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// One reconcile pass. uploadFn is injected (defaults to the real uploadFile) so
|
|
96
|
+
// the pass is unit-testable without a network. Returns a summary and mutates
|
|
97
|
+
// `manifest` in place, persisting after each successful upload.
|
|
98
|
+
export async function syncOnce({
|
|
99
|
+
apiBaseUrl,
|
|
100
|
+
accessToken,
|
|
101
|
+
rootKey,
|
|
102
|
+
folder,
|
|
103
|
+
manifestPath,
|
|
104
|
+
manifest,
|
|
105
|
+
uploadFn,
|
|
106
|
+
log = () => {},
|
|
107
|
+
}) {
|
|
108
|
+
const entries = await scanFiles(folder, { exclude: [MANIFEST_NAME] })
|
|
109
|
+
const { toUpload, unchanged } = planSync(entries, manifest)
|
|
110
|
+
|
|
111
|
+
let uploaded = 0
|
|
112
|
+
let failed = 0
|
|
113
|
+
const errors = []
|
|
114
|
+
|
|
115
|
+
for (const entry of toUpload) {
|
|
116
|
+
try {
|
|
117
|
+
const { fileId } = await uploadFn({
|
|
118
|
+
apiBaseUrl,
|
|
119
|
+
accessToken,
|
|
120
|
+
rootKey,
|
|
121
|
+
name: entry.name,
|
|
122
|
+
path: entry.path,
|
|
123
|
+
size: entry.size,
|
|
124
|
+
})
|
|
125
|
+
manifest.files[entry.name] = {
|
|
126
|
+
signature: signatureOf(entry),
|
|
127
|
+
size: entry.size,
|
|
128
|
+
mtimeMs: entry.mtimeMs,
|
|
129
|
+
fileId,
|
|
130
|
+
uploadedAt: new Date().toISOString(),
|
|
131
|
+
}
|
|
132
|
+
await saveManifest(manifestPath, manifest)
|
|
133
|
+
uploaded += 1
|
|
134
|
+
log(`synced ${entry.name}`)
|
|
135
|
+
} catch (err) {
|
|
136
|
+
failed += 1
|
|
137
|
+
errors.push({ name: entry.name, message: err.message })
|
|
138
|
+
log(`failed ${entry.name}: ${err.message}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return { uploaded, skipped: unchanged.length, failed, errors }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function sleep(ms, signal) {
|
|
146
|
+
return new Promise((resolve) => {
|
|
147
|
+
const timer = setTimeout(resolve, ms)
|
|
148
|
+
signal?.addEventListener(
|
|
149
|
+
'abort',
|
|
150
|
+
() => {
|
|
151
|
+
clearTimeout(timer)
|
|
152
|
+
resolve()
|
|
153
|
+
},
|
|
154
|
+
{ once: true },
|
|
155
|
+
)
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Orchestrates a real sync: sign in + unlock once, then run one pass (or loop on
|
|
160
|
+
// an interval under --watch). authAndUnlock is injected so the CLI can share its
|
|
161
|
+
// sign-in/unlock path and tests can stub it.
|
|
162
|
+
export async function runSync({
|
|
163
|
+
cfg,
|
|
164
|
+
folder,
|
|
165
|
+
watch = false,
|
|
166
|
+
intervalMs = 5000,
|
|
167
|
+
authAndUnlock,
|
|
168
|
+
uploadFn,
|
|
169
|
+
log = (m) => process.stdout.write(`${m}\n`),
|
|
170
|
+
status = (m) => process.stderr.write(`${m}\n`),
|
|
171
|
+
}) {
|
|
172
|
+
const { accessToken, rootKey } = await authAndUnlock(cfg)
|
|
173
|
+
const manifestPath = join(folder, MANIFEST_NAME)
|
|
174
|
+
const manifest = await loadManifest(manifestPath)
|
|
175
|
+
|
|
176
|
+
const controller = new AbortController()
|
|
177
|
+
const onSigint = () => {
|
|
178
|
+
status('\nstopping…')
|
|
179
|
+
controller.abort()
|
|
180
|
+
}
|
|
181
|
+
if (watch) process.on('SIGINT', onSigint)
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
do {
|
|
185
|
+
const summary = await syncOnce({
|
|
186
|
+
apiBaseUrl: cfg.apiBaseUrl,
|
|
187
|
+
accessToken,
|
|
188
|
+
rootKey,
|
|
189
|
+
folder,
|
|
190
|
+
manifestPath,
|
|
191
|
+
manifest,
|
|
192
|
+
uploadFn,
|
|
193
|
+
log,
|
|
194
|
+
})
|
|
195
|
+
status(
|
|
196
|
+
`pass: ${summary.uploaded} synced, ${summary.skipped} unchanged` +
|
|
197
|
+
(summary.failed ? `, ${summary.failed} failed` : ''),
|
|
198
|
+
)
|
|
199
|
+
if (!watch || controller.signal.aborted) break
|
|
200
|
+
await sleep(intervalMs, controller.signal)
|
|
201
|
+
} while (!controller.signal.aborted)
|
|
202
|
+
} finally {
|
|
203
|
+
if (watch) process.off('SIGINT', onSigint)
|
|
204
|
+
}
|
|
205
|
+
}
|
package/src/unlock.mjs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// ShieldFive CLI — vault unlock (VERIFIED crypto).
|
|
2
|
+
//
|
|
3
|
+
// Turns your password into the vault root key, client-side, exactly the way the
|
|
4
|
+
// apps do. Mirrors crypto/examples/decrypt-one.mjs (the reference offline
|
|
5
|
+
// decryptor), so a real vault_keys row unwraps here too. Exercised by an
|
|
6
|
+
// encrypt -> unwrap round-trip test (test/unlock.roundtrip.test.mjs).
|
|
7
|
+
//
|
|
8
|
+
// The only LIVE part is fetching the vault_keys row from the server
|
|
9
|
+
// (GET the wrapped root key + KDF params); the unwrap itself is offline.
|
|
10
|
+
|
|
11
|
+
import { webcrypto } from 'node:crypto'
|
|
12
|
+
|
|
13
|
+
import { deriveMasterSecret } from '@shieldfive/crypto/kdf/argon2id'
|
|
14
|
+
|
|
15
|
+
const subtle = webcrypto.subtle
|
|
16
|
+
|
|
17
|
+
export function base64ToBytes(b64) {
|
|
18
|
+
return new Uint8Array(Buffer.from(b64, 'base64'))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function aesGcmDecrypt(key, iv, ciphertext) {
|
|
22
|
+
return new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Derive the user key (an AES-GCM key) that wraps the root key, from the
|
|
27
|
+
* password and the stored KDF parameters. Supports the legacy PBKDF2 vaults and
|
|
28
|
+
* the current Argon2id vaults.
|
|
29
|
+
*/
|
|
30
|
+
export async function deriveUserKey({
|
|
31
|
+
password,
|
|
32
|
+
salt,
|
|
33
|
+
kdf,
|
|
34
|
+
iterations,
|
|
35
|
+
argon2Preset,
|
|
36
|
+
}) {
|
|
37
|
+
if (kdf === 'pbkdf2-sha256') {
|
|
38
|
+
if (!iterations || iterations <= 0) {
|
|
39
|
+
throw new Error('PBKDF2 unwrap requires a positive iteration count')
|
|
40
|
+
}
|
|
41
|
+
const material = await subtle.importKey(
|
|
42
|
+
'raw',
|
|
43
|
+
new TextEncoder().encode(password),
|
|
44
|
+
'PBKDF2',
|
|
45
|
+
false,
|
|
46
|
+
['deriveKey'],
|
|
47
|
+
)
|
|
48
|
+
return subtle.deriveKey(
|
|
49
|
+
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations },
|
|
50
|
+
material,
|
|
51
|
+
{ name: 'AES-GCM', length: 256 },
|
|
52
|
+
false,
|
|
53
|
+
['decrypt'],
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
if (kdf === 'argon2id') {
|
|
57
|
+
if (argon2Preset !== 'moderate' && argon2Preset !== 'sensitive') {
|
|
58
|
+
throw new Error(`Unsupported Argon2id preset: ${argon2Preset}`)
|
|
59
|
+
}
|
|
60
|
+
const { masterSecret } = await deriveMasterSecret({
|
|
61
|
+
passphrase: password,
|
|
62
|
+
salt,
|
|
63
|
+
preset: argon2Preset,
|
|
64
|
+
})
|
|
65
|
+
return subtle.importKey('raw', masterSecret, { name: 'AES-GCM' }, false, [
|
|
66
|
+
'decrypt',
|
|
67
|
+
])
|
|
68
|
+
}
|
|
69
|
+
throw new Error(`Unsupported vault KDF: ${kdf}`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Unwrap the vault root key from the password. `vaultKey` carries the base64
|
|
74
|
+
* fields of the server's vault_keys row (same shape as the export bundle's
|
|
75
|
+
* vault.json): ukSalt, ukIv, ukKdf, ukIterations?, ukArgon2Preset?, rkWrappedByUk.
|
|
76
|
+
* @returns {Promise<Uint8Array>} the 32-byte root key
|
|
77
|
+
*/
|
|
78
|
+
export async function unlockRootKey({ password, vaultKey }) {
|
|
79
|
+
const uk = await deriveUserKey({
|
|
80
|
+
password,
|
|
81
|
+
salt: base64ToBytes(vaultKey.ukSalt),
|
|
82
|
+
kdf: vaultKey.ukKdf,
|
|
83
|
+
iterations: vaultKey.ukIterations,
|
|
84
|
+
argon2Preset: vaultKey.ukArgon2Preset,
|
|
85
|
+
})
|
|
86
|
+
return aesGcmDecrypt(
|
|
87
|
+
uk,
|
|
88
|
+
base64ToBytes(vaultKey.ukIv),
|
|
89
|
+
base64ToBytes(vaultKey.rkWrappedByUk),
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Recovery-key path: unwrap the root key with the base64 recovery key. */
|
|
94
|
+
export async function unlockRootKeyWithRecovery({ recoveryKeyB64, vaultKey }) {
|
|
95
|
+
const recKey = await subtle.importKey(
|
|
96
|
+
'raw',
|
|
97
|
+
base64ToBytes(recoveryKeyB64.trim()),
|
|
98
|
+
{ name: 'AES-GCM' },
|
|
99
|
+
false,
|
|
100
|
+
['decrypt'],
|
|
101
|
+
)
|
|
102
|
+
return aesGcmDecrypt(
|
|
103
|
+
recKey,
|
|
104
|
+
base64ToBytes(vaultKey.recIv),
|
|
105
|
+
base64ToBytes(vaultKey.rkWrappedByRec),
|
|
106
|
+
)
|
|
107
|
+
}
|