Compare commits
No commits in common. "master" and "v0.16.1" have entirely different histories.
541
.github/workflows/threatcrush-scan.yml
vendored
|
|
@ -1,20 +1,12 @@
|
||||||
# Managed by sh1pt Actions Fleet
|
# Managed by sh1pt Actions Fleet
|
||||||
# pack: threatcrush-scan@2.1.1
|
# pack: threatcrush-scan@1.1.0
|
||||||
# install: sh1pt-actions-store
|
# install: sh1pt-actions-store
|
||||||
# hash: sha256:66bcb069caec3c64c34bcd647b937401708e1442e742c191315a1d4c14db1611
|
# hash: sha256:8b7430185637af9aea9bef6223b7ed1754a7f1c5e0d78ad058d47832a1ac46d3
|
||||||
name: threatcrush security scan
|
name: threatcrush security scan
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
# Only what the enabled outputs actually need. Both write scopes below serve an
|
|
||||||
# optional feature — the Security tab upload and the pull request comment — and
|
|
||||||
# are omitted entirely, not disabled, when those are switched off.
|
|
||||||
#
|
|
||||||
# With uploadSarif and commentOnPr both false this reads `contents: read` and
|
|
||||||
# nothing else, and findings arrive in the job summary and the SARIF artifact.
|
|
||||||
# Those are also the two outputs that keep working on fork pull requests, where
|
|
||||||
# GitHub downgrades GITHUB_TOKEN to read-only.
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
|
@ -27,132 +19,89 @@ jobs:
|
||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
# persist-credentials: false because nothing here pushes, and the rest of
|
- uses: actions/checkout@v4
|
||||||
# this job runs a scanner installed from the network over the contents of
|
|
||||||
# a pull request. A token no step needs should not be sitting in
|
|
||||||
# .git/config while that happens.
|
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
# Two commits, so the merge ref's own parents are present and the
|
|
||||||
# report can tell this pull request's files from the rest of the tree.
|
|
||||||
fetch-depth: 2
|
|
||||||
|
|
||||||
# Which findings belong to this review?
|
- uses: actions/setup-node@v4
|
||||||
#
|
|
||||||
# The scan covers the whole tree, and it should: a credential three
|
|
||||||
# directories away is still committed. But a report is a review artifact,
|
|
||||||
# and a review is about the change under review. `refs/pull/N/merge` has
|
|
||||||
# the base branch as its first parent and the head as its second, so
|
|
||||||
# `HEAD^1..HEAD` is exactly this pull request's diff — no API call, no
|
|
||||||
# token.
|
|
||||||
#
|
|
||||||
# That identity only holds for a real merge ref. On a conflicted pull
|
|
||||||
# request GitHub cannot produce one, checkout falls back to the head
|
|
||||||
# commit, and `HEAD^1` silently becomes "the previous commit on the
|
|
||||||
# branch". So the shape is verified before it is trusted, and a failure
|
|
||||||
# reports everything unscoped rather than scoping to the wrong set.
|
|
||||||
- name: Determine which files this pull request touches
|
|
||||||
id: changed
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
if [ "$(git rev-list --parents --max-count=1 HEAD | wc -w)" -eq 3 ]; then
|
|
||||||
git diff --name-only HEAD^1 HEAD > "${RUNNER_TEMP}/threatcrush-changed.txt"
|
|
||||||
echo "scoped=true" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "Scoping the report to $(wc -l < "${RUNNER_TEMP}/threatcrush-changed.txt") changed file(s)."
|
|
||||||
else
|
|
||||||
: > "${RUNNER_TEMP}/threatcrush-changed.txt"
|
|
||||||
echo "scoped=false" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "::notice::No merge ref (conflicted pull request?) — reporting every finding, unscoped."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
|
||||||
with:
|
with:
|
||||||
node-version: "20"
|
node-version: "20"
|
||||||
|
|
||||||
# Downloaded, hashed, and only then installed. A version pin says which
|
# An unretried `npm i -g` is a network call to a registry that decides
|
||||||
# release to fetch; it does not say the bytes are the ones that release
|
# whether a security gate runs at all. Retry before giving up; a
|
||||||
# was published with, and the party answering "which version" is the same
|
# transient registry blip is not a security signal and should not read
|
||||||
# party serving the tarball.
|
# like one.
|
||||||
#
|
|
||||||
# --ignore-scripts because a lifecycle script is arbitrary code from the
|
|
||||||
# dependency tree; the CLI declares no install hook and `scan` runs
|
|
||||||
# correctly without one. Into RUNNER_TEMP rather than the checkout,
|
|
||||||
# because `npm pack` writes to the working directory by default and a
|
|
||||||
# stray .tgz is something this job would then scan.
|
|
||||||
- name: Install ThreatCrush
|
- name: Install ThreatCrush
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
|
||||||
spec='@profullstack/threatcrush@0.21.0'
|
|
||||||
want='sha512-bzkPU+cOJ52K/ltDGqVUN4BpAQ6CnToX8VDd5uU/B1/V0SqZvC/YbRHNguavKSzxLQjcIxKOwBefyVdSPlcRrA=='
|
|
||||||
|
|
||||||
# Retried: a transient registry blip is not a security signal.
|
|
||||||
name=""
|
|
||||||
for attempt in 1 2 3; do
|
for attempt in 1 2 3; do
|
||||||
if name=$(npm pack --silent --pack-destination "${RUNNER_TEMP}" "${spec}" | tail -1) \
|
if npm install -g "@profullstack/threatcrush@latest"; then
|
||||||
&& [ -n "${name}" ] && [ -f "${RUNNER_TEMP}/${name}" ]; then
|
exit 0
|
||||||
break
|
|
||||||
fi
|
fi
|
||||||
name=""
|
delay=$((attempt * 10))
|
||||||
echo "::warning::ThreatCrush download attempt ${attempt}/3 failed; retrying in $((attempt * 10))s"
|
echo "::warning::ThreatCrush install attempt ${attempt}/3 failed; retrying in ${delay}s"
|
||||||
sleep "$((attempt * 10))"
|
sleep "${delay}"
|
||||||
done
|
done
|
||||||
if [ -z "${name}" ]; then
|
echo "::error::ThreatCrush install failed after 3 attempts"
|
||||||
echo "::error::ThreatCrush download failed after 3 attempts"
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
|
||||||
|
|
||||||
# Not retried, unlike the download. A blip and a mismatch are not the
|
# Recorded into every run log so a release that changes the interface
|
||||||
# same event: one is the network, the other is the registry handing
|
# shows up immediately, rather than silently scoring zero.
|
||||||
# back bytes nobody signed off on, and retrying that just asks again
|
- name: Record the CLI interface
|
||||||
# until it succeeds.
|
run: |
|
||||||
if [ -n "${want}" ]; then
|
threatcrush --version || true
|
||||||
got="sha512-$(openssl dgst -sha512 -binary "${RUNNER_TEMP}/${name}" | openssl base64 -A)"
|
threatcrush scan --help || true
|
||||||
if [ "${got}" != "${want}" ]; then
|
|
||||||
echo "::error::ThreatCrush integrity mismatch for ${spec}"
|
# Which interface does the installed CLI actually have?
|
||||||
echo "::error::expected ${want}"
|
#
|
||||||
echo "::error::received ${got}"
|
# Determined up front rather than inferred from an exit code, because
|
||||||
echo "::error::refusing to install — this is not a transient failure"
|
# exit codes cannot tell the two failures apart. `0.2.2` has no
|
||||||
exit 1
|
# `--format`: the scan died with `error: unknown option '--format'` and
|
||||||
fi
|
# commander exited 1 — the same code the CLI uses for "findings at or
|
||||||
echo "Integrity verified for ${spec}: ${got}"
|
# above --fail-on". Read as a result, that produced a green check and a
|
||||||
|
# "0 findings" comment on a repository nothing had scanned.
|
||||||
|
- name: Detect the CLI output interface
|
||||||
|
id: iface
|
||||||
|
run: |
|
||||||
|
if threatcrush scan --help 2>&1 | grep -q -- '--format'; then
|
||||||
|
echo "native=true" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Native SARIF output available."
|
||||||
else
|
else
|
||||||
echo "::warning::no integrity hash pinned for ${spec}; installing unverified"
|
echo "native=false" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "::notice::CLI $(threatcrush --version 2>/dev/null || echo unknown) predates --format; converting terminal output instead."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
npm install -g --ignore-scripts "${RUNNER_TEMP}/${name}"
|
|
||||||
|
|
||||||
# Recorded so a release that changed the interface is visible in the
|
|
||||||
# log rather than inferred from a confusing failure downstream.
|
|
||||||
threatcrush --version
|
|
||||||
|
|
||||||
# The CLI emits SARIF itself, so this asks for it and nothing converts
|
|
||||||
# anything.
|
|
||||||
#
|
|
||||||
# There used to be a capability probe here and a 235-line Python converter
|
|
||||||
# that parsed the CLI's terminal output when the probe said no. Both are
|
|
||||||
# gone, because the premise stopped holding: `threatcrushPackageSpec` pins
|
|
||||||
# an exact version and the install step refuses any other bytes, so "which
|
|
||||||
# interface does the installed CLI have" is answered by the pack, not
|
|
||||||
# discovered at runtime.
|
|
||||||
#
|
|
||||||
# Nothing is lost by not probing. A CLI without `--format` writes no SARIF
|
|
||||||
# file, and the check below turns that into a hard failure that says the
|
|
||||||
# diff was not scanned — which is the same answer the probe gave, from
|
|
||||||
# evidence rather than from asking.
|
|
||||||
- name: Scan
|
- name: Scan
|
||||||
id: scan
|
id: scan
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -o pipefail
|
||||||
FAIL_ON=""
|
FAIL_ON=""
|
||||||
SCAN_PATH="."
|
SCAN_PATH="."
|
||||||
code=0
|
code=0
|
||||||
|
|
||||||
|
if [ "${{ steps.iface.outputs.native }}" = "true" ]; then
|
||||||
ARGS=(scan "$SCAN_PATH" --format sarif --output threatcrush.sarif)
|
ARGS=(scan "$SCAN_PATH" --format sarif --output threatcrush.sarif)
|
||||||
if [ -n "$FAIL_ON" ]; then
|
if [ -n "$FAIL_ON" ]; then
|
||||||
ARGS+=(--fail-on "$FAIL_ON")
|
ARGS+=(--fail-on "$FAIL_ON")
|
||||||
fi
|
fi
|
||||||
threatcrush "${ARGS[@]}" || code=$?
|
threatcrush "${ARGS[@]}" || code=$?
|
||||||
|
else
|
||||||
|
# Compatibility path for CLIs older than native SARIF. The
|
||||||
|
# converter fails closed: if it cannot recognise the output it
|
||||||
|
# exits non-zero and writes nothing, so an unparseable scan can
|
||||||
|
# never arrive downstream looking like a clean one.
|
||||||
|
threatcrush scan "$SCAN_PATH" 2>&1 | tee threatcrush-output.txt || true
|
||||||
|
PREFIX=""
|
||||||
|
if [ "$SCAN_PATH" != "." ]; then
|
||||||
|
# Paths in terminal output are relative to the scan root. Left
|
||||||
|
# unprefixed they resolve to nothing in the repository view, and
|
||||||
|
# every finding reads as out-of-scope.
|
||||||
|
PREFIX="$SCAN_PATH"
|
||||||
|
fi
|
||||||
|
python3 .github/threatcrush-to-sarif.py \
|
||||||
|
--input threatcrush-output.txt \
|
||||||
|
--output threatcrush.sarif \
|
||||||
|
--path-prefix "$PREFIX" \
|
||||||
|
--tool-version "$(threatcrush --version 2>/dev/null || echo unknown)" \
|
||||||
|
--fail-on "$FAIL_ON" || code=$?
|
||||||
|
fi
|
||||||
|
|
||||||
# The SARIF file is the evidence that a scan happened, and it is the
|
# The SARIF file is the evidence that a scan happened, and it is the
|
||||||
# only evidence worth trusting. An exit code says what the process
|
# only evidence worth trusting. An exit code says what the process
|
||||||
|
|
@ -165,12 +114,12 @@ jobs:
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
case "${code}" in
|
case "$code" in
|
||||||
0) echo "status=clean" >> "$GITHUB_OUTPUT" ;;
|
0) echo "status=clean" >> "$GITHUB_OUTPUT" ;;
|
||||||
# Exit 1 *with* a SARIF file is the documented "findings at or above
|
# Exit 1 *with* a SARIF file is the documented "findings at or
|
||||||
# --fail-on" result, and the CLI only returns it when --fail-on was
|
# above --fail-on" result. Without one it was caught above. The CLI
|
||||||
# passed. Propagate it: a gate that records the finding and then
|
# only returns 1 when --fail-on was passed, so propagate it: a gate
|
||||||
# lets the job pass is not a gate.
|
# that records the finding and then lets the job pass is not a gate.
|
||||||
1)
|
1)
|
||||||
echo "status=findings" >> "$GITHUB_OUTPUT"
|
echo "status=findings" >> "$GITHUB_OUTPUT"
|
||||||
exit 1
|
exit 1
|
||||||
|
|
@ -178,277 +127,165 @@ jobs:
|
||||||
*)
|
*)
|
||||||
echo "status=error" >> "$GITHUB_OUTPUT"
|
echo "status=error" >> "$GITHUB_OUTPUT"
|
||||||
echo "::error::ThreatCrush scan failed with exit code ${code} — results may be incomplete"
|
echo "::error::ThreatCrush scan failed with exit code ${code} — results may be incomplete"
|
||||||
exit "${code}"
|
exit "$code"
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
# A credential this pull request adds is never backlog, so it fails the
|
# Reached only when the scan step already failed the job. The empty run
|
||||||
# job whatever failOn says. failOn stays empty by default because the scan
|
# exists so the upload does not error on a missing file and bury the real
|
||||||
# covers the whole tree and an old finding three directories away should
|
# cause; it is not a result. The scan step has already set status=error,
|
||||||
# not block an unrelated change; this gate only looks at files the pull
|
# so the report says NOT RUN rather than rendering this as a clean scan.
|
||||||
# request itself touches, so it blocks exactly the new leak and nothing
|
- name: Ensure SARIF exists
|
||||||
# that was already there.
|
|
||||||
#
|
|
||||||
# crawlproof.com#160 is why: it committed `.env.bak-2026-07-28`, a full
|
|
||||||
# production environment, into a public repository. A report-only scan
|
|
||||||
# would have listed it in a comment beside a green check.
|
|
||||||
#
|
|
||||||
# Two triggers, both scoped to the diff:
|
|
||||||
# 1. a dotenv file (.env, .env.*, *.env, *.env.*) that holds real-looking
|
|
||||||
# secret values — checked here directly, so it does not depend on the
|
|
||||||
# scanner recognising any one key format;
|
|
||||||
# 2. any `secret-*` finding at level error in a changed file.
|
|
||||||
# A path listed in .threatcrushignore is exempt from (1); the scanner
|
|
||||||
# already honours it for (2).
|
|
||||||
- name: Block credentials this pull request adds
|
|
||||||
id: gate
|
|
||||||
if: always() && steps.scan.outputs.status != 'error' && steps.changed.outputs.scoped == 'true'
|
|
||||||
env:
|
|
||||||
SCAN_PATH: "."
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
python3 - <<'PY'
|
|
||||||
import fnmatch, json, os, re, sys
|
|
||||||
|
|
||||||
changed = [l.strip() for l in open(os.path.join(os.environ["RUNNER_TEMP"], "threatcrush-changed.txt")) if l.strip()]
|
|
||||||
present = [p for p in changed if os.path.isfile(p)] # deletions are fixes, not leaks
|
|
||||||
|
|
||||||
ignore = []
|
|
||||||
if os.path.isfile(".threatcrushignore"):
|
|
||||||
ignore = [l.strip() for l in open(".threatcrushignore") if l.strip() and not l.startswith("#")]
|
|
||||||
def ignored(p):
|
|
||||||
return any(fnmatch.fnmatch(p, g) or fnmatch.fnmatch(os.path.basename(p), g) for g in ignore)
|
|
||||||
|
|
||||||
TEMPLATE = re.compile(r"\.(example|sample|template|dist|defaults|schema)(\.|$)", re.I)
|
|
||||||
CODE = re.compile(r"\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|rb|php|java|kt|swift|md|json|ya?ml|toml|sh|d\.ts)$", re.I)
|
|
||||||
def is_env_file(p):
|
|
||||||
b = os.path.basename(p)
|
|
||||||
if TEMPLATE.search(b) or CODE.search(b):
|
|
||||||
return False
|
|
||||||
return b == ".env" or b.startswith(".env.") or b.endswith(".env") or ".env." in b
|
|
||||||
|
|
||||||
SECRET_KEY = re.compile(r"(KEY|SECRET|TOKEN|PASSWORD|PASSWD|PASS|PEPPER|PRIVATE|CREDENTIAL|DSN|AUTH)", re.I)
|
|
||||||
PLACEHOLDER = re.compile(r"^(changeme|change-me|xxx+|todo|example|placeholder|dummy|test|none|null|your[-_].*|<.*>|\$\{.*\}|\*+)$", re.I)
|
|
||||||
def secret_lines(p):
|
|
||||||
hits = []
|
|
||||||
try:
|
|
||||||
lines = open(p, errors="replace").read().splitlines()
|
|
||||||
except OSError:
|
|
||||||
return hits
|
|
||||||
for n, line in enumerate(lines, 1):
|
|
||||||
m = re.match(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$", line)
|
|
||||||
if not m or not SECRET_KEY.search(m.group(1)):
|
|
||||||
continue
|
|
||||||
v = m.group(2).strip().strip("'\"")
|
|
||||||
if len(v) < 8 or PLACEHOLDER.match(v) or len(set(v)) == 1:
|
|
||||||
continue
|
|
||||||
hits.append(n)
|
|
||||||
return hits
|
|
||||||
|
|
||||||
problems = []
|
|
||||||
for p in present:
|
|
||||||
if is_env_file(p) and not ignored(p):
|
|
||||||
hits = secret_lines(p)
|
|
||||||
if hits:
|
|
||||||
problems.append((p, hits[0], "committed-env-file",
|
|
||||||
f"dotenv file with {len(hits)} secret-looking value(s) is committed; secrets belong in the vault, not git"))
|
|
||||||
|
|
||||||
try:
|
|
||||||
results = json.load(open("threatcrush.sarif"))["runs"][0]["results"]
|
|
||||||
except Exception as err:
|
|
||||||
print(f"::error::could not read threatcrush.sarif ({err}); refusing to pass the credential gate")
|
|
||||||
sys.exit(1)
|
|
||||||
prefix = os.environ.get("SCAN_PATH", ".").strip().strip("/")
|
|
||||||
wanted = set(present)
|
|
||||||
for r in results:
|
|
||||||
rule = r.get("ruleId", "")
|
|
||||||
if not rule.startswith("secret-") or r.get("level") != "error":
|
|
||||||
continue
|
|
||||||
loc = r["locations"][0]["physicalLocation"]
|
|
||||||
uri = loc["artifactLocation"]["uri"]
|
|
||||||
path = os.path.normpath(os.path.join(prefix, uri)) if prefix not in ("", ".") else os.path.normpath(uri)
|
|
||||||
if path in wanted:
|
|
||||||
problems.append((path, loc.get("region", {}).get("startLine", 1), rule, "credential added by this pull request"))
|
|
||||||
|
|
||||||
if not problems:
|
|
||||||
print(f"No credentials added in {len(present)} changed file(s).")
|
|
||||||
sys.exit(0)
|
|
||||||
for path, line, rule, msg in problems:
|
|
||||||
print(f"::error file={path},line={line},title=ThreatCrush {rule}::{msg}")
|
|
||||||
print(f"::error::{len(problems)} credential finding(s) in files this pull request changes. "
|
|
||||||
"Remove them from the branch AND rotate them: anything pushed to a pull request is already exposed.")
|
|
||||||
sys.exit(1)
|
|
||||||
PY
|
|
||||||
|
|
||||||
- name: Build the report
|
|
||||||
if: always()
|
if: always()
|
||||||
env:
|
|
||||||
SCAN_STATUS: ${{ steps.scan.outputs.status }}
|
|
||||||
# Empty when the changed-file step was skipped or found no merge ref,
|
|
||||||
# which reads as "not scoped" and reports everything.
|
|
||||||
SCAN_SCOPED: ${{ steps.changed.outputs.scoped }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
if [ ! -f threatcrush.sarif ]; then
|
||||||
python3 - <<'PY' > "${RUNNER_TEMP}/threatcrush-report.md"
|
cat > threatcrush.sarif <<'JSON'
|
||||||
import json, os, sys
|
{
|
||||||
|
"version": "2.1.0",
|
||||||
|
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
||||||
|
"runs": [{ "tool": { "driver": { "name": "ThreatCrush", "rules": [] } }, "results": [] }]
|
||||||
|
}
|
||||||
|
JSON
|
||||||
|
fi
|
||||||
|
|
||||||
LABELS = {"error": "HIGH", "warning": "MEDIUM", "note": "LOW"}
|
|
||||||
# Most serious first. SARIF order is file order, so the row cap would
|
|
||||||
# otherwise be decided by where a finding happens to sit in the tree —
|
|
||||||
# a HIGH in the last file cut while fifty LOWs from the first print.
|
|
||||||
RANK = {"error": 0, "warning": 1, "note": 2}
|
|
||||||
|
|
||||||
def locate(result):
|
|
||||||
# SARIF permits a result with no locations; indexing [0] unguarded
|
|
||||||
# threw, and the run reported "could not be read" instead of the
|
|
||||||
# findings it actually had.
|
|
||||||
where = (result.get("locations") or [{}])[0].get("physicalLocation", {})
|
|
||||||
return (where.get("artifactLocation", {}).get("uri", ""),
|
|
||||||
where.get("region", {}).get("startLine", 1))
|
|
||||||
|
|
||||||
def tally(rows):
|
|
||||||
seen = {k: sum(1 for r in rows if r.get("level", "warning") == k) for k in LABELS}
|
|
||||||
return " | ".join(f"**{LABELS[k]}**: {seen[k]}" for k in LABELS if seen[k])
|
|
||||||
|
|
||||||
def table(rows, limit):
|
|
||||||
out = ["| Severity | Rule | Location |", "|---|---|---|"]
|
|
||||||
for result in rows[:limit]:
|
|
||||||
uri, line = locate(result)
|
|
||||||
where = f"`{uri}`:{line}" if uri else "_(no location)_"
|
|
||||||
out.append(f"| {LABELS.get(result.get('level', 'warning'), 'INFO')} "
|
|
||||||
f"| `{result.get('ruleId', '?')}` | {where} |")
|
|
||||||
if len(rows) > limit:
|
|
||||||
# Say so. A silent truncation reads as "that was everything".
|
|
||||||
out += ["", f"_…and {len(rows) - limit} more; the full set is in the SARIF artifact._"]
|
|
||||||
return out
|
|
||||||
|
|
||||||
status = os.environ.get("SCAN_STATUS", "")
|
|
||||||
try:
|
|
||||||
results = json.load(open("threatcrush.sarif"))["runs"][0]["results"]
|
|
||||||
except Exception as err:
|
|
||||||
# stderr, not stdout: stdout is the report file.
|
|
||||||
print(f"::warning::could not read SARIF: {err}", file=sys.stderr)
|
|
||||||
results = None
|
|
||||||
|
|
||||||
out = ["## ThreatCrush Security Scan", ""]
|
|
||||||
|
|
||||||
# Fail closed. `status` is the empty string when an earlier step failed
|
|
||||||
# and the scan was *skipped*, and an earlier version read that as
|
|
||||||
# "no findings" — a clean report on a diff nothing had examined. Any
|
|
||||||
# state that is not a known-good outcome is NOT RUN.
|
|
||||||
if status not in ("clean", "findings") or results is None:
|
|
||||||
out += ["**NOT RUN** — the scan did not complete, so this diff was not examined.",
|
|
||||||
"This is not a clean result. See the job log."]
|
|
||||||
elif not results:
|
|
||||||
out.append("No findings.")
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
changed = set(open(os.environ["RUNNER_TEMP"] + "/threatcrush-changed.txt").read().split())
|
|
||||||
except Exception:
|
|
||||||
changed = set()
|
|
||||||
|
|
||||||
scoped = os.environ.get("SCAN_SCOPED", "") == "true"
|
|
||||||
results.sort(key=lambda r: (RANK.get(r.get("level", "warning"), 3), locate(r)))
|
|
||||||
touched = [r for r in results if locate(r)[0] in changed] if scoped else results
|
|
||||||
backlog = [r for r in results if locate(r)[0] not in changed] if scoped else []
|
|
||||||
|
|
||||||
out += [f"**{len(touched)}** finding(s) in the {len(changed)} file(s) this pull request changes."
|
|
||||||
if scoped else f"**{len(results)}** finding(s)", ""]
|
|
||||||
|
|
||||||
if touched:
|
|
||||||
badges = tally(touched)
|
|
||||||
out += ([badges, ""] if badges else []) + table(touched, 50)
|
|
||||||
elif scoped:
|
|
||||||
out.append("Nothing in the files this pull request changes.")
|
|
||||||
|
|
||||||
# The rest of the repository is reported, but not *at* the author
|
|
||||||
# of an unrelated change. It is a standing backlog, it was there
|
|
||||||
# before this branch, and it belongs behind a fold.
|
|
||||||
if backlog:
|
|
||||||
out += ["", "<details>",
|
|
||||||
f"<summary>{len(backlog)} pre-existing finding(s) elsewhere in the repository"
|
|
||||||
f" — {tally(backlog) or 'no severities'}</summary>", "",
|
|
||||||
"Not introduced by this pull request.", ""]
|
|
||||||
out += table(backlog, 20) + ["", "</details>"]
|
|
||||||
|
|
||||||
out += ["", "Snippets are redacted; ThreatCrush never prints matched credential material."]
|
|
||||||
|
|
||||||
print("\n".join(out))
|
|
||||||
PY
|
|
||||||
cat "${RUNNER_TEMP}/threatcrush-report.md" >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
|
|
||||||
# if-no-files-found: ignore, because nothing synthesises the file. A run
|
|
||||||
# that never produced SARIF has no artifact to keep, and that is the
|
|
||||||
# honest outcome rather than a reason to invent one.
|
|
||||||
- name: Upload SARIF artifact
|
|
||||||
if: always()
|
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
|
||||||
with:
|
|
||||||
name: threatcrush-sarif
|
|
||||||
path: threatcrush.sarif
|
|
||||||
if-no-files-found: ignore
|
|
||||||
retention-days: 30
|
|
||||||
|
|
||||||
# Never on a failed or empty run. Code scanning treats a new analysis in a
|
|
||||||
# category as the current truth for that category, so an empty run does
|
|
||||||
# not read as "no data" — it resolves every open ThreatCrush alert the
|
|
||||||
# repository already had. A scanner that fails and marks the findings it
|
|
||||||
# previously reported as fixed is worse than one that does not run.
|
|
||||||
- name: Upload to the Security tab
|
- name: Upload to the Security tab
|
||||||
if: >-
|
if: always() && 'true' == 'true'
|
||||||
always()
|
|
||||||
&& (steps.scan.outputs.status == 'clean' || steps.scan.outputs.status == 'findings')
|
|
||||||
&& hashFiles('threatcrush.sarif') != ''
|
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: github/codeql-action/upload-sarif@f3712979fa5f215279b101dd0a2e3bdfb4353324 # v3
|
uses: github/codeql-action/upload-sarif@v3
|
||||||
with:
|
with:
|
||||||
sarif_file: threatcrush.sarif
|
sarif_file: threatcrush.sarif
|
||||||
category: threatcrush
|
category: threatcrush
|
||||||
|
|
||||||
# Best-effort. `pull_request` gives fork pull requests a read-only token,
|
- name: Build the report
|
||||||
# so this 403s on fork submissions — the report is in the job summary
|
if: always()
|
||||||
# either way, and pass/fail is decided by the scan step, not by whether a
|
run: |
|
||||||
# comment posted. Deliberately NOT pull_request_target to get a writable
|
python3 << 'PYEOF'
|
||||||
# token: that event runs with repository secrets in scope against a
|
import json, os
|
||||||
# checkout of untrusted contributor code.
|
|
||||||
|
status = os.environ.get("SCAN_STATUS", "")
|
||||||
|
try:
|
||||||
|
with open("threatcrush.sarif") as handle:
|
||||||
|
results = json.load(handle)["runs"][0]["results"]
|
||||||
|
except Exception as err:
|
||||||
|
results = None
|
||||||
|
print(f"::warning::could not read SARIF: {err}")
|
||||||
|
|
||||||
|
lines = ["## ThreatCrush Security Scan", ""]
|
||||||
|
|
||||||
|
# Fail closed: render findings only on positive evidence that a scan
|
||||||
|
# completed. Testing for `status == "error"` was fail-open and got
|
||||||
|
# caught immediately — when the capability check failed, the scan
|
||||||
|
# step was *skipped*, so `status` was the empty string rather than
|
||||||
|
# "error", and the comment cheerfully reported "0 findings" for a
|
||||||
|
# scan that never started. Any state that is not a known-good
|
||||||
|
# outcome is NOT RUN.
|
||||||
|
if status not in ("clean", "findings") or results is None:
|
||||||
|
# Never render "no issues found" for a scan that did not finish.
|
||||||
|
# An unexamined diff is not a clean one, and the two are
|
||||||
|
# indistinguishable to whoever reads the comment.
|
||||||
|
lines += [
|
||||||
|
"**NOT RUN** — the scan did not complete, so this diff was not examined.",
|
||||||
|
"This is not a clean result. See the job log.",
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
counts = {"error": 0, "warning": 0, "note": 0}
|
||||||
|
for result in results:
|
||||||
|
level = result.get("level", "warning")
|
||||||
|
if level in counts:
|
||||||
|
counts[level] += 1
|
||||||
|
|
||||||
|
lines.append(f"**{len(results)}** finding(s)")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
if results:
|
||||||
|
badges = []
|
||||||
|
if counts["error"]:
|
||||||
|
badges.append(f"**HIGH/CRITICAL**: {counts['error']}")
|
||||||
|
if counts["warning"]:
|
||||||
|
badges.append(f"**MEDIUM**: {counts['warning']}")
|
||||||
|
if counts["note"]:
|
||||||
|
badges.append(f"**LOW**: {counts['note']}")
|
||||||
|
if badges:
|
||||||
|
lines += [" | ".join(badges), ""]
|
||||||
|
|
||||||
|
lines += ["| Severity | Rule | Location |", "|---|---|---|"]
|
||||||
|
for result in results[:50]:
|
||||||
|
location = result["locations"][0]["physicalLocation"]
|
||||||
|
uri = location["artifactLocation"]["uri"]
|
||||||
|
line_no = location.get("region", {}).get("startLine", 1)
|
||||||
|
label = {"error": "HIGH", "warning": "MEDIUM", "note": "LOW"}.get(
|
||||||
|
result.get("level", "warning"), "INFO"
|
||||||
|
)
|
||||||
|
lines.append(f"| {label} | `{result.get('ruleId','?')}` | `{uri}`:{line_no} |")
|
||||||
|
if len(results) > 50:
|
||||||
|
# Say so. A silent truncation reads as "that was everything".
|
||||||
|
lines += ["", f"_…and {len(results) - 50} more. Full results in the Security tab._"]
|
||||||
|
lines += ["", "Snippets are redacted; ThreatCrush never prints matched credential material."]
|
||||||
|
else:
|
||||||
|
lines.append("No findings.")
|
||||||
|
|
||||||
|
with open(os.environ["RUNNER_TEMP"] + "/threatcrush-comment.md", "w") as handle:
|
||||||
|
handle.write("\n".join(lines) + "\n")
|
||||||
|
PYEOF
|
||||||
|
env:
|
||||||
|
SCAN_STATUS: ${{ steps.scan.outputs.status }}
|
||||||
|
|
||||||
|
- name: Write report to job summary
|
||||||
|
if: always()
|
||||||
|
run: cat "$RUNNER_TEMP/threatcrush-comment.md" >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||||
|
|
||||||
|
- name: Upload SARIF artifact
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: threatcrush-sarif
|
||||||
|
path: threatcrush.sarif
|
||||||
|
retention-days: 30
|
||||||
|
|
||||||
|
# Best-effort. `pull_request` gives fork PRs a read-only token, so this
|
||||||
|
# 403s on fork submissions — the report is in the job summary either way,
|
||||||
|
# and the scan's pass/fail is decided by the scan step, not by whether a
|
||||||
|
# comment posted. Deliberately NOT switching to pull_request_target to
|
||||||
|
# get a writable token: that event runs with repository secrets in scope
|
||||||
|
# against a checkout of untrusted contributor code.
|
||||||
- name: Comment on PR
|
- name: Comment on PR
|
||||||
if: >-
|
if: always() && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]'
|
||||||
always()
|
|
||||||
&& github.event.pull_request.head.repo.full_name == github.repository
|
|
||||||
&& github.actor != 'dependabot[bot]'
|
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
uses: actions/github-script@v7
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = fs.readFileSync(`${process.env.RUNNER_TEMP}/threatcrush-report.md`, 'utf8');
|
body = fs.readFileSync(`${process.env.RUNNER_TEMP}/threatcrush-comment.md`, 'utf8');
|
||||||
} catch {
|
} catch {
|
||||||
body = '## ThreatCrush Security Scan\n\nScan completed but the report could not be read.';
|
body = '## ThreatCrush Security Scan\n\nScan completed but the report could not be read.';
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Paginated. listComments returns the first thirty and stops, so
|
const { data: comments } = await github.rest.issues.listComments({
|
||||||
// on a pull request with more discussion than that the existing
|
|
||||||
// report falls off the page, is not found, and every run posts
|
|
||||||
// another one. The bug only appears on the requests people
|
|
||||||
// actually engage with, which is the worst place for it.
|
|
||||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
|
||||||
issue_number: context.issue.number,
|
issue_number: context.issue.number,
|
||||||
owner: context.repo.owner,
|
owner: context.repo.owner,
|
||||||
repo: context.repo.repo,
|
repo: context.repo.repo,
|
||||||
per_page: 100,
|
|
||||||
});
|
});
|
||||||
const existing = comments.find(
|
const existing = comments.find(
|
||||||
(c) => c.user.type === 'Bot' && c.body.includes('ThreatCrush Security Scan'),
|
(c) => c.user.type === 'Bot' && c.body.includes('ThreatCrush Security Scan'),
|
||||||
);
|
);
|
||||||
const target = { owner: context.repo.owner, repo: context.repo.repo, body };
|
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
await github.rest.issues.updateComment({ ...target, comment_id: existing.id });
|
await github.rest.issues.updateComment({
|
||||||
|
comment_id: existing.id,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
body,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
await github.rest.issues.createComment({ ...target, issue_number: context.issue.number });
|
await github.rest.issues.createComment({
|
||||||
|
issue_number: context.issue.number,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
body,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
core.warning(
|
core.warning(
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@
|
||||||
"@profullstack/autoblog": "^0.5.0",
|
"@profullstack/autoblog": "^0.5.0",
|
||||||
"@profullstack/footer": "latest",
|
"@profullstack/footer": "latest",
|
||||||
"@profullstack/stack": "^0.5.0",
|
"@profullstack/stack": "^0.5.0",
|
||||||
"@profullstack/x402-gateway": "^0.20.0",
|
"@profullstack/x402-gateway": "^0.18.1",
|
||||||
"@supabase/supabase-js": "^2.118.0",
|
"@supabase/supabase-js": "^2.118.0",
|
||||||
"marked": "^18.1.1",
|
"marked": "^18.1.1",
|
||||||
"next": "16.4.3",
|
"next": "16.4.3",
|
||||||
|
|
|
||||||
BIN
apps/logicsrc-web/public/openicon/set/hq/png/128/vu1nz.png
Normal file
|
After Width: | Height: | Size: 1 KiB |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/16/vu1nz.png
Normal file
|
After Width: | Height: | Size: 205 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/20/vu1nz.png
Normal file
|
After Width: | Height: | Size: 285 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/24/vu1nz.png
Normal file
|
After Width: | Height: | Size: 273 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/256/vu1nz.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/32/vu1nz.png
Normal file
|
After Width: | Height: | Size: 285 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/48/vu1nz.png
Normal file
|
After Width: | Height: | Size: 427 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/png/64/vu1nz.png
Normal file
|
After Width: | Height: | Size: 523 B |
1
apps/logicsrc-web/public/openicon/set/hq/svg/vu1nz.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#5865F2"><title>vu1nz.com</title><g transform="translate(2 2) scale(0.3125)"><path d="M32 12L20 18v12c0 7.5 5.2 14.5 12 16 6.8-1.5 12-8.5 12-16V18L32 12z"/><path d="M27 30l3 3 7-7"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 259 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/webp/128/vu1nz.webp
Normal file
|
After Width: | Height: | Size: 688 B |
BIN
apps/logicsrc-web/public/openicon/set/hq/webp/64/vu1nz.webp
Normal file
|
After Width: | Height: | Size: 470 B |
|
|
@ -33,7 +33,7 @@
|
||||||
"nerd-fonts": "Nerd Fonts 3.4.0 glyph names (MIT)",
|
"nerd-fonts": "Nerd Fonts 3.4.0 glyph names (MIT)",
|
||||||
"simple-icons": "Simple Icons 16.32.0 (CC0-1.0)",
|
"simple-icons": "Simple Icons 16.32.0 (CC0-1.0)",
|
||||||
"font-awesome": "Font Awesome Free 7.3.1 brands (CC-BY-4.0)",
|
"font-awesome": "Font Awesome Free 7.3.1 brands (CC-BY-4.0)",
|
||||||
"profullstack-services": "79 Profullstack property marks; source URLs are recorded per icon"
|
"profullstack-services": "80 Profullstack property marks; source URLs are recorded per icon"
|
||||||
},
|
},
|
||||||
"categories": {
|
"categories": {
|
||||||
"action": "Actions",
|
"action": "Actions",
|
||||||
|
|
@ -19792,6 +19792,65 @@
|
||||||
"hex_source": "https://ugig.net/favicon.svg"
|
"hex_source": "https://ugig.net/favicon.svg"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "vu1nz",
|
||||||
|
"name": "vu1nz.com",
|
||||||
|
"category": "brand",
|
||||||
|
"brand": true,
|
||||||
|
"trademark": "vu1nz.com and its logo are trademarks of their owner. Use them to refer to vu1nz.com, not to imply endorsement.",
|
||||||
|
"source": "profullstack-service:vu1nz.com",
|
||||||
|
"source_url": "https://vu1nz.com/favicon.svg",
|
||||||
|
"license": "Profullstack, Inc. service mark",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "svg/vu1nz.svg",
|
||||||
|
"png": "png/{size}/vu1nz.png",
|
||||||
|
"tui": {
|
||||||
|
"unicode": "V",
|
||||||
|
"ascii": "vu1"
|
||||||
|
},
|
||||||
|
"styles": {
|
||||||
|
"hq": {
|
||||||
|
"png": "hq/png/{size}/vu1nz.png",
|
||||||
|
"webp": "hq/webp/{size}/vu1nz.webp",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "hq/svg/vu1nz.svg",
|
||||||
|
"hex": "#5865F2",
|
||||||
|
"hex_source": "https://vu1nz.com/favicon.svg"
|
||||||
|
},
|
||||||
|
"agentic-matte": {
|
||||||
|
"png": "styles/agentic-matte/png/{size}/vu1nz.png",
|
||||||
|
"webp": "styles/agentic-matte/webp/{size}/vu1nz.webp",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "styles/agentic-matte/svg/vu1nz.svg",
|
||||||
|
"hex": "#5865F2",
|
||||||
|
"hex_source": "https://vu1nz.com/favicon.svg"
|
||||||
|
},
|
||||||
|
"agentic-machined": {
|
||||||
|
"png": "styles/agentic-machined/png/{size}/vu1nz.png",
|
||||||
|
"webp": "styles/agentic-machined/webp/{size}/vu1nz.webp",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "styles/agentic-machined/svg/vu1nz.svg",
|
||||||
|
"hex": "#5865F2",
|
||||||
|
"hex_source": "https://vu1nz.com/favicon.svg"
|
||||||
|
},
|
||||||
|
"agentic-emissive": {
|
||||||
|
"png": "styles/agentic-emissive/png/{size}/vu1nz.png",
|
||||||
|
"webp": "styles/agentic-emissive/webp/{size}/vu1nz.webp",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "styles/agentic-emissive/svg/vu1nz.svg",
|
||||||
|
"hex": "#5865F2",
|
||||||
|
"hex_source": "https://vu1nz.com/favicon.svg"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"hq": {
|
||||||
|
"png": "hq/png/{size}/vu1nz.png",
|
||||||
|
"webp": "hq/webp/{size}/vu1nz.webp",
|
||||||
|
"made_by": "human",
|
||||||
|
"svg": "hq/svg/vu1nz.svg",
|
||||||
|
"hex": "#5865F2",
|
||||||
|
"hex_source": "https://vu1nz.com/favicon.svg"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "weedforcrypto",
|
"key": "weedforcrypto",
|
||||||
"name": "weedforcrypto.com",
|
"name": "weedforcrypto.com",
|
||||||
|
|
@ -23011,8 +23070,8 @@
|
||||||
"ai_provider": "OpenAI",
|
"ai_provider": "OpenAI",
|
||||||
"ai_prompt_url": "hq/style.txt",
|
"ai_prompt_url": "hq/style.txt",
|
||||||
"coverage": {
|
"coverage": {
|
||||||
"total": 451,
|
"total": 452,
|
||||||
"done": 451
|
"done": 452
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"agentic-matte": {
|
"agentic-matte": {
|
||||||
|
|
@ -23039,8 +23098,8 @@
|
||||||
"ai_provider": "OpenAI",
|
"ai_provider": "OpenAI",
|
||||||
"ai_prompt_url": "styles/agentic-matte/style.txt",
|
"ai_prompt_url": "styles/agentic-matte/style.txt",
|
||||||
"coverage": {
|
"coverage": {
|
||||||
"total": 451,
|
"total": 452,
|
||||||
"done": 451
|
"done": 452
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"agentic-machined": {
|
"agentic-machined": {
|
||||||
|
|
@ -23067,8 +23126,8 @@
|
||||||
"ai_provider": "OpenAI",
|
"ai_provider": "OpenAI",
|
||||||
"ai_prompt_url": "styles/agentic-machined/style.txt",
|
"ai_prompt_url": "styles/agentic-machined/style.txt",
|
||||||
"coverage": {
|
"coverage": {
|
||||||
"total": 451,
|
"total": 452,
|
||||||
"done": 451
|
"done": 452
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"agentic-emissive": {
|
"agentic-emissive": {
|
||||||
|
|
@ -23095,8 +23154,8 @@
|
||||||
"ai_provider": "OpenAI",
|
"ai_provider": "OpenAI",
|
||||||
"ai_prompt_url": "styles/agentic-emissive/style.txt",
|
"ai_prompt_url": "styles/agentic-emissive/style.txt",
|
||||||
"coverage": {
|
"coverage": {
|
||||||
"total": 451,
|
"total": 452,
|
||||||
"done": 451
|
"done": 452
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -23124,8 +23183,8 @@
|
||||||
"ai_provider": "OpenAI",
|
"ai_provider": "OpenAI",
|
||||||
"ai_prompt_url": "hq/style.txt",
|
"ai_prompt_url": "hq/style.txt",
|
||||||
"coverage": {
|
"coverage": {
|
||||||
"total": 451,
|
"total": 452,
|
||||||
"done": 451
|
"done": 452
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
BIN
apps/logicsrc-web/public/openicon/set/png/128/vu1nz.png
Normal file
|
After Width: | Height: | Size: 1 KiB |
BIN
apps/logicsrc-web/public/openicon/set/png/16/vu1nz.png
Normal file
|
After Width: | Height: | Size: 201 B |
BIN
apps/logicsrc-web/public/openicon/set/png/20/vu1nz.png
Normal file
|
After Width: | Height: | Size: 283 B |
BIN
apps/logicsrc-web/public/openicon/set/png/24/vu1nz.png
Normal file
|
After Width: | Height: | Size: 264 B |
BIN
apps/logicsrc-web/public/openicon/set/png/256/vu1nz.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
apps/logicsrc-web/public/openicon/set/png/32/vu1nz.png
Normal file
|
After Width: | Height: | Size: 286 B |
BIN
apps/logicsrc-web/public/openicon/set/png/48/vu1nz.png
Normal file
|
After Width: | Height: | Size: 415 B |
BIN
apps/logicsrc-web/public/openicon/set/png/64/vu1nz.png
Normal file
|
After Width: | Height: | Size: 518 B |
|
After Width: | Height: | Size: 1 KiB |
|
After Width: | Height: | Size: 205 B |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 273 B |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 427 B |
|
After Width: | Height: | Size: 523 B |
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#5865F2"><title>vu1nz.com</title><g transform="translate(2 2) scale(0.3125)"><path d="M32 12L20 18v12c0 7.5 5.2 14.5 12 16 6.8-1.5 12-8.5 12-16V18L32 12z"/><path d="M27 30l3 3 7-7"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 259 B |
|
After Width: | Height: | Size: 688 B |
|
After Width: | Height: | Size: 470 B |
|
After Width: | Height: | Size: 1 KiB |
|
After Width: | Height: | Size: 205 B |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 273 B |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 427 B |
|
After Width: | Height: | Size: 523 B |
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#5865F2"><title>vu1nz.com</title><g transform="translate(2 2) scale(0.3125)"><path d="M32 12L20 18v12c0 7.5 5.2 14.5 12 16 6.8-1.5 12-8.5 12-16V18L32 12z"/><path d="M27 30l3 3 7-7"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 259 B |
|
After Width: | Height: | Size: 688 B |
|
After Width: | Height: | Size: 470 B |
|
After Width: | Height: | Size: 1 KiB |
|
After Width: | Height: | Size: 205 B |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 273 B |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 427 B |
|
After Width: | Height: | Size: 523 B |
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#5865F2"><title>vu1nz.com</title><g transform="translate(2 2) scale(0.3125)"><path d="M32 12L20 18v12c0 7.5 5.2 14.5 12 16 6.8-1.5 12-8.5 12-16V18L32 12z"/><path d="M27 30l3 3 7-7"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 259 B |
|
After Width: | Height: | Size: 688 B |
|
After Width: | Height: | Size: 470 B |
1
apps/logicsrc-web/public/openicon/set/svg/vu1nz.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><title>vu1nz.com</title><g transform="translate(2 2) scale(0.3125)"><path d="M32 12L20 18v12c0 7.5 5.2 14.5 12 16 6.8-1.5 12-8.5 12-16V18L32 12z"/><path d="M27 30l3 3 7-7"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 264 B |
|
|
@ -1,6 +1,5 @@
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { json } from "@/lib/http";
|
import { json } from "@/lib/http";
|
||||||
import { COINPAY_UA } from "@/lib/coinpay-ua";
|
|
||||||
import { COINPAY_SESSION_COOKIE, parseJson, verifySession } from "@/lib/coinpay";
|
import { COINPAY_SESSION_COOKIE, parseJson, verifySession } from "@/lib/coinpay";
|
||||||
import { HIRE_US_PRODUCT } from "@/lib/coinpay-webhook";
|
import { HIRE_US_PRODUCT } from "@/lib/coinpay-webhook";
|
||||||
import { hireUsCheckoutStore } from "@/lib/hire-us-payments";
|
import { hireUsCheckoutStore } from "@/lib/hire-us-payments";
|
||||||
|
|
@ -76,8 +75,7 @@ export async function POST(request: NextRequest) {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
authorization: `Bearer ${apiKey}`,
|
authorization: `Bearer ${apiKey}`,
|
||||||
"content-type": "application/json",
|
"content-type": "application/json"
|
||||||
"user-agent": COINPAY_UA
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
amount: amountUsdDue,
|
amount: amountUsdDue,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { json } from "@/lib/http";
|
import { json } from "@/lib/http";
|
||||||
import { COINPAY_UA } from "@/lib/coinpay-ua";
|
|
||||||
import {
|
import {
|
||||||
COINPAY_OAUTH_STATE_COOKIE,
|
COINPAY_OAUTH_STATE_COOKIE,
|
||||||
COINPAY_SESSION_COOKIE,
|
COINPAY_SESSION_COOKIE,
|
||||||
|
|
@ -50,7 +49,7 @@ export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const tokenResponse = await fetch(new URL("/api/oauth/token", config.issuer), {
|
const tokenResponse = await fetch(new URL("/api/oauth/token", config.issuer), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": COINPAY_UA },
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code,
|
code,
|
||||||
|
|
@ -71,7 +70,7 @@ export async function GET(request: NextRequest) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const userResponse = await fetch(new URL("/api/oauth/userinfo", config.issuer), {
|
const userResponse = await fetch(new URL("/api/oauth/userinfo", config.issuer), {
|
||||||
headers: { authorization: `Bearer ${tokenPayload.access_token}`, "user-agent": COINPAY_UA }
|
headers: { authorization: `Bearer ${tokenPayload.access_token}` }
|
||||||
});
|
});
|
||||||
const userText = await userResponse.text();
|
const userText = await userResponse.text();
|
||||||
const userInfo = userResponse.ok ? parseJson(userText) : {};
|
const userInfo = userResponse.ok ? parseJson(userText) : {};
|
||||||
|
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import pkg from "../../package.json";
|
|
||||||
|
|
||||||
/** Sent on every server-side call to CoinPay so its logs and throttle can tell this app apart. */
|
|
||||||
export const COINPAY_UA = `logicsrc.com/${pkg.version} (+https://logicsrc.com)`;
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||||
import { COINPAY_UA } from "./coinpay-ua";
|
|
||||||
|
|
||||||
// Server-side CoinPay + session helpers, ported from the legacy server.js so the
|
// Server-side CoinPay + session helpers, ported from the legacy server.js so the
|
||||||
// Next API routes keep identical behavior (eligibility-driven payment rails,
|
// Next API routes keep identical behavior (eligibility-driven payment rails,
|
||||||
|
|
@ -49,7 +48,7 @@ export async function fetchMerchantEligibility(
|
||||||
const url = new URL("/api/payments/merchant-eligibility", apiUrl);
|
const url = new URL("/api/payments/merchant-eligibility", apiUrl);
|
||||||
url.searchParams.set("merchant_id", merchantId);
|
url.searchParams.set("merchant_id", merchantId);
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
headers: { authorization: `Bearer ${apiKey ?? ""}`, "user-agent": COINPAY_UA }
|
headers: { authorization: `Bearer ${apiKey ?? ""}` }
|
||||||
});
|
});
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
const payload = parseJson(text);
|
const payload = parseJson(text);
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@
|
||||||
// rotation_auto_paid_until NULL with the switch on means it was flipped by hand
|
// rotation_auto_paid_until NULL with the switch on means it was flipped by hand
|
||||||
// (a comp): it never expires and a payment does not cap it.
|
// (a comp): it never expires and a payment does not cap it.
|
||||||
import { CoinPay, readWebhook } from "@profullstack/coinpay-onboard";
|
import { CoinPay, readWebhook } from "@profullstack/coinpay-onboard";
|
||||||
import { COINPAY_UA } from "./coinpay-ua.mjs";
|
|
||||||
import { createAutoRotation, sqlStore, resendMailer, DAY_MS } from "@profullstack/key-rotation";
|
import { createAutoRotation, sqlStore, resendMailer, DAY_MS } from "@profullstack/key-rotation";
|
||||||
import { get, all, run } from "../db.mjs";
|
import { get, all, run } from "../db.mjs";
|
||||||
import { config } from "../config.mjs";
|
import { config } from "../config.mjs";
|
||||||
|
|
@ -34,19 +33,11 @@ export const store = sqlStore({
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* coinpay-onboard 0.3.x has no userAgent option, so name this app on every
|
|
||||||
* CoinPay call through its fetch hook (CoinPay's logs and throttle key on it).
|
|
||||||
*/
|
|
||||||
export function coinpayFetch(url, init = {}) {
|
|
||||||
return fetch(url, { ...init, headers: { ...(init.headers ?? {}), "user-agent": COINPAY_UA } });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A CoinPay client on app.logicsrc.com's business key. */
|
/** A CoinPay client on app.logicsrc.com's business key. */
|
||||||
export function coinpayClient(env = process.env) {
|
export function coinpayClient(env = process.env) {
|
||||||
const token = env.COINPAY_API_KEY;
|
const token = env.COINPAY_API_KEY;
|
||||||
if (!token) throw new Error("COINPAY_API_KEY is not configured");
|
if (!token) throw new Error("COINPAY_API_KEY is not configured");
|
||||||
return new CoinPay({ token, base: env.COINPAY_API_URL || undefined, fetch: coinpayFetch });
|
return new CoinPay({ token, base: env.COINPAY_API_URL || undefined });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The module bound to this app; `origin` only changes the links (tests). */
|
/** The module bound to this app; `origin` only changes the links (tests). */
|
||||||
|
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
import { readFileSync } from "node:fs";
|
|
||||||
|
|
||||||
// Sent on every server-side call to CoinPay so its logs and throttle can tell
|
|
||||||
// app.logicsrc.com apart from the other apps on the same box.
|
|
||||||
let version = "";
|
|
||||||
try {
|
|
||||||
version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version || "";
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
export const COINPAY_UA = `app.logicsrc.com${version ? `/${version}` : ""} (+https://app.logicsrc.com)`;
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
// robots.txt and sitemap.xml for the credentials app.
|
|
||||||
//
|
|
||||||
// Almost everything here sits behind a session, so the sitemap lists only the
|
|
||||||
// pages an anonymous visitor (or a crawler) can open: the sign-in page and the
|
|
||||||
// sign-up form. The origin comes from the request, so whichever hostname the app
|
|
||||||
// answers on describes itself rather than another one.
|
|
||||||
|
|
||||||
import { requestOrigin } from "./origin.mjs";
|
|
||||||
|
|
||||||
// Public pages, by path. Everything else redirects to sign-in.
|
|
||||||
export const PUBLIC_PATHS = ["/", "/?mode=up"];
|
|
||||||
|
|
||||||
// Session-only areas a crawler has no reason to visit.
|
|
||||||
const DISALLOW = ["/api/", "/auth/", "/cli/", "/dashboard", "/keyring", "/settings", "/teams/", "/k/"];
|
|
||||||
|
|
||||||
/** https origin for this request (http only for localhost development). */
|
|
||||||
export function siteOrigin(req, fallback) {
|
|
||||||
const origin = requestOrigin(req, fallback);
|
|
||||||
return /^http:\/\/(localhost|127\.0\.0\.1)(:|$)/.test(origin) ? origin : origin.replace(/^http:/, "https:");
|
|
||||||
}
|
|
||||||
|
|
||||||
const xmlEscape = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
||||||
|
|
||||||
export function sitemapXml(origin) {
|
|
||||||
const urls = PUBLIC_PATHS.map((p) => ` <url><loc>${xmlEscape(origin + p)}</loc></url>`).join("\n");
|
|
||||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function robotsTxt(origin) {
|
|
||||||
return ["User-agent: *", "Allow: /", ...DISALLOW.map((p) => `Disallow: ${p}`), "", `Sitemap: ${origin}/sitemap.xml`, ""].join("\n");
|
|
||||||
}
|
|
||||||
|
|
@ -1,455 +0,0 @@
|
||||||
// Vault email recovery (opt-in, $5 lifetime per user) for the personal vault.
|
|
||||||
//
|
|
||||||
// The CLI (packages/opencreds/src/email-recovery.ts) encrypts the vault's user
|
|
||||||
// key K under a random key E and splits E = S XOR U. This module keeps:
|
|
||||||
//
|
|
||||||
// escrow_blob / escrow_iv AES-GCM(K) under E: useless without E
|
|
||||||
// server_share_ct / _iv S, AES-GCM under VAULT_ESCROW_KEY (versioned)
|
|
||||||
//
|
|
||||||
// and never U. U arrives once, at enrollment, is rendered as a recovery code
|
|
||||||
// into an email to the account, and is dropped. A stolen database plus this
|
|
||||||
// server's env yields K only with the enrollment email as well. A live server
|
|
||||||
// compromise during enrollment or recovery, or the mailbox plus a live server,
|
|
||||||
// can: docs/opencreds/security.md says so plainly.
|
|
||||||
//
|
|
||||||
// Recovering releases S only against a fresh 8-digit code mailed at that time
|
|
||||||
// (15 minutes, 5 tries, single use, 3 per hour), and every claim is audited and
|
|
||||||
// announced by email.
|
|
||||||
import crypto from "node:crypto";
|
|
||||||
import { readWebhook } from "@profullstack/coinpay-onboard";
|
|
||||||
import { get, all, run, batch } from "../db.mjs";
|
|
||||||
import { config } from "../config.mjs";
|
|
||||||
import { id } from "./crypto.mjs";
|
|
||||||
import { coinpayClient, PROPERTY } from "./auto-rotation.mjs";
|
|
||||||
|
|
||||||
export const PURPOSE = "vault_recovery";
|
|
||||||
export const CODE_TTL_MS = 15 * 60 * 1000;
|
|
||||||
export const CODE_MAX_ATTEMPTS = 5;
|
|
||||||
export const STARTS_PER_HOUR = 3;
|
|
||||||
export const HOUR_MS = 60 * 60 * 1000;
|
|
||||||
export const SHARE_BYTES = 32;
|
|
||||||
export const IV_BYTES = 12;
|
|
||||||
/** AES-GCM of a 32-byte key: 32 bytes of ciphertext + a 16-byte tag. */
|
|
||||||
export const ESCROW_BLOB_BYTES = 48;
|
|
||||||
|
|
||||||
/** $5 unless VAULT_RECOVERY_PRICE_USD says otherwise. Read per call, so it follows the env. */
|
|
||||||
export const priceUsd = (env = process.env) => {
|
|
||||||
const n = Number(env.VAULT_RECOVERY_PRICE_USD || 5);
|
|
||||||
return Number.isFinite(n) && n > 0 ? n : 5;
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- keys ----
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The server escrow keyring. VAULT_ESCROW_KEY is the current key (32 bytes,
|
|
||||||
* base64) at version VAULT_ESCROW_KEY_VERSION (default 1). To rotate: move the
|
|
||||||
* old key to VAULT_ESCROW_KEY_V<old version>, set the new key and bump the
|
|
||||||
* version; old rows keep decrypting, new enrollments use the new key.
|
|
||||||
*/
|
|
||||||
export function escrowKeyring(env = process.env) {
|
|
||||||
const version = Number.parseInt(env.VAULT_ESCROW_KEY_VERSION || "1", 10) || 1;
|
|
||||||
const keys = new Map();
|
|
||||||
const parse = (value, name) => {
|
|
||||||
const key = Buffer.from(String(value).trim(), "base64");
|
|
||||||
if (key.length !== 32) throw new Error(`${name} must be 32 random bytes, base64-encoded (got ${key.length} bytes)`);
|
|
||||||
return key;
|
|
||||||
};
|
|
||||||
for (const [name, value] of Object.entries(env)) {
|
|
||||||
const m = /^VAULT_ESCROW_KEY_V(\d+)$/.exec(name);
|
|
||||||
if (m && value) keys.set(Number(m[1]), parse(value, name));
|
|
||||||
}
|
|
||||||
if (env.VAULT_ESCROW_KEY) keys.set(version, parse(env.VAULT_ESCROW_KEY, "VAULT_ESCROW_KEY"));
|
|
||||||
return { version, current: keys.get(version) || null, get: (v) => keys.get(Number(v)) || null };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const recoveryConfigured = (env = process.env) => {
|
|
||||||
try {
|
|
||||||
return Boolean(escrowKeyring(env).current);
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const shareAad = (userId) => Buffer.from(`logicsrc:vault-escrow:server-share:v1:${userId}`);
|
|
||||||
|
|
||||||
/** Encrypt S under the current escrow key, bound to the user. */
|
|
||||||
export function sealServerShare(share, userId, ring = escrowKeyring()) {
|
|
||||||
if (!ring.current) throw new Error("VAULT_ESCROW_KEY is not configured");
|
|
||||||
const iv = crypto.randomBytes(IV_BYTES);
|
|
||||||
const cipher = crypto.createCipheriv("aes-256-gcm", ring.current, iv);
|
|
||||||
cipher.setAAD(shareAad(userId));
|
|
||||||
const ct = Buffer.concat([cipher.update(share), cipher.final(), cipher.getAuthTag()]);
|
|
||||||
return { ct: ct.toString("base64"), iv: iv.toString("base64"), version: ring.version };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function openServerShare(row, ring = escrowKeyring()) {
|
|
||||||
const key = ring.get(row.key_version);
|
|
||||||
if (!key) throw new Error(`No escrow key for version ${row.key_version} (set VAULT_ESCROW_KEY_V${row.key_version})`);
|
|
||||||
const data = Buffer.from(row.server_share_ct, "base64");
|
|
||||||
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(row.server_share_iv, "base64"));
|
|
||||||
decipher.setAAD(shareAad(row.user_id));
|
|
||||||
decipher.setAuthTag(data.subarray(data.length - 16));
|
|
||||||
return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------- recovery code ---
|
|
||||||
// Mirrors formatRecoveryCode in packages/opencreds/src/email-recovery.ts (a
|
|
||||||
// test pins that the two agree): 55 Crockford base32 characters of U (256 bits
|
|
||||||
// plus 19 zero bits) and a 5-character check group, in twelve groups of five.
|
|
||||||
|
|
||||||
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
||||||
export const RECOVERY_CODE_CHECK_PREFIX = "opencreds:email-recovery-code:v1";
|
|
||||||
|
|
||||||
function encodeBits(bytes, chars) {
|
|
||||||
let out = "";
|
|
||||||
for (let i = 0; i < chars; i++) {
|
|
||||||
let v = 0;
|
|
||||||
for (let b = 0; b < 5; b++) {
|
|
||||||
const bit = i * 5 + b;
|
|
||||||
const byte = bit >> 3;
|
|
||||||
v = (v << 1) | (byte < bytes.length ? (bytes[byte] >> (7 - (bit & 7))) & 1 : 0);
|
|
||||||
}
|
|
||||||
out += ALPHABET[v];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function renderRecoveryCode(userShare) {
|
|
||||||
if (userShare.length !== SHARE_BYTES) throw new Error("The user share must be 32 bytes");
|
|
||||||
const check = crypto.createHash("sha256").update(RECOVERY_CODE_CHECK_PREFIX).update(userShare).digest();
|
|
||||||
const text = encodeBits(userShare, 55) + encodeBits(check, 5);
|
|
||||||
return text.match(/.{1,5}/g).join("-");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- misc ----
|
|
||||||
|
|
||||||
/** a***@example.com: enough to recognise, not enough to harvest. */
|
|
||||||
export function maskEmail(email) {
|
|
||||||
const [local, domain] = String(email || "").split("@");
|
|
||||||
if (!local || !domain) return null;
|
|
||||||
return `${local[0]}***@${domain}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const affected = (r) => Number(r?.rowsAffected ?? r?.changes ?? r?.rowCount ?? 0);
|
|
||||||
|
|
||||||
/** Plain-text mail through Resend; false when it is not configured or did not send. */
|
|
||||||
export async function sendMail(to, subject, text) {
|
|
||||||
if (!config.resend.apiKey || !to) return false;
|
|
||||||
const response = await fetch("https://api.resend.com/emails", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { authorization: `Bearer ${config.resend.apiKey}`, "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ from: config.resend.from, to, subject, text }),
|
|
||||||
}).catch(() => null);
|
|
||||||
return Boolean(response && response.ok);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function audit(userId, action, { ip = null, userAgent = null, detail = null } = {}, now = Date.now()) {
|
|
||||||
await run(
|
|
||||||
`INSERT INTO vault_recovery_audit (id, user_id, action, detail, ip, user_agent, created_at) VALUES (?,?,?,?,?,?,?)`,
|
|
||||||
[id(), userId, action, detail, ip, userAgent, now],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- payments ---
|
|
||||||
|
|
||||||
export async function isEntitled(userId) {
|
|
||||||
return Boolean(await get(`SELECT 1 AS ok FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled' LIMIT 1`, [userId]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Open a CoinPay checkout for email recovery and record it as pending. */
|
|
||||||
export async function createRecoveryCheckout({ user, client, origin = config.origin, now = Date.now() }) {
|
|
||||||
if (!user?.id || !user?.email) throw new Error("A signed-in user with an email is required");
|
|
||||||
const paymentRef = id();
|
|
||||||
const back = `${origin}/settings`;
|
|
||||||
const session = await (client || coinpayClient()).createCheckoutSession({
|
|
||||||
amount: priceUsd(),
|
|
||||||
currency: "USD",
|
|
||||||
description: "LogicSRC vault email recovery (lifetime)",
|
|
||||||
customerEmail: user.email,
|
|
||||||
accountId: user.id,
|
|
||||||
property: PROPERTY,
|
|
||||||
metadata: { purpose: PURPOSE, user_id: user.id, payment_ref: paymentRef },
|
|
||||||
successUrl: `${back}?vault_recovery=paid&session_id={CHECKOUT_SESSION_ID}#vault-recovery`,
|
|
||||||
cancelUrl: `${back}?vault_recovery=cancelled#vault-recovery`,
|
|
||||||
expiresInMinutes: 60,
|
|
||||||
});
|
|
||||||
await run(
|
|
||||||
`INSERT INTO vault_recovery_payments (checkout_session_id, payment_ref, user_id, status, created_at) VALUES (?,?,?,?,?) ON CONFLICT (checkout_session_id) DO NOTHING`,
|
|
||||||
[session.id, paymentRef, user.id, "pending", now],
|
|
||||||
);
|
|
||||||
return session;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mark a checkout paid. Idempotent on the checkout session (or payment) id: the
|
|
||||||
* first settle wins, a replayed webhook or the return check changes nothing.
|
|
||||||
*/
|
|
||||||
export async function settleVaultRecovery({ checkoutSessionId, paymentId, userId, amountUsd = null, method = null }, now = Date.now()) {
|
|
||||||
const key = checkoutSessionId || paymentId;
|
|
||||||
if (!key) return { handled: false, reason: "no checkout session or payment id" };
|
|
||||||
const existing = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [key]);
|
|
||||||
if (existing) {
|
|
||||||
const r = await run(
|
|
||||||
`UPDATE vault_recovery_payments SET status = 'settled', settled_at = ?, payment_id = COALESCE(payment_id, ?), amount_usd = ?, method = ? WHERE checkout_session_id = ? AND status <> 'settled'`,
|
|
||||||
[now, paymentId || null, amountUsd, method, key],
|
|
||||||
);
|
|
||||||
if (!affected(r)) return { handled: true, purpose: PURPOSE, duplicate: true, userId: existing.user_id };
|
|
||||||
// The row we wrote at checkout names the buyer; metadata is only a fallback.
|
|
||||||
await audit(existing.user_id, "purchase", { detail: key }, now).catch(() => {});
|
|
||||||
return { handled: true, purpose: PURPOSE, action: "settled", userId: existing.user_id };
|
|
||||||
}
|
|
||||||
if (!userId) return { handled: false, reason: "no user_id" };
|
|
||||||
if (!(await get(`SELECT id FROM users WHERE id = ?`, [userId]))) return { handled: false, reason: "unknown user" };
|
|
||||||
const r = await run(
|
|
||||||
`INSERT INTO vault_recovery_payments (checkout_session_id, payment_id, user_id, amount_usd, method, status, created_at, settled_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT (checkout_session_id) DO NOTHING`,
|
|
||||||
[key, paymentId || null, userId, amountUsd, method, "settled", now, now],
|
|
||||||
);
|
|
||||||
if (!affected(r)) return { handled: true, purpose: PURPOSE, duplicate: true, userId };
|
|
||||||
await audit(userId, "purchase", { detail: key }, now).catch(() => {});
|
|
||||||
return { handled: true, purpose: PURPOSE, action: "settled", userId };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Is this (verified) webhook for email recovery? The dispatcher routes on it. */
|
|
||||||
export function isVaultRecoveryEvent(payload) {
|
|
||||||
try {
|
|
||||||
return readWebhook(payload).metadata?.purpose === PURPOSE;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Settle from a verified webhook payload. */
|
|
||||||
export async function settleVaultRecoveryWebhook(payload, now = Date.now()) {
|
|
||||||
const event = readWebhook(payload);
|
|
||||||
if (!event.paid) return { handled: false, purpose: PURPOSE, type: event.type, status: event.status };
|
|
||||||
if (event.property && event.property !== PROPERTY) return { handled: false, purpose: PURPOSE, reason: "other property" };
|
|
||||||
const meta = event.metadata || {};
|
|
||||||
return settleVaultRecovery({
|
|
||||||
checkoutSessionId: event.checkoutSessionId,
|
|
||||||
paymentId: event.paymentId,
|
|
||||||
userId: meta.user_id || event.accountId,
|
|
||||||
amountUsd: event.amountUsd,
|
|
||||||
method: event.method,
|
|
||||||
}, now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Settings page's return check: settle now if CoinPay already says paid. */
|
|
||||||
export async function reconcileRecoveryReturn(sessionId, user, client, now = Date.now()) {
|
|
||||||
if (!sessionId || !/^cs_[A-Za-z0-9_-]+$/.test(sessionId)) return null;
|
|
||||||
const session = await (client || coinpayClient()).checkoutSession(sessionId);
|
|
||||||
const meta = session.metadata || {};
|
|
||||||
if (meta.purpose !== PURPOSE || meta.user_id !== user.id) return null;
|
|
||||||
if (session.status === "paid") {
|
|
||||||
await settleVaultRecovery({
|
|
||||||
checkoutSessionId: session.id,
|
|
||||||
paymentId: session.paymentId || null,
|
|
||||||
userId: user.id,
|
|
||||||
amountUsd: session.amount,
|
|
||||||
method: session.paidMethod || null,
|
|
||||||
}, now);
|
|
||||||
}
|
|
||||||
return session.status;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----------------------------------------------------------- enrollment ---
|
|
||||||
|
|
||||||
export const activeEnrollment = (userId) =>
|
|
||||||
get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active' ORDER BY enrolled_at DESC LIMIT 1`, [userId]);
|
|
||||||
|
|
||||||
export async function recoveryStatus(user) {
|
|
||||||
const [row, purchased] = await Promise.all([activeEnrollment(user.id), isEntitled(user.id)]);
|
|
||||||
return {
|
|
||||||
enrolled: Boolean(row),
|
|
||||||
enrolledAt: row ? new Date(Number(row.enrolled_at)).toISOString() : null,
|
|
||||||
email: maskEmail(user.email),
|
|
||||||
purchased,
|
|
||||||
priceUsd: priceUsd(),
|
|
||||||
configured: recoveryConfigured(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const b64 = (value, bytes) => {
|
|
||||||
if (typeof value !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null;
|
|
||||||
const buf = Buffer.from(value, "base64");
|
|
||||||
return buf.length === bytes ? buf : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Validate an enroll body; returns the parsed shares or an error string. */
|
|
||||||
export function parseEnrollment(body) {
|
|
||||||
const blob = b64(body?.escrowBlob, ESCROW_BLOB_BYTES);
|
|
||||||
const iv = b64(body?.escrowIv, IV_BYTES);
|
|
||||||
const serverShare = b64(body?.serverShare, SHARE_BYTES);
|
|
||||||
const userShare = b64(body?.userShare, SHARE_BYTES);
|
|
||||||
const createdAt = typeof body?.vaultCreatedAt === "string" && body.vaultCreatedAt.length > 0 && body.vaultCreatedAt.length <= 64 ? body.vaultCreatedAt : null;
|
|
||||||
if (!blob || !iv || !serverShare || !userShare || !createdAt) {
|
|
||||||
return { error: "Expected { escrowBlob, escrowIv, serverShare, userShare, vaultCreatedAt } (base64; 48, 12, 32 and 32 bytes)." };
|
|
||||||
}
|
|
||||||
return { escrowBlob: body.escrowBlob, escrowIv: body.escrowIv, serverShare, userShare, vaultCreatedAt: createdAt };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function enrollmentEmail(code) {
|
|
||||||
return {
|
|
||||||
subject: "Your LogicSRC vault email-recovery code — keep this email",
|
|
||||||
text:
|
|
||||||
"You turned on email recovery for your LogicSRC personal vault.\n\n" +
|
|
||||||
"Your recovery code:\n\n" +
|
|
||||||
` ${code}\n\n` +
|
|
||||||
"Keep this email. If you ever lose your master password, run\n\n" +
|
|
||||||
" logicsrc vault recover --email\n\n" +
|
|
||||||
"and type this code when it asks. We will also email you a one-time code at that moment.\n\n" +
|
|
||||||
"LogicSRC does not store this code. It is one half of the key to your vault: the other half is on our " +
|
|
||||||
"server, and neither half opens anything alone. Someone who has this email AND can sign in to your " +
|
|
||||||
"LogicSRC account could recover your vault, so keep this mailbox secure.\n\n" +
|
|
||||||
"Turning email recovery off, or enabling it again, makes this code stop working.\n\n" +
|
|
||||||
"If you did not turn this on, sign in, disable it (Settings, or `logicsrc vault recovery disable`) and change your password.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enroll: store the blob and the sealed S as pending, mail U, then activate
|
|
||||||
* (replacing any prior enrollment). If the mail does not go out, the pending
|
|
||||||
* row is deleted and the prior enrollment, if any, is untouched.
|
|
||||||
*/
|
|
||||||
export async function enroll(user, parsed, ctx = {}, now = Date.now()) {
|
|
||||||
const sealed = sealServerShare(parsed.serverShare, user.id);
|
|
||||||
parsed.serverShare.fill(0);
|
|
||||||
const rowId = id();
|
|
||||||
await run(
|
|
||||||
`INSERT INTO vault_recovery_enrollments (id, user_id, status, escrow_blob, escrow_iv, server_share_ct, server_share_iv, key_version, vault_created_at, enrolled_at) VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
|
||||||
[rowId, user.id, "pending", parsed.escrowBlob, parsed.escrowIv, sealed.ct, sealed.iv, sealed.version, parsed.vaultCreatedAt, now],
|
|
||||||
);
|
|
||||||
let sent = false;
|
|
||||||
try {
|
|
||||||
const mail = enrollmentEmail(renderRecoveryCode(parsed.userShare));
|
|
||||||
sent = await sendMail(user.email, mail.subject, mail.text);
|
|
||||||
} finally {
|
|
||||||
parsed.userShare.fill(0);
|
|
||||||
}
|
|
||||||
if (!sent) {
|
|
||||||
await run(`DELETE FROM vault_recovery_enrollments WHERE id = ?`, [rowId]);
|
|
||||||
await audit(user.id, "enroll_failed", { ...ctx, detail: "email not sent" }, now).catch(() => {});
|
|
||||||
return { ok: false };
|
|
||||||
}
|
|
||||||
await batch([
|
|
||||||
{
|
|
||||||
sql: `UPDATE vault_recovery_enrollments SET status = 'revoked', revoked_at = ?, escrow_blob = NULL, escrow_iv = NULL, server_share_ct = NULL, server_share_iv = NULL WHERE user_id = ? AND status = 'active'`,
|
|
||||||
args: [now, user.id],
|
|
||||||
},
|
|
||||||
{ sql: `UPDATE vault_recovery_enrollments SET status = 'active' WHERE id = ?`, args: [rowId] },
|
|
||||||
{ sql: `UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, args: [now, user.id] },
|
|
||||||
]);
|
|
||||||
await audit(user.id, "enroll", ctx, now);
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Turn it off: the escrow material is deleted, live codes die. */
|
|
||||||
export async function disable(userId, ctx = {}, now = Date.now()) {
|
|
||||||
const r = await run(
|
|
||||||
`UPDATE vault_recovery_enrollments SET status = 'revoked', revoked_at = ?, escrow_blob = NULL, escrow_iv = NULL, server_share_ct = NULL, server_share_iv = NULL WHERE user_id = ? AND status IN ('active', 'pending')`,
|
|
||||||
[now, userId],
|
|
||||||
);
|
|
||||||
await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, [now, userId]);
|
|
||||||
const disabled = affected(r) > 0;
|
|
||||||
if (disabled) await audit(userId, "disable", ctx, now);
|
|
||||||
return { disabled };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- recovery ---
|
|
||||||
|
|
||||||
/** HMAC under the escrow key, so a database dump alone cannot brute-force a live 8-digit code. */
|
|
||||||
function codeHash(userId, codeId, code, ring = escrowKeyring()) {
|
|
||||||
return crypto.createHmac("sha256", ring.current).update(`vault-recovery-otp:v1:${userId}:${codeId}:${code}`).digest("hex");
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RecoveryError extends Error {
|
|
||||||
constructor(status, code, message, extra = {}) {
|
|
||||||
super(message);
|
|
||||||
this.status = status;
|
|
||||||
this.code = code;
|
|
||||||
this.extra = extra;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mail a fresh one-time code. */
|
|
||||||
export async function startRecovery(user, ctx = {}, now = Date.now()) {
|
|
||||||
if (!(await activeEnrollment(user.id))) {
|
|
||||||
throw new RecoveryError(404, "not_enrolled", "Email recovery is not enabled for this account.");
|
|
||||||
}
|
|
||||||
if (!user.email) throw new RecoveryError(422, "no_email", "This account has no email address.");
|
|
||||||
const recent = await all(`SELECT created_at FROM vault_recovery_codes WHERE user_id = ? AND created_at > ? ORDER BY created_at`, [user.id, now - HOUR_MS]);
|
|
||||||
if (recent.length >= STARTS_PER_HOUR) {
|
|
||||||
const retryAfter = Math.max(1, Math.ceil((Number(recent[0].created_at) + HOUR_MS - now) / 1000));
|
|
||||||
throw new RecoveryError(429, "rate_limited", `Too many recovery attempts. Try again in ${Math.ceil(retryAfter / 60)} minute(s).`, { retryAfter });
|
|
||||||
}
|
|
||||||
await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, [now, user.id]);
|
|
||||||
const codeId = id();
|
|
||||||
const code = String(crypto.randomInt(0, 100_000_000)).padStart(8, "0");
|
|
||||||
await run(
|
|
||||||
`INSERT INTO vault_recovery_codes (id, user_id, code_hash, attempts, created_at, expires_at) VALUES (?,?,?,?,?,?)`,
|
|
||||||
[codeId, user.id, codeHash(user.id, codeId, code), 0, now, now + CODE_TTL_MS],
|
|
||||||
);
|
|
||||||
const sent = await sendMail(
|
|
||||||
user.email,
|
|
||||||
"Your LogicSRC vault recovery code",
|
|
||||||
`Someone (hopefully you) is recovering your LogicSRC personal vault through email recovery.\n\n` +
|
|
||||||
`One-time code: ${code}\n\nIt expires in 15 minutes and works once.\n\n` +
|
|
||||||
`If this was not you, someone can sign in to your LogicSRC account: change your password now, and turn email recovery off (Settings, or \`logicsrc vault recovery disable\`). ` +
|
|
||||||
`They also need the recovery code from your enrollment email, so if anyone else can read this mailbox, secure your email account first.`,
|
|
||||||
);
|
|
||||||
if (!sent) {
|
|
||||||
await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, codeId]);
|
|
||||||
throw new RecoveryError(502, "email_failed", "Could not send the one-time code email. Try again in a minute.");
|
|
||||||
}
|
|
||||||
await audit(user.id, "start", ctx, now);
|
|
||||||
return { sent: true, email: maskEmail(user.email) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Spend a one-time code; on success release the escrow material with S decrypted. */
|
|
||||||
export async function claimRecovery(user, code, ctx = {}, now = Date.now()) {
|
|
||||||
const entered = String(code ?? "").replace(/\s+/g, "");
|
|
||||||
const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL ORDER BY created_at DESC LIMIT 1`, [user.id]);
|
|
||||||
if (!row || Number(row.expires_at) <= now) {
|
|
||||||
if (row) await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, row.id]);
|
|
||||||
throw new RecoveryError(410, "code_expired", "No live one-time code. Start the recovery again to get a new one.");
|
|
||||||
}
|
|
||||||
if (Number(row.attempts) >= CODE_MAX_ATTEMPTS) {
|
|
||||||
await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, row.id]);
|
|
||||||
throw new RecoveryError(429, "too_many_attempts", "Too many wrong codes. Start the recovery again.");
|
|
||||||
}
|
|
||||||
const expected = Buffer.from(row.code_hash, "hex");
|
|
||||||
const got = Buffer.from(codeHash(user.id, row.id, entered), "hex");
|
|
||||||
if (!/^\d{8}$/.test(entered) || !crypto.timingSafeEqual(expected, got)) {
|
|
||||||
const attempts = Number(row.attempts) + 1;
|
|
||||||
await run(
|
|
||||||
`UPDATE vault_recovery_codes SET attempts = ?, used_at = ? WHERE id = ?`,
|
|
||||||
[attempts, attempts >= CODE_MAX_ATTEMPTS ? now : null, row.id],
|
|
||||||
);
|
|
||||||
await audit(user.id, "claim_failed", { ...ctx, detail: `attempt ${attempts}` }, now).catch(() => {});
|
|
||||||
const attemptsLeft = Math.max(0, CODE_MAX_ATTEMPTS - attempts);
|
|
||||||
throw new RecoveryError(401, "wrong_code", attemptsLeft ? `Wrong one-time code (${attemptsLeft} tries left).` : "Wrong one-time code. Start the recovery again.", { attemptsLeft });
|
|
||||||
}
|
|
||||||
// Single use, even under a race: only the update that flips used_at wins.
|
|
||||||
const spent = await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ? AND used_at IS NULL`, [now, row.id]);
|
|
||||||
if (!affected(spent)) throw new RecoveryError(410, "code_expired", "That one-time code was already used. Start the recovery again.");
|
|
||||||
|
|
||||||
const enrollment = await activeEnrollment(user.id);
|
|
||||||
if (!enrollment) throw new RecoveryError(404, "not_enrolled", "Email recovery is not enabled for this account.");
|
|
||||||
const share = openServerShare(enrollment);
|
|
||||||
const material = {
|
|
||||||
escrowBlob: enrollment.escrow_blob,
|
|
||||||
escrowIv: enrollment.escrow_iv,
|
|
||||||
serverShare: share.toString("base64"),
|
|
||||||
vaultCreatedAt: enrollment.vault_created_at,
|
|
||||||
};
|
|
||||||
share.fill(0);
|
|
||||||
await audit(user.id, "claim", ctx, now);
|
|
||||||
await sendMail(
|
|
||||||
user.email,
|
|
||||||
"Your LogicSRC vault email recovery was used",
|
|
||||||
`Email recovery for your LogicSRC personal vault was just used (${new Date(now).toISOString()}` +
|
|
||||||
`${ctx.ip ? `, from ${ctx.ip}` : ""}${ctx.userAgent ? `, ${ctx.userAgent}` : ""}).\n\n` +
|
|
||||||
`If that was you, there is nothing to do: the CLI sets a new master password and emails you a new recovery code.\n\n` +
|
|
||||||
`If it was not you, change your LogicSRC password now and turn email recovery off (Settings, or \`logicsrc vault recovery disable\`).`,
|
|
||||||
).catch(() => false);
|
|
||||||
return material;
|
|
||||||
}
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
-- Postgres copy of migrations/014_vault_email_recovery.sql (INTEGER -> bigint, REAL -> double precision).
|
|
||||||
-- Vault email recovery (opt-in, $5 lifetime): escrowed blob + server share S (encrypted
|
|
||||||
-- under VAULT_ESCROW_KEY); the user share U is emailed once and never stored (no column for it).
|
|
||||||
-- No inline comments: the pg shim joins lines. Additive only.
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_enrollments (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
escrow_blob TEXT,
|
|
||||||
escrow_iv TEXT,
|
|
||||||
server_share_ct TEXT,
|
|
||||||
server_share_iv TEXT,
|
|
||||||
key_version bigint NOT NULL,
|
|
||||||
vault_created_at TEXT NOT NULL,
|
|
||||||
enrolled_at bigint NOT NULL,
|
|
||||||
revoked_at bigint
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status);
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_codes (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
code_hash TEXT NOT NULL,
|
|
||||||
attempts bigint NOT NULL DEFAULT 0,
|
|
||||||
created_at bigint NOT NULL,
|
|
||||||
expires_at bigint NOT NULL,
|
|
||||||
used_at bigint
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at);
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_payments (
|
|
||||||
checkout_session_id TEXT PRIMARY KEY,
|
|
||||||
payment_ref TEXT,
|
|
||||||
payment_id TEXT,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
amount_usd double precision,
|
|
||||||
method TEXT,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
created_at bigint NOT NULL,
|
|
||||||
settled_at bigint
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status);
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_audit (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
action TEXT NOT NULL,
|
|
||||||
detail TEXT,
|
|
||||||
ip TEXT,
|
|
||||||
user_agent TEXT,
|
|
||||||
created_at bigint NOT NULL
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at);
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
-- Vault email recovery (opt-in, $5 lifetime per user). See docs/opencreds/security.md.
|
|
||||||
--
|
|
||||||
-- The CLI encrypts the personal vault's user key under a random key E and splits
|
|
||||||
-- E into two XOR shares. The server keeps the escrowed blob and share S, with S
|
|
||||||
-- encrypted under VAULT_ESCROW_KEY (key_version says which one, for rotation).
|
|
||||||
-- The other share, U, is emailed to the account once and NEVER stored: there is
|
|
||||||
-- deliberately no column for it. Neither the blob, S, nor this database plus the
|
|
||||||
-- server env opens a vault without the enrollment email.
|
|
||||||
--
|
|
||||||
-- status: pending (enrollment email not yet confirmed sent) -> active -> revoked.
|
|
||||||
-- A revoked row keeps its timestamps for the audit trail; its escrow material is
|
|
||||||
-- set to NULL (deleted). Additive only.
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_enrollments (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
escrow_blob TEXT,
|
|
||||||
escrow_iv TEXT,
|
|
||||||
server_share_ct TEXT,
|
|
||||||
server_share_iv TEXT,
|
|
||||||
key_version INTEGER NOT NULL,
|
|
||||||
vault_created_at TEXT NOT NULL,
|
|
||||||
enrolled_at INTEGER NOT NULL,
|
|
||||||
revoked_at INTEGER
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status);
|
|
||||||
|
|
||||||
-- One-time codes for a recovery: 8 digits, HMAC'd at rest, 15 minutes, 5 tries, single use.
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_codes (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
code_hash TEXT NOT NULL,
|
|
||||||
attempts INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at INTEGER NOT NULL,
|
|
||||||
expires_at INTEGER NOT NULL,
|
|
||||||
used_at INTEGER
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at);
|
|
||||||
|
|
||||||
-- The purchase ledger: one row per CoinPay checkout session; settled once.
|
|
||||||
-- Entitlement = any settled row for the user.
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_payments (
|
|
||||||
checkout_session_id TEXT PRIMARY KEY,
|
|
||||||
payment_ref TEXT,
|
|
||||||
payment_id TEXT,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
amount_usd REAL,
|
|
||||||
method TEXT,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
created_at INTEGER NOT NULL,
|
|
||||||
settled_at INTEGER
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status);
|
|
||||||
|
|
||||||
-- Append-only trail of every enroll, start, claim, failure and disable.
|
|
||||||
CREATE TABLE IF NOT EXISTS vault_recovery_audit (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
action TEXT NOT NULL,
|
|
||||||
detail TEXT,
|
|
||||||
ip TEXT,
|
|
||||||
user_agent TEXT,
|
|
||||||
created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at);
|
|
||||||
|
|
@ -12,7 +12,6 @@ import { get } from "../db.mjs";
|
||||||
import { requireAuth } from "../lib/session.mjs";
|
import { requireAuth } from "../lib/session.mjs";
|
||||||
import { api, requireMember } from "./credshare.mjs";
|
import { api, requireMember } from "./credshare.mjs";
|
||||||
import { autoRotationState, createCheckout, settleWebhook, verifySignature, AUTO_ROTATION_PRICE_USD, AUTO_ROTATION_DAYS } from "../lib/auto-rotation.mjs";
|
import { autoRotationState, createCheckout, settleWebhook, verifySignature, AUTO_ROTATION_PRICE_USD, AUTO_ROTATION_DAYS } from "../lib/auto-rotation.mjs";
|
||||||
import { isVaultRecoveryEvent, settleVaultRecoveryWebhook } from "../lib/vault-recovery.mjs";
|
|
||||||
|
|
||||||
export const autoRotationRouter = Router();
|
export const autoRotationRouter = Router();
|
||||||
|
|
||||||
|
|
@ -50,16 +49,10 @@ autoRotationRouter.post("/api/credshare/teams/:slug/rotation/auto/checkout", api
|
||||||
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS });
|
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS });
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// The one CoinPay webhook for this app: the signature is verified once, then the
|
|
||||||
// event goes to its product by metadata.purpose. "vault_recovery" (email
|
|
||||||
// recovery, lib/vault-recovery.mjs) settles there; everything else goes to the
|
|
||||||
// automatic-rotation settler exactly as before.
|
|
||||||
autoRotationRouter.post("/api/coinpay/webhook", async (req, res) => {
|
autoRotationRouter.post("/api/coinpay/webhook", async (req, res) => {
|
||||||
if (!verifySignature(req.rawBody, req.get("x-coinpay-signature"))) return res.status(401).json({ error: "Invalid signature" });
|
if (!verifySignature(req.rawBody, req.get("x-coinpay-signature"))) return res.status(401).json({ error: "Invalid signature" });
|
||||||
try {
|
try {
|
||||||
const result = isVaultRecoveryEvent(req.body)
|
const result = await settleWebhook(req.body);
|
||||||
? await settleVaultRecoveryWebhook(req.body)
|
|
||||||
: await settleWebhook(req.body);
|
|
||||||
console.log("coinpay webhook", JSON.stringify(result));
|
console.log("coinpay webhook", JSON.stringify(result));
|
||||||
res.json({ received: true, ...result });
|
res.json({ received: true, ...result });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import { config } from "../config.mjs";
|
import { config } from "../config.mjs";
|
||||||
import { COINPAY_UA } from "../lib/coinpay-ua.mjs";
|
|
||||||
import { token } from "../lib/crypto.mjs";
|
import { token } from "../lib/crypto.mjs";
|
||||||
import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.mjs";
|
import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.mjs";
|
||||||
import { userByCoinpay, createUserForCoinpay } from "../lib/users.mjs";
|
import { userByCoinpay, createUserForCoinpay } from "../lib/users.mjs";
|
||||||
|
|
@ -40,7 +39,7 @@ coinpayRouter.get("/auth/coinpay/callback", async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const tokenRes = await fetch(config.coinpay.oauth.tokenUrl, {
|
const tokenRes = await fetch(config.coinpay.oauth.tokenUrl, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": COINPAY_UA },
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: String(req.query.code),
|
code: String(req.query.code),
|
||||||
|
|
@ -53,7 +52,7 @@ coinpayRouter.get("/auth/coinpay/callback", async (req, res) => {
|
||||||
const tok = await tokenRes.json();
|
const tok = await tokenRes.json();
|
||||||
|
|
||||||
const infoRes = await fetch(config.coinpay.oauth.userinfoUrl, {
|
const infoRes = await fetch(config.coinpay.oauth.userinfoUrl, {
|
||||||
headers: { authorization: `Bearer ${tok.access_token}`, "user-agent": COINPAY_UA },
|
headers: { authorization: `Bearer ${tok.access_token}` },
|
||||||
});
|
});
|
||||||
if (!infoRes.ok) throw new Error(`userinfo ${infoRes.status}`);
|
if (!infoRes.ok) throw new Error(`userinfo ${infoRes.status}`);
|
||||||
const info = await infoRes.json();
|
const info = await infoRes.json();
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,6 @@ import { CLI_HINT } from "../lib/cli-hint.mjs";
|
||||||
import { bulkUnlockCard, vaultPageBody } from "../lib/vault-page.mjs";
|
import { bulkUnlockCard, vaultPageBody } from "../lib/vault-page.mjs";
|
||||||
import { keyFingerprint } from "../lib/keyfp.mjs";
|
import { keyFingerprint } from "../lib/keyfp.mjs";
|
||||||
import { teamAudit } from "./credshare.mjs";
|
import { teamAudit } from "./credshare.mjs";
|
||||||
import { vaultRecoveryCard } from "./vault-recovery.mjs";
|
|
||||||
import { config } from "../config.mjs";
|
import { config } from "../config.mjs";
|
||||||
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
|
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
|
||||||
import { profiles } from "../lib/profile.mjs";
|
import { profiles } from "../lib/profile.mjs";
|
||||||
|
|
@ -314,7 +313,6 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
||||||
if (recoveryToken) clearCeremony(res, "recovery");
|
if (recoveryToken) clearCeremony(res, "recovery");
|
||||||
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
|
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
|
||||||
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
|
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
|
||||||
const recoveryCardHtml = await vaultRecoveryCard(req);
|
|
||||||
const body = `${appBar(req)}
|
const body = `${appBar(req)}
|
||||||
<main class="wrap" style="max-width:720px;padding-top:30px">
|
<main class="wrap" style="max-width:720px;padding-top:30px">
|
||||||
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
|
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
|
||||||
|
|
@ -366,7 +364,6 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
||||||
<button class="btn">Create key</button>
|
<button class="btn">Create key</button>
|
||||||
</form>
|
</form>
|
||||||
</div></div>
|
</div></div>
|
||||||
${recoveryCardHtml}
|
|
||||||
<div class="card" style="margin-top:20px"><div class="card-head"><span class="h">Emergency recovery</span></div>
|
<div class="card" style="margin-top:20px"><div class="card-head"><span class="h">Emergency recovery</span></div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<p class="dim" style="font-size:.85rem;margin-top:0">Create a single-use recovery token for your password manager. The server stores only a hash; if you lose the plaintext, it cannot be recovered. Creating a new token revokes older ones.</p>
|
<p class="dim" style="font-size:.85rem;margin-top:0">Create a single-use recovery token for your password manager. The server stores only a hash; if you lose the plaintext, it cannot be recovered. Creating a new token revokes older ones.</p>
|
||||||
|
|
|
||||||
|
|
@ -1,201 +0,0 @@
|
||||||
// Vault email recovery (opt-in, $5 lifetime): lib/vault-recovery.mjs holds the logic.
|
|
||||||
//
|
|
||||||
// GET /api/opencreds/recovery status: {enrolled, enrolledAt, email (masked), purchased, priceUsd}
|
|
||||||
// POST /api/opencreds/recovery/checkout a CoinPay checkout: {url, sessionId, priceUsd}
|
|
||||||
// POST /api/opencreds/recovery/enroll {escrowBlob, escrowIv, serverShare, userShare, vaultCreatedAt}
|
|
||||||
// POST /api/opencreds/recovery/start mail a one-time code
|
|
||||||
// POST /api/opencreds/recovery/claim {code} -> {escrowBlob, escrowIv, serverShare, vaultCreatedAt}
|
|
||||||
// DELETE /api/opencreds/recovery disable: delete the escrow material
|
|
||||||
// POST /settings/vault-recovery/checkout the Settings page's Buy button (303 to CoinPay)
|
|
||||||
// POST /settings/vault-recovery/disable the Settings page's switch-off
|
|
||||||
//
|
|
||||||
// Auth as /api/opencreds: a browser session or a person's `Bearer lsk_…`; a
|
|
||||||
// machine key never reaches the personal vault. The webhook that settles a
|
|
||||||
// purchase is the shared /api/coinpay/webhook (routes/auto-rotation.mjs), which
|
|
||||||
// dispatches purpose "vault_recovery" here.
|
|
||||||
import { Router } from "express";
|
|
||||||
import { get } from "../db.mjs";
|
|
||||||
import { config } from "../config.mjs";
|
|
||||||
import { bearer, keyForBearer } from "../lib/apikey.mjs";
|
|
||||||
import { esc } from "../lib/html.mjs";
|
|
||||||
import { csrfInput, requireAuth } from "../lib/session.mjs";
|
|
||||||
import {
|
|
||||||
RecoveryError,
|
|
||||||
claimRecovery,
|
|
||||||
createRecoveryCheckout,
|
|
||||||
disable,
|
|
||||||
enroll,
|
|
||||||
isEntitled,
|
|
||||||
maskEmail,
|
|
||||||
parseEnrollment,
|
|
||||||
priceUsd,
|
|
||||||
reconcileRecoveryReturn,
|
|
||||||
recoveryConfigured,
|
|
||||||
recoveryStatus,
|
|
||||||
startRecovery,
|
|
||||||
} from "../lib/vault-recovery.mjs";
|
|
||||||
|
|
||||||
export const vaultRecoveryRouter = Router();
|
|
||||||
|
|
||||||
const userRow = (userId) => get(`SELECT id, email FROM users WHERE id = ?`, [userId]);
|
|
||||||
|
|
||||||
function context(req) {
|
|
||||||
return {
|
|
||||||
ip: (req.ip || "").replace(/^::ffff:/, "") || null,
|
|
||||||
userAgent: String(req.get("user-agent") || "").slice(0, 300) || null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function api(handler) {
|
|
||||||
return async (req, res) => {
|
|
||||||
let userId = req.user?.id;
|
|
||||||
if (!userId) {
|
|
||||||
const found = await keyForBearer(bearer(req));
|
|
||||||
if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
|
|
||||||
if (found.key.kind === "machine") {
|
|
||||||
return res.status(403).json({ error: "A machine API key cannot reach the personal vault.", code: "machine_key_forbidden" });
|
|
||||||
}
|
|
||||||
userId = found.user.id;
|
|
||||||
}
|
|
||||||
res.set("Cache-Control", "no-store");
|
|
||||||
try {
|
|
||||||
const user = await userRow(userId);
|
|
||||||
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
|
|
||||||
await handler(req, res, user);
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof RecoveryError) {
|
|
||||||
if (e.extra?.retryAfter) res.set("Retry-After", String(e.extra.retryAfter));
|
|
||||||
return res.status(e.status).json({ error: e.message, code: e.code, ...e.extra });
|
|
||||||
}
|
|
||||||
// Never the body: it can carry key shares.
|
|
||||||
console.error("vault-recovery:", e?.message || e);
|
|
||||||
res.status(500).json({ error: "Email recovery failed on the server." });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const notConfigured = (res) =>
|
|
||||||
res.status(503).json({ error: "Email recovery is not configured on this server.", code: "not_configured" });
|
|
||||||
|
|
||||||
/** A checkout link to put in a 402, when CoinPay is reachable; else the Settings page. */
|
|
||||||
async function checkoutHint(user) {
|
|
||||||
try {
|
|
||||||
return (await createRecoveryCheckout({ user })).url;
|
|
||||||
} catch {
|
|
||||||
return `${config.origin}/settings#vault-recovery`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
vaultRecoveryRouter.get("/api/opencreds/recovery", api(async (_req, res, user) => {
|
|
||||||
res.json(await recoveryStatus(user));
|
|
||||||
}));
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/api/opencreds/recovery/checkout", api(async (req, res, user) => {
|
|
||||||
if (!user.email) return res.status(422).json({ error: "Add an email to your account first: recovery codes are sent there." });
|
|
||||||
if (await isEntitled(user.id)) return res.status(409).json({ error: "Email recovery is already purchased.", code: "already_purchased" });
|
|
||||||
try {
|
|
||||||
const session = await createRecoveryCheckout({ user });
|
|
||||||
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: priceUsd() });
|
|
||||||
} catch (e) {
|
|
||||||
console.error("vault-recovery checkout failed:", e.message);
|
|
||||||
res.status(502).json({ error: "Could not open the CoinPay checkout. Try again in a minute." });
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/api/opencreds/recovery/enroll", api(async (req, res, user) => {
|
|
||||||
if (!recoveryConfigured()) return notConfigured(res);
|
|
||||||
if (!user.email) return res.status(422).json({ error: "This account has no email address to send the recovery code to." });
|
|
||||||
if (!(await isEntitled(user.id))) {
|
|
||||||
return res.status(402).json({
|
|
||||||
error: `Email recovery is a $${priceUsd()} lifetime add-on and is not purchased yet.`,
|
|
||||||
code: "payment_required",
|
|
||||||
priceUsd: priceUsd(),
|
|
||||||
checkoutUrl: await checkoutHint(user),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const parsed = parseEnrollment(req.body);
|
|
||||||
// Drop the request's copy of U as soon as it is parsed (a string cannot be zeroed; this is what is possible).
|
|
||||||
if (req.body && typeof req.body === "object") delete req.body.userShare;
|
|
||||||
if (parsed.error) return res.status(422).json({ error: parsed.error });
|
|
||||||
const result = await enroll(user, parsed, context(req));
|
|
||||||
if (!result.ok) {
|
|
||||||
return res.status(502).json({ error: "Could not send the enrollment email, so nothing was enrolled. Try again.", code: "email_failed" });
|
|
||||||
}
|
|
||||||
res.status(201).json({ enrolled: true, email: maskEmail(user.email) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/api/opencreds/recovery/start", api(async (req, res, user) => {
|
|
||||||
if (!recoveryConfigured()) return notConfigured(res);
|
|
||||||
res.json(await startRecovery(user, context(req)));
|
|
||||||
}));
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/api/opencreds/recovery/claim", api(async (req, res, user) => {
|
|
||||||
if (!recoveryConfigured()) return notConfigured(res);
|
|
||||||
res.json(await claimRecovery(user, req.body?.code, context(req)));
|
|
||||||
}));
|
|
||||||
|
|
||||||
vaultRecoveryRouter.delete("/api/opencreds/recovery", api(async (req, res, user) => {
|
|
||||||
res.json(await disable(user.id, context(req)));
|
|
||||||
}));
|
|
||||||
|
|
||||||
// ---- the Settings page ----
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/settings/vault-recovery/checkout", requireAuth, async (req, res) => {
|
|
||||||
const back = "/settings";
|
|
||||||
const user = await userRow(req.user.id);
|
|
||||||
if (!user?.email) return res.redirect(`${back}?err=${encodeURIComponent("Add an email to your account first: recovery codes are sent there.")}`);
|
|
||||||
if (await isEntitled(user.id)) return res.redirect(`${back}#vault-recovery`);
|
|
||||||
try {
|
|
||||||
const session = await createRecoveryCheckout({ user });
|
|
||||||
res.redirect(303, session.url);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("vault-recovery checkout failed:", e.message);
|
|
||||||
res.redirect(`${back}?err=${encodeURIComponent("Could not open the CoinPay checkout. Try again in a minute.")}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
vaultRecoveryRouter.post("/settings/vault-recovery/disable", requireAuth, async (req, res) => {
|
|
||||||
await disable(req.user.id, context(req));
|
|
||||||
res.redirect("/settings?vault_recovery=disabled#vault-recovery");
|
|
||||||
});
|
|
||||||
|
|
||||||
/** The Settings card. Never throws: a database without the tables shows the card as unavailable. */
|
|
||||||
export async function vaultRecoveryCard(req) {
|
|
||||||
let status;
|
|
||||||
try {
|
|
||||||
if (req.query.vault_recovery === "paid" && req.query.session_id) {
|
|
||||||
await reconcileRecoveryReturn(String(req.query.session_id), req.user).catch(() => null);
|
|
||||||
}
|
|
||||||
status = await recoveryStatus(req.user);
|
|
||||||
} catch {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
const notice =
|
|
||||||
req.query.vault_recovery === "paid"
|
|
||||||
? status.purchased
|
|
||||||
? `<div class="notice ok">Payment received. Turn email recovery on from the CLI: <code>logicsrc vault recovery enable</code>.</div>`
|
|
||||||
: `<div class="notice ok">Thanks. CoinPay is confirming the payment; this page shows it as purchased once it lands.</div>`
|
|
||||||
: req.query.vault_recovery === "cancelled"
|
|
||||||
? `<div class="notice err">Checkout cancelled. Nothing was charged.</div>`
|
|
||||||
: req.query.vault_recovery === "disabled"
|
|
||||||
? `<div class="notice ok">Email recovery is off. The server deleted its share; the emailed code is useless now.</div>`
|
|
||||||
: "";
|
|
||||||
const pill = (on, yes, no) => `<span class="pill ${on ? "on" : ""}">${on ? yes : no}</span>`;
|
|
||||||
const action = !status.purchased
|
|
||||||
? `<form method="post" action="/settings/vault-recovery/checkout" style="margin-top:12px">${csrfInput(req)}<button class="btn acid">Buy email recovery ($${esc(String(status.priceUsd))}, lifetime)</button></form>`
|
|
||||||
: status.enrolled
|
|
||||||
? `<form method="post" action="/settings/vault-recovery/disable" style="margin-top:12px">${csrfInput(req)}<button class="btn danger">Turn email recovery off</button></form>`
|
|
||||||
: `<p class="dim" style="font-size:.85rem">Turn it on from the CLI (it needs your unlocked vault): <code>logicsrc vault recovery enable</code></p>`;
|
|
||||||
return `
|
|
||||||
<div class="card" id="vault-recovery" style="margin-top:20px"><div class="card-head"><span class="h">Vault email recovery — $${esc(String(status.priceUsd))} lifetime</span></div>
|
|
||||||
<div class="card-body">
|
|
||||||
${notice}
|
|
||||||
<p class="dim" style="font-size:.85rem;margin-top:0">A second way into your personal vault if you lose the master password and the offline recovery key. We email you a recovery code once; on the day you need it, <code>logicsrc vault recover --email</code> asks for that code plus a fresh one-time code. We keep an encrypted half of the key and never the code, so our database alone cannot open your vault. Someone with your mailbox <b>and</b> a compromised LogicSRC server could, which is why it is opt-in. Without it, your vault stays zero-knowledge.</p>
|
|
||||||
<div class="mono" style="font-size:.8rem;display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
|
||||||
${pill(status.purchased, "purchased", "not purchased")}
|
|
||||||
${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")}
|
|
||||||
${status.email ? `<span class="faint">codes go to ${esc(status.email)}</span>` : ""}
|
|
||||||
</div>
|
|
||||||
${status.configured ? action : `<p class="faint mono" style="font-size:.78rem">Not available on this server yet.</p>`}
|
|
||||||
</div></div>`;
|
|
||||||
}
|
|
||||||
|
|
@ -16,7 +16,6 @@ import { autoRotationRouter } from "./routes/auto-rotation.mjs";
|
||||||
import { sweepAutoRotation } from "./lib/auto-rotation.mjs";
|
import { sweepAutoRotation } from "./lib/auto-rotation.mjs";
|
||||||
import { apiKeysRouter } from "./routes/apikeys.mjs";
|
import { apiKeysRouter } from "./routes/apikeys.mjs";
|
||||||
import { opencredsRouter } from "./routes/opencreds.mjs";
|
import { opencredsRouter } from "./routes/opencreds.mjs";
|
||||||
import { vaultRecoveryRouter } from "./routes/vault-recovery.mjs";
|
|
||||||
import { keyringRouter } from "./routes/keyring.mjs";
|
import { keyringRouter } from "./routes/keyring.mjs";
|
||||||
import { keyringShareRouter, publicKeysRouter } from "./routes/keyring-share.mjs";
|
import { keyringShareRouter, publicKeysRouter } from "./routes/keyring-share.mjs";
|
||||||
import { cliRouter } from "./routes/cli.mjs";
|
import { cliRouter } from "./routes/cli.mjs";
|
||||||
|
|
@ -25,7 +24,6 @@ import { profileRouter } from "./lib/profile.mjs";
|
||||||
import { descriptor } from "@profullstack/footer";
|
import { descriptor } from "@profullstack/footer";
|
||||||
import { RING_FOOTER_OPTIONS } from "./lib/ring-footer.mjs";
|
import { RING_FOOTER_OPTIONS } from "./lib/ring-footer.mjs";
|
||||||
import { securityHeaders } from "./lib/security-headers.mjs";
|
import { securityHeaders } from "./lib/security-headers.mjs";
|
||||||
import { robotsTxt, siteOrigin, sitemapXml } from "./lib/seo.mjs";
|
|
||||||
import { PROFILE_ENHANCE_SCRIPT } from "@profullstack/profile";
|
import { PROFILE_ENHANCE_SCRIPT } from "@profullstack/profile";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
@ -75,11 +73,7 @@ app.get("/vendor/profile-enhance.js", (_req, res) => res.type("application/javas
|
||||||
app.get("/.well-known/openwebring.json", (_req, res) =>
|
app.get("/.well-known/openwebring.json", (_req, res) =>
|
||||||
res.json(descriptor({ site: RING_FOOTER_OPTIONS.site, name: "LogicSRC credentials" })));
|
res.json(descriptor({ site: RING_FOOTER_OPTIONS.site, name: "LogicSRC credentials" })));
|
||||||
|
|
||||||
// Crawlers: only the public sign-in and sign-up pages, on whichever host was asked.
|
app.get("/healthz", (_req, res) => res.json({ ok: true, env: config.env }));
|
||||||
app.get("/robots.txt", (req, res) => res.type("text/plain").set("Cache-Control", "public, max-age=3600").send(robotsTxt(siteOrigin(req, config.origin))));
|
|
||||||
app.get("/sitemap.xml", (req, res) => res.type("application/xml").set("Cache-Control", "public, max-age=3600").send(sitemapXml(siteOrigin(req, config.origin))));
|
|
||||||
|
|
||||||
app.get("/healthz",(_req, res) => res.json({ ok: true, env: config.env }));
|
|
||||||
|
|
||||||
// The keyring share link (/k/<token>.json|.keys): public, CORS-open, no session
|
// The keyring share link (/k/<token>.json|.keys): public, CORS-open, no session
|
||||||
// (mounted before the session middleware so it never sets a cookie on a cacheable answer).
|
// (mounted before the session middleware so it never sets a cookie on a cacheable answer).
|
||||||
|
|
@ -98,7 +92,6 @@ app.use(autoRotationRouter); // paid automatic rotation: CoinPay checkout + /api
|
||||||
app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values)
|
app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values)
|
||||||
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
|
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
|
||||||
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
|
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
|
||||||
app.use(vaultRecoveryRouter); // /api/opencreds/recovery/* + /settings/vault-recovery/* — opt-in paid email recovery
|
|
||||||
app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key)
|
app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key)
|
||||||
app.use(keyringRouter); // /api/keyring/* + /keyring — SSH keys / key pairs, ciphertext only
|
app.use(keyringRouter); // /api/keyring/* + /keyring — SSH keys / key pairs, ciphertext only
|
||||||
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
|
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
|
||||||
|
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
|
|
||||||
import { robotsTxt, siteOrigin, sitemapXml } from "../src/lib/seo.mjs";
|
|
||||||
|
|
||||||
const req = (host, protocol = "http") => ({ protocol, headers: { host }, get: (h) => (h.toLowerCase() === "host" ? host : undefined) });
|
|
||||||
|
|
||||||
test("each hostname describes itself over https", () => {
|
|
||||||
assert.equal(siteOrigin(req("app.logicsrc.com"), "https://x"), "https://app.logicsrc.com");
|
|
||||||
assert.equal(siteOrigin(req("localhost:8080"), "https://x"), "http://localhost:8080");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("sitemap lists only public pages on this host", () => {
|
|
||||||
const xml = sitemapXml("https://app.logicsrc.com");
|
|
||||||
assert.match(xml, /<urlset /);
|
|
||||||
assert.match(xml, /<loc>https:\/\/app\.logicsrc\.com\/<\/loc>/);
|
|
||||||
assert.match(xml, /<loc>https:\/\/app\.logicsrc\.com\/\?mode=up<\/loc>/);
|
|
||||||
assert.doesNotMatch(xml, /dashboard|settings|keyring/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("robots points at this host's sitemap and keeps it crawlable", () => {
|
|
||||||
const txt = robotsTxt("https://app.logicsrc.com");
|
|
||||||
assert.match(txt, /^Sitemap: https:\/\/app\.logicsrc\.com\/sitemap\.xml$/m);
|
|
||||||
assert.doesNotMatch(txt, /Disallow: \/sitemap/);
|
|
||||||
assert.match(txt, /Disallow: \/dashboard/);
|
|
||||||
});
|
|
||||||
|
|
@ -1,362 +0,0 @@
|
||||||
// Vault email recovery (lib/vault-recovery.mjs, routes/vault-recovery.mjs): a
|
|
||||||
// paid, opt-in escrow. What these pin: enrolling needs the purchase (402 with a
|
|
||||||
// checkout link otherwise); the user share U goes out in the email and is never
|
|
||||||
// written anywhere; a failed email leaves nothing enrolled; one-time codes have
|
|
||||||
// a TTL, an attempt cap, single use and a start rate limit; a claim returns S
|
|
||||||
// decrypted and, with U, reopens the vault key; disable deletes the material;
|
|
||||||
// the shared CoinPay webhook settles vault_recovery once and still settles
|
|
||||||
// auto_rotation; a machine key never gets in.
|
|
||||||
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
|
|
||||||
process.env.COINPAY_WEBHOOK_SECRET = "whsec_test";
|
|
||||||
process.env.COINPAY_API_KEY = "cp_test";
|
|
||||||
process.env.COINPAY_API_URL = "https://coinpay.test";
|
|
||||||
process.env.RESEND_API_KEY = "re_test";
|
|
||||||
process.env.VAULT_ESCROW_KEY = (await import("node:crypto")).randomBytes(32).toString("base64");
|
|
||||||
delete process.env.VAULT_ESCROW_KEY_VERSION;
|
|
||||||
|
|
||||||
import test from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { readFileSync } from "node:fs";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import { dirname, join } from "node:path";
|
|
||||||
import express from "express";
|
|
||||||
import { signWebhook } from "@profullstack/coinpay-onboard";
|
|
||||||
import {
|
|
||||||
createVault,
|
|
||||||
formatRecoveryCode,
|
|
||||||
fromBase64,
|
|
||||||
parseRecoveryCode,
|
|
||||||
prepareEnrollment,
|
|
||||||
recoverUserKeyByEmail,
|
|
||||||
} from "@logicsrc/opencreds";
|
|
||||||
|
|
||||||
const here = dirname(fileURLToPath(import.meta.url));
|
|
||||||
const { db, run, get, all, isPostgres } = await import("../src/db.mjs");
|
|
||||||
const { vaultRecoveryRouter } = await import("../src/routes/vault-recovery.mjs");
|
|
||||||
const { autoRotationRouter } = await import("../src/routes/auto-rotation.mjs");
|
|
||||||
const { createApiKey } = await import("../src/lib/apikey.mjs");
|
|
||||||
const vr = await import("../src/lib/vault-recovery.mjs");
|
|
||||||
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
if (isPostgres) {
|
|
||||||
await db.execute("DROP SCHEMA public CASCADE");
|
|
||||||
await db.execute("CREATE SCHEMA public");
|
|
||||||
}
|
|
||||||
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql", "011_rotation_policy.sql", "012_auto_rotation_billing.sql", "014_vault_email_recovery.sql"]) {
|
|
||||||
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
|
|
||||||
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- outbound mail and CoinPay, intercepted; everything else (our own server) passes through ----
|
|
||||||
const realFetch = globalThis.fetch;
|
|
||||||
const mail = [];
|
|
||||||
let mailFails = false;
|
|
||||||
let sessionSeq = 0;
|
|
||||||
const sessions = new Map();
|
|
||||||
globalThis.fetch = async (url, init = {}) => {
|
|
||||||
const u = String(url);
|
|
||||||
if (u.startsWith("https://api.resend.com/")) {
|
|
||||||
const body = JSON.parse(init.body);
|
|
||||||
if (mailFails) return new Response(JSON.stringify({ message: "down" }), { status: 500 });
|
|
||||||
mail.push(body);
|
|
||||||
return new Response(JSON.stringify({ id: `em_${mail.length}` }), { status: 200 });
|
|
||||||
}
|
|
||||||
if (u.startsWith("https://coinpay.test/api/checkout/sessions")) {
|
|
||||||
if ((init.method || "GET") === "POST") {
|
|
||||||
const input = JSON.parse(init.body);
|
|
||||||
const id = `cs_vr${++sessionSeq}`;
|
|
||||||
const session = { id, url: `https://coinpay.test/pay/${id}`, status: "open", amount: input.amount, currency: "USD", metadata: input.metadata, account_id: input.account_id };
|
|
||||||
sessions.set(id, session);
|
|
||||||
return new Response(JSON.stringify({ session }), { status: 201 });
|
|
||||||
}
|
|
||||||
const id = decodeURIComponent(u.split("/").pop());
|
|
||||||
return new Response(JSON.stringify({ session: sessions.get(id) }), { status: 200 });
|
|
||||||
}
|
|
||||||
return realFetch(url, init);
|
|
||||||
};
|
|
||||||
test.after(() => { globalThis.fetch = realFetch; });
|
|
||||||
|
|
||||||
// ---- people, keys and a team (for the auto-rotation dispatch check) ----
|
|
||||||
const users = ["u_a", "u_b", "u_c", "u_d", "u_e", "u_owner"];
|
|
||||||
for (const uid of users) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@example.com`, now]);
|
|
||||||
const keys = {};
|
|
||||||
for (const uid of users) keys[uid] = (await createApiKey(uid, "cli")).plaintext;
|
|
||||||
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t_acme", "acme", "acme", "u_owner", now]);
|
|
||||||
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t_acme", "u_owner", "u_owner@example.com", "owner", "active", now]);
|
|
||||||
const machine = (await createApiKey("u_a", "dev2-deploy", { kind: "machine", teamId: "t_acme", vaultScope: null, readOnly: true })).plaintext;
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf.toString("utf8"); } }));
|
|
||||||
app.use(vaultRecoveryRouter);
|
|
||||||
app.use(autoRotationRouter);
|
|
||||||
const server = app.listen(0);
|
|
||||||
await new Promise((r) => server.once("listening", r));
|
|
||||||
const base = `http://127.0.0.1:${server.address().port}`;
|
|
||||||
test.after(() => new Promise((r) => server.close(r)));
|
|
||||||
|
|
||||||
async function call(token, method, path, body, headers = {}) {
|
|
||||||
const raw = body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body);
|
|
||||||
const res = await realFetch(base + path, {
|
|
||||||
method,
|
|
||||||
headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(raw ? { "content-type": "application/json" } : {}), ...headers },
|
|
||||||
body: raw,
|
|
||||||
});
|
|
||||||
const text = await res.text();
|
|
||||||
return { status: res.status, body: text ? JSON.parse(text) : null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// One real vault for everything below (PBKDF2 at the floor, to keep this quick).
|
|
||||||
const vault = await createVault("old master password", { params: { kdf: "pbkdf2-sha256", iterations: 100_000 } });
|
|
||||||
|
|
||||||
async function enrollPayload() {
|
|
||||||
const prepared = await prepareEnrollment(vault.meta, vault.userKey);
|
|
||||||
return { ...prepared.payload };
|
|
||||||
}
|
|
||||||
const grant = (uid, cs = `cs_grant_${uid}`) =>
|
|
||||||
run(`INSERT INTO vault_recovery_payments (checkout_session_id, user_id, status, created_at, settled_at) VALUES (?,?,?,?,?)`, [cs, uid, "settled", now, now]);
|
|
||||||
const lastMailTo = (to) => [...mail].reverse().find((m) => m.to === to);
|
|
||||||
const codeIn = (text) => /\b([0-9A-Z]{5}(?:-[0-9A-Z]{5}){11})\b/.exec(text)?.[1];
|
|
||||||
const otpIn = (text) => /One-time code: (\d{8})/.exec(text)?.[1];
|
|
||||||
|
|
||||||
async function enrolled(uid) {
|
|
||||||
await grant(uid);
|
|
||||||
const payload = await enrollPayload();
|
|
||||||
const r = await call(keys[uid], "POST", "/api/opencreds/recovery/enroll", payload);
|
|
||||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
test("no key: 401; a machine key is refused everywhere", async () => {
|
|
||||||
assert.equal((await call(null, "GET", "/api/opencreds/recovery")).status, 401);
|
|
||||||
for (const [method, path] of [["GET", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/enroll"], ["POST", "/api/opencreds/recovery/start"], ["POST", "/api/opencreds/recovery/claim"], ["DELETE", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/checkout"]]) {
|
|
||||||
const r = await call(machine, method, path, method === "POST" ? {} : undefined);
|
|
||||||
assert.equal(r.status, 403, `${method} ${path}`);
|
|
||||||
assert.equal(r.body.code, "machine_key_forbidden");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("enroll without the purchase: 402 with a checkout link, and nothing stored", async () => {
|
|
||||||
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload());
|
|
||||||
assert.equal(r.status, 402);
|
|
||||||
assert.equal(r.body.code, "payment_required");
|
|
||||||
assert.equal(r.body.priceUsd, 5);
|
|
||||||
assert.match(r.body.checkoutUrl, /^https:\/\/coinpay\.test\/pay\/cs_vr\d+$/);
|
|
||||||
assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0);
|
|
||||||
const status = await call(keys.u_a, "GET", "/api/opencreds/recovery");
|
|
||||||
assert.deepEqual({ ...status.body, enrolledAt: null }, { enrolled: false, enrolledAt: null, email: "u***@example.com", purchased: false, priceUsd: 5, configured: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("webhook: settles vault_recovery once (replay is a no-op) and still settles auto_rotation", async () => {
|
|
||||||
const checkout = await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout");
|
|
||||||
assert.equal(checkout.status, 201);
|
|
||||||
const cs = checkout.body.sessionId;
|
|
||||||
const created = sessions.get(cs);
|
|
||||||
assert.equal(created.metadata.purpose, "vault_recovery");
|
|
||||||
assert.equal(created.metadata.user_id, "u_a");
|
|
||||||
assert.ok(created.metadata.payment_ref);
|
|
||||||
assert.equal((await get(`SELECT status FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs])).status, "pending");
|
|
||||||
|
|
||||||
const event = (id, data) => JSON.stringify({ id, type: "payment.confirmed", data: { payment_id: `pay_${id}`, status: "confirmed", amount_usd: 5, blockchain: "USDC_POL", property: "app.logicsrc.com", ...data } });
|
|
||||||
const vrEvent = event("vr1", { checkout_session_id: cs, metadata: { purpose: "vault_recovery", user_id: "u_a", payment_ref: created.metadata.payment_ref } });
|
|
||||||
assert.equal((await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": "t=1,v1=bad" })).status, 401);
|
|
||||||
const first = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") });
|
|
||||||
assert.equal(first.status, 200);
|
|
||||||
assert.equal(first.body.purpose, "vault_recovery");
|
|
||||||
assert.equal(first.body.action, "settled");
|
|
||||||
const replay = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") });
|
|
||||||
assert.equal(replay.body.duplicate, true);
|
|
||||||
const row = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs]);
|
|
||||||
assert.equal(row.status, "settled");
|
|
||||||
assert.equal((await all(`SELECT * FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled'`, ["u_a"])).length, 1);
|
|
||||||
assert.equal((await call(keys.u_a, "GET", "/api/opencreds/recovery")).body.purchased, true);
|
|
||||||
assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout")).status, 409);
|
|
||||||
|
|
||||||
// The same endpoint, an auto-rotation purchase: routed to the old settler, unchanged.
|
|
||||||
const arEvent = event("ar1", { checkout_session_id: "cs_ar1", metadata: { purpose: "auto_rotation", team_id: "t_acme", user_id: "u_owner" } });
|
|
||||||
const ar = await call(null, "POST", "/api/coinpay/webhook", arEvent, { "x-coinpay-signature": signWebhook(arEvent, "whsec_test") });
|
|
||||||
assert.equal(ar.body.action, "activated");
|
|
||||||
assert.equal(Number((await get(`SELECT rotation_auto_approve FROM credshare_teams WHERE id = ?`, ["t_acme"])).rotation_auto_approve), 1);
|
|
||||||
assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_payments WHERE checkout_session_id = ?`, ["cs_ar1"])).n), 0);
|
|
||||||
|
|
||||||
// An unpaid vault_recovery event settles nothing.
|
|
||||||
const pending = JSON.stringify({ id: "vr2", type: "payment.pending", data: { status: "pending", metadata: { purpose: "vault_recovery", user_id: "u_b" } } });
|
|
||||||
assert.equal((await call(null, "POST", "/api/coinpay/webhook", pending, { "x-coinpay-signature": signWebhook(pending, "whsec_test") })).body.handled, false);
|
|
||||||
assert.equal(await vr.isEntitled("u_b"), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("enroll rolls back when the email does not send (a prior enrollment survives)", async () => {
|
|
||||||
mailFails = true;
|
|
||||||
try {
|
|
||||||
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload());
|
|
||||||
assert.equal(r.status, 502);
|
|
||||||
assert.equal(r.body.code, "email_failed");
|
|
||||||
} finally {
|
|
||||||
mailFails = false;
|
|
||||||
}
|
|
||||||
assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0);
|
|
||||||
|
|
||||||
await enrolled("u_c");
|
|
||||||
const before = await get(`SELECT id FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_c"]);
|
|
||||||
mailFails = true;
|
|
||||||
try {
|
|
||||||
assert.equal((await call(keys.u_c, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 502);
|
|
||||||
} finally {
|
|
||||||
mailFails = false;
|
|
||||||
}
|
|
||||||
const rows = await all(`SELECT id, status FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_c"]);
|
|
||||||
assert.deepEqual(rows.map((r) => [r.id, r.status]), [[before.id, "active"]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("enroll emails U as a checksummed code and never stores it; a re-enroll replaces the old one", async () => {
|
|
||||||
const payload = await enrollPayload();
|
|
||||||
const sent = mail.length;
|
|
||||||
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", payload);
|
|
||||||
assert.equal(r.status, 201);
|
|
||||||
assert.deepEqual(r.body, { enrolled: true, email: "u***@example.com" });
|
|
||||||
assert.ok(!JSON.stringify(r.body).includes(payload.userShare));
|
|
||||||
|
|
||||||
assert.equal(mail.length, sent + 1);
|
|
||||||
const email = mail.at(-1);
|
|
||||||
assert.equal(email.to, "u_a@example.com");
|
|
||||||
assert.equal(email.subject, "Your LogicSRC vault email-recovery code — keep this email");
|
|
||||||
const code = codeIn(email.text);
|
|
||||||
assert.ok(code, "a recovery code in the email");
|
|
||||||
const U = fromBase64(payload.userShare);
|
|
||||||
// The server's renderer and the CLI's agree, and the CLI parses it back to U.
|
|
||||||
assert.equal(code, await formatRecoveryCode(U));
|
|
||||||
assert.deepEqual(await parseRecoveryCode(code), U);
|
|
||||||
|
|
||||||
// U is nowhere at rest: no column for it, and no value in any table holds it in any encoding.
|
|
||||||
const tables = ["vault_recovery_enrollments", "vault_recovery_codes", "vault_recovery_payments", "vault_recovery_audit", "users", "api_keys"];
|
|
||||||
const needles = [payload.userShare, Buffer.from(U).toString("hex"), Buffer.from(U).toString("base64url"), code, code.replace(/-/g, "")];
|
|
||||||
for (const table of tables) {
|
|
||||||
for (const row of await all(`SELECT * FROM ${table}`)) {
|
|
||||||
for (const [column, value] of Object.entries(row)) {
|
|
||||||
assert.ok(!/user_?share/i.test(column), `${table}.${column}`);
|
|
||||||
if (typeof value !== "string") continue;
|
|
||||||
for (const needle of needles) assert.ok(!value.includes(needle), `U found in ${table}.${column}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// S is stored only encrypted.
|
|
||||||
const active = await get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_a"]);
|
|
||||||
assert.notEqual(active.server_share_ct, payload.serverShare);
|
|
||||||
assert.equal(Number(active.key_version), 1);
|
|
||||||
assert.equal(active.escrow_blob, payload.escrowBlob);
|
|
||||||
|
|
||||||
// Re-enroll: a single active row, the old one revoked with its material deleted.
|
|
||||||
const again = await enrollPayload();
|
|
||||||
assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", again)).status, 201);
|
|
||||||
const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? ORDER BY enrolled_at, status`, ["u_a"]);
|
|
||||||
assert.equal(rows.filter((x) => x.status === "active").length, 1);
|
|
||||||
const old = rows.find((x) => x.id === active.id);
|
|
||||||
assert.equal(old.status, "revoked");
|
|
||||||
assert.equal(old.escrow_blob, null);
|
|
||||||
assert.equal(old.server_share_ct, null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("start + claim: emails a code, wrong code counts, the right one returns S decrypted and reopens K, once", async () => {
|
|
||||||
const payload = await enrolled("u_d");
|
|
||||||
const U = await parseRecoveryCode(codeIn(lastMailTo("u_d@example.com").text));
|
|
||||||
|
|
||||||
const start = await call(keys.u_d, "POST", "/api/opencreds/recovery/start");
|
|
||||||
assert.deepEqual(start.body, { sent: true, email: "u***@example.com" });
|
|
||||||
const otp = otpIn(lastMailTo("u_d@example.com").text);
|
|
||||||
assert.match(otp, /^\d{8}$/);
|
|
||||||
const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL`, ["u_d"]);
|
|
||||||
assert.ok(!row.code_hash.includes(otp));
|
|
||||||
assert.equal(Number(row.expires_at) - Number(row.created_at), 15 * 60 * 1000);
|
|
||||||
|
|
||||||
const wrong = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp === "00000000" ? "11111111" : "00000000" });
|
|
||||||
assert.equal(wrong.status, 401);
|
|
||||||
assert.equal(wrong.body.attemptsLeft, 4);
|
|
||||||
|
|
||||||
const notices = mail.length;
|
|
||||||
const claim = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp });
|
|
||||||
assert.equal(claim.status, 200);
|
|
||||||
assert.deepEqual(claim.body, { escrowBlob: payload.escrowBlob, escrowIv: payload.escrowIv, serverShare: payload.serverShare, vaultCreatedAt: vault.meta.createdAt });
|
|
||||||
assert.equal(mail.at(-1).subject, "Your LogicSRC vault email recovery was used");
|
|
||||||
assert.equal(mail.length, notices + 1);
|
|
||||||
assert.ok((await all(`SELECT action FROM vault_recovery_audit WHERE user_id = ?`, ["u_d"])).some((a) => a.action === "claim"));
|
|
||||||
|
|
||||||
// S from the server + U from the enrollment email = the vault's own key.
|
|
||||||
const K = await recoverUserKeyByEmail({ meta: vault.meta, material: claim.body, userShare: U });
|
|
||||||
assert.deepEqual(K, vault.userKey);
|
|
||||||
|
|
||||||
// Single use.
|
|
||||||
assert.equal((await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("codes expire after 15 minutes and die after 5 wrong tries", async () => {
|
|
||||||
await enrolled("u_e");
|
|
||||||
await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
||||||
const expired = otpIn(lastMailTo("u_e@example.com").text);
|
|
||||||
await run(`UPDATE vault_recovery_codes SET expires_at = ? WHERE user_id = ? AND used_at IS NULL`, [Date.now() - 1, "u_e"]);
|
|
||||||
const late = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: expired });
|
|
||||||
assert.equal(late.status, 410);
|
|
||||||
assert.equal(late.body.code, "code_expired");
|
|
||||||
|
|
||||||
await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
||||||
const otp = otpIn(lastMailTo("u_e@example.com").text);
|
|
||||||
const bad = otp === "99999999" ? "88888888" : "99999999";
|
|
||||||
let r;
|
|
||||||
for (let i = 0; i < 5; i++) r = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: bad });
|
|
||||||
assert.equal(r.status, 401);
|
|
||||||
assert.equal(r.body.attemptsLeft, 0);
|
|
||||||
const after = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: otp });
|
|
||||||
assert.equal(after.status, 410, "the right code is dead after five wrong ones");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("start is rate limited to 3 per hour per user", async () => {
|
|
||||||
// u_e has used 2 starts above; one more is allowed, the next is not.
|
|
||||||
assert.equal((await call(keys.u_e, "POST", "/api/opencreds/recovery/start")).status, 200);
|
|
||||||
const limited = await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
||||||
assert.equal(limited.status, 429);
|
|
||||||
assert.equal(limited.body.code, "rate_limited");
|
|
||||||
assert.ok(limited.body.retryAfter > 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("start/claim need an active enrollment; disable deletes the material and kills live codes", async () => {
|
|
||||||
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404);
|
|
||||||
|
|
||||||
await enrolled("u_b");
|
|
||||||
await call(keys.u_b, "POST", "/api/opencreds/recovery/start");
|
|
||||||
const otp = otpIn(lastMailTo("u_b@example.com").text);
|
|
||||||
const off = await call(keys.u_b, "DELETE", "/api/opencreds/recovery");
|
|
||||||
assert.deepEqual(off.body, { disabled: true });
|
|
||||||
const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_b"]);
|
|
||||||
assert.ok(rows.every((x) => x.status === "revoked" && x.escrow_blob === null && x.escrow_iv === null && x.server_share_ct === null && x.server_share_iv === null));
|
|
||||||
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410);
|
|
||||||
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404);
|
|
||||||
const status = (await call(keys.u_b, "GET", "/api/opencreds/recovery")).body;
|
|
||||||
assert.equal(status.enrolled, false);
|
|
||||||
assert.equal(status.purchased, true, "disabling does not burn the purchase");
|
|
||||||
assert.deepEqual((await call(keys.u_b, "DELETE", "/api/opencreds/recovery")).body, { disabled: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("escrow keyring: a rotated key still opens rows sealed under the old version", () => {
|
|
||||||
const share = Buffer.alloc(32, 7);
|
|
||||||
const v1 = vr.escrowKeyring({ VAULT_ESCROW_KEY: process.env.VAULT_ESCROW_KEY });
|
|
||||||
const sealed = vr.sealServerShare(share, "u_x", v1);
|
|
||||||
const rotated = vr.escrowKeyring({ VAULT_ESCROW_KEY: Buffer.alloc(32, 1).toString("base64"), VAULT_ESCROW_KEY_VERSION: "2", VAULT_ESCROW_KEY_V1: process.env.VAULT_ESCROW_KEY });
|
|
||||||
assert.equal(rotated.version, 2);
|
|
||||||
const row = { user_id: "u_x", server_share_ct: sealed.ct, server_share_iv: sealed.iv, key_version: sealed.version };
|
|
||||||
assert.deepEqual(vr.openServerShare(row, rotated), share);
|
|
||||||
// Bound to the user: the same ciphertext under another user id does not open.
|
|
||||||
assert.throws(() => vr.openServerShare({ ...row, user_id: "u_y" }, rotated));
|
|
||||||
assert.throws(() => vr.escrowKeyring({ VAULT_ESCROW_KEY: "dG9vLXNob3J0" }), /32 random bytes/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the Settings card: a Buy button before the purchase, the CLI hint after, a switch-off once enrolled", async () => {
|
|
||||||
const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs");
|
|
||||||
const req = (uid) => ({ query: {}, user: { id: uid, email: `${uid}@example.com` }, csrfToken: "t" });
|
|
||||||
const unpaid = await vaultRecoveryCard(req("u_owner"));
|
|
||||||
assert.match(unpaid, /Vault email recovery — \$5 lifetime/);
|
|
||||||
assert.match(unpaid, /action="\/settings\/vault-recovery\/checkout"/);
|
|
||||||
await grant("u_owner");
|
|
||||||
assert.match(await vaultRecoveryCard(req("u_owner")), /logicsrc vault recovery enable/);
|
|
||||||
const on = await vaultRecoveryCard(req("u_a"));
|
|
||||||
assert.match(on, /action="\/settings\/vault-recovery\/disable"/);
|
|
||||||
assert.match(on, /u\*\*\*@example\.com/);
|
|
||||||
});
|
|
||||||
4
bun.lock
|
|
@ -59,7 +59,7 @@
|
||||||
"@profullstack/autoblog": "^0.5.0",
|
"@profullstack/autoblog": "^0.5.0",
|
||||||
"@profullstack/footer": "latest",
|
"@profullstack/footer": "latest",
|
||||||
"@profullstack/stack": "^0.5.0",
|
"@profullstack/stack": "^0.5.0",
|
||||||
"@profullstack/x402-gateway": "^0.20.0",
|
"@profullstack/x402-gateway": "^0.18.1",
|
||||||
"@supabase/supabase-js": "^2.118.0",
|
"@supabase/supabase-js": "^2.118.0",
|
||||||
"marked": "^18.1.1",
|
"marked": "^18.1.1",
|
||||||
"next": "16.4.3",
|
"next": "16.4.3",
|
||||||
|
|
@ -787,7 +787,7 @@
|
||||||
|
|
||||||
"@profullstack/stack": ["@profullstack/stack@0.5.0", "", { "dependencies": { "@profullstack/emailer": "^1.0.1", "@profullstack/form-guard": "^0.1.1", "@profullstack/referrals": "^0.1.0" }, "peerDependencies": { "@supabase/ssr": ">=0.5.0", "next": ">=13.0.0", "react": ">=18.0.0" }, "optionalPeers": ["@supabase/ssr", "next", "react"] }, "sha512-LbXovIhyzLEq+a+y3q8KWC+jN1tJjvSoUiFEhpiEBisQn5U+iutIGHDgg16Lul74kQaFZeFlbp7CMPAVJ8KL6g=="],
|
"@profullstack/stack": ["@profullstack/stack@0.5.0", "", { "dependencies": { "@profullstack/emailer": "^1.0.1", "@profullstack/form-guard": "^0.1.1", "@profullstack/referrals": "^0.1.0" }, "peerDependencies": { "@supabase/ssr": ">=0.5.0", "next": ">=13.0.0", "react": ">=18.0.0" }, "optionalPeers": ["@supabase/ssr", "next", "react"] }, "sha512-LbXovIhyzLEq+a+y3q8KWC+jN1tJjvSoUiFEhpiEBisQn5U+iutIGHDgg16Lul74kQaFZeFlbp7CMPAVJ8KL6g=="],
|
||||||
|
|
||||||
"@profullstack/x402-gateway": ["@profullstack/x402-gateway@0.20.0", "", { "dependencies": { "@profullstack/keys": "^0.1.0" } }, "sha512-gdOAsrxwBw4REZJHSpFR8HnC5lmuqQJGDPV8SAqZX6CQTi4HY7ztwysGcd9dp70EDYugYcHERC5hIrFtAFi1dA=="],
|
"@profullstack/x402-gateway": ["@profullstack/x402-gateway@0.18.1", "", { "dependencies": { "@profullstack/keys": "^0.1.0" } }, "sha512-zc2JGLXMX8eCk7Mp4X91E175enOTNcWPZncKf3LXzoGE+XEhHDJHM1LRZkkY3x2pjLYX3AB11Vx/TP3cobSQ/g=="],
|
||||||
|
|
||||||
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.15", "", { "os": "android", "cpu": "arm" }, "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw=="],
|
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.15", "", { "os": "android", "cpu": "arm" }, "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw=="],
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -52,24 +52,6 @@ opencreds recover # unlock with the recovery key, set a new password
|
||||||
A password change re-wraps the user key. Not one item is re-encrypted, which is
|
A password change re-wraps the user key. Not one item is re-encrypted, which is
|
||||||
why it is instant on a vault of any size.
|
why it is instant on a vault of any size.
|
||||||
|
|
||||||
### Email recovery (`logicsrc vault` only)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
logicsrc vault recovery status [--json] # enrolled? since? email (masked)? purchased?
|
|
||||||
logicsrc vault recovery buy # CoinPay checkout link ($5, lifetime)
|
|
||||||
logicsrc vault recovery enable # enroll; emails a recovery code to keep
|
|
||||||
logicsrc vault recovery disable # server deletes its escrow share and blob
|
|
||||||
logicsrc vault recover --email # recovery code + fresh one-time code, then a new password
|
|
||||||
```
|
|
||||||
|
|
||||||
An opt-in, paid account feature; the standalone `opencreds` binary has no
|
|
||||||
account and exits 1 with a pointer to `logicsrc login`. `enable` exits 1 and
|
|
||||||
prints the checkout link when the purchase is missing. `recover --email` works
|
|
||||||
with the vault locked, exits 3 when the recovery code does not match, prints the
|
|
||||||
new offline recovery key once, and re-enrolls automatically (it warns loudly,
|
|
||||||
exit 0, if that last step fails). The trade-off is in
|
|
||||||
[security.md](./security.md#email-recovery-opt-in-paid).
|
|
||||||
|
|
||||||
## Items
|
## Items
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
|
||||||
|
|
@ -122,42 +122,6 @@ rotating the key and re-encrypting, because the key they held is a key they may
|
||||||
have kept. Partial sharing is not a feature of a shared key; it is a second
|
have kept. Partial sharing is not a feature of a shared key; it is a second
|
||||||
vault.
|
vault.
|
||||||
|
|
||||||
## Email recovery escrow
|
|
||||||
|
|
||||||
Email recovery (opt-in, paid) is a LogicSRC account feature, not part of the
|
|
||||||
format: a vault that never enrolls is untouched by it. The security trade-off is
|
|
||||||
in [security.md](./security.md#email-recovery-opt-in-paid); the construction is:
|
|
||||||
|
|
||||||
```
|
|
||||||
user key K (32 bytes)
|
|
||||||
│
|
|
||||||
└─ AES-256-GCM(E, K, AAD = "<ns>:vault:email-escrow:v1|<vault createdAt>") → escrow blob
|
|
||||||
|
|
||||||
E (32 random bytes, client-side, never sent whole)
|
|
||||||
├─ S = 32 random bytes → server, AES-256-GCM under VAULT_ESCROW_KEY
|
|
||||||
│ (AAD binds the user id; key_version for rotation)
|
|
||||||
└─ U = E XOR S → emailed once as the recovery code, never stored
|
|
||||||
```
|
|
||||||
|
|
||||||
- **XOR, not a threshold scheme.** Two shares, both required: a 2-of-2 split is
|
|
||||||
XOR, and XOR with a uniformly random S makes U uniformly random too, so each
|
|
||||||
share alone carries no information about E.
|
|
||||||
- **The AAD carries `createdAt`.** It survives password changes and changes on
|
|
||||||
`init`, so an escrow blob cannot be replayed against a different vault.
|
|
||||||
- **The recovery code** is U in Crockford base32 (the alphabet of the offline
|
|
||||||
recovery key): 55 characters for 256 bits plus 19 zero bits, then a 5-character
|
|
||||||
check group, the first 25 bits of
|
|
||||||
`SHA-256("opencreds:email-recovery-code:v1" || U)`. Twelve groups of five. The
|
|
||||||
check group catches a typo before a one-time code is requested or spent;
|
|
||||||
a well-formed but wrong code fails the GCM tag on the escrow blob instead
|
|
||||||
("recovery code doesn't match").
|
|
||||||
- **After recovery** the client re-wraps K under the new password, replaces the
|
|
||||||
offline recovery key, and re-enrolls with a fresh E, S and U. K itself does not
|
|
||||||
change, so not one item is re-encrypted.
|
|
||||||
- **One-time codes** are 8 digits, stored as an HMAC under the server escrow key
|
|
||||||
(a dump of the codes table alone cannot brute-force a live one), 15 minutes,
|
|
||||||
5 attempts, single use.
|
|
||||||
|
|
||||||
## Randomness
|
## Randomness
|
||||||
|
|
||||||
Every IV, salt, user key and recovery key MUST come from a cryptographic RNG
|
Every IV, salt, user key and recovery key MUST come from a cryptographic RNG
|
||||||
|
|
|
||||||
|
|
@ -113,56 +113,6 @@ Consequences worth stating in a product's own docs:
|
||||||
give them access, because it does not have the key. This is a feature, and it
|
give them access, because it does not have the key. This is a feature, and it
|
||||||
means a grant requires an authorized member to be online.
|
means a grant requires an authorized member to be online.
|
||||||
|
|
||||||
## Email recovery (opt-in, paid)
|
|
||||||
|
|
||||||
The LogicSRC account service offers a second way back into a personal (`user`
|
|
||||||
profile) vault: `logicsrc vault recovery enable`, $5 once per account. It is off
|
|
||||||
unless the person turns it on, and it changes the threat model for those who
|
|
||||||
do. A vault that is never enrolled stays exactly as described above: the server
|
|
||||||
holds nothing that can open it.
|
|
||||||
|
|
||||||
**What enrolling stores.** The client draws a random 32-byte escrow key E,
|
|
||||||
encrypts the user key under it, and splits E into two XOR shares, S and U. The
|
|
||||||
server stores the escrowed blob and S, with S encrypted under the server's own
|
|
||||||
escrow key (`VAULT_ESCROW_KEY`). U is rendered as a recovery code, emailed to
|
|
||||||
the account address once ("keep this email"), and dropped: no table has a
|
|
||||||
column for it. Each share alone is uniformly random and says nothing about E.
|
|
||||||
The crypto is in [crypto.md](./crypto.md#email-recovery-escrow).
|
|
||||||
|
|
||||||
**What recovering needs.** `logicsrc vault recover --email` needs the recovery
|
|
||||||
code from the enrollment email (U) and a fresh 8-digit one-time code the server
|
|
||||||
mails at that moment (15 minutes, 5 tries, single use, 3 requests an hour),
|
|
||||||
plus a signed-in LogicSRC CLI. The server releases S only against that code,
|
|
||||||
logs the claim and mails a "your vault email recovery was used" notice. The
|
|
||||||
client recombines E, decrypts the user key, checks it opens an item, sets a new
|
|
||||||
master password, issues a new offline recovery key and re-enrolls with fresh
|
|
||||||
shares, so the code just used is dead.
|
|
||||||
|
|
||||||
What this does and does not hold against, stated plainly:
|
|
||||||
|
|
||||||
- **A stolen database, even with the server's environment (the escrow key):**
|
|
||||||
cannot open an enrolled vault. It yields the blob and S, and E also needs U,
|
|
||||||
which only the enrollment email has.
|
|
||||||
- **The enrollment email alone:** cannot open the vault. It is U without S, and
|
|
||||||
S is released only to a signed-in account that also receives a fresh code.
|
|
||||||
- **A live compromise of the server while a person enrolls or recovers:** can
|
|
||||||
open that vault. Enrollment hands U to the server in transit so it can be
|
|
||||||
mailed, and a claim hands S back out; code running on the server at that
|
|
||||||
moment sees what it needs.
|
|
||||||
- **Whoever controls the person's mailbox can open the vault.** The mailbox
|
|
||||||
holds U and receives the one-time code, and the LogicSRC account password
|
|
||||||
can itself be reset by email, so the mailbox alone is enough to sign in, claim
|
|
||||||
S and recombine E. The only defences are the notice emails (a claim and every
|
|
||||||
account-password reset are mailed, and the owner may see them first) and
|
|
||||||
disabling recovery. This is the reason the feature is opt-in: it moves the
|
|
||||||
vault's safety onto the security of an email account. Enable it only on an
|
|
||||||
email account with its own strong password and second factor.
|
|
||||||
- **The account operator** can see that a person enrolled, when, and when they
|
|
||||||
recovered; never the contents.
|
|
||||||
|
|
||||||
Turning it off (`logicsrc vault recovery disable`, or Settings) deletes the
|
|
||||||
escrowed blob and S on the server, after which the emailed code is useless.
|
|
||||||
|
|
||||||
## Reporting
|
## Reporting
|
||||||
|
|
||||||
Security issues in the specification or the reference implementation:
|
Security issues in the specification or the reference implementation:
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import type { Command } from "commander";
|
import type { Command } from "commander";
|
||||||
import { registerCredsCommands } from "@logicsrc/opencreds/commands";
|
import { registerCredsCommands } from "@logicsrc/opencreds/commands";
|
||||||
import { accountRecoveryFor, accountRemoteFor } from "./vault-sync.js";
|
import { accountRemoteFor } from "./vault-sync.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `logicsrc vault …`
|
* `logicsrc vault …`
|
||||||
|
|
@ -53,14 +53,6 @@ gets it with: logicsrc login, then logicsrc vault sync.
|
||||||
logicsrc vault sync --status what is synced, what is waiting
|
logicsrc vault sync --status what is synced, what is waiting
|
||||||
LOGICSRC_VAULT_SYNC=off turn it off (a --home vault never syncs)
|
LOGICSRC_VAULT_SYNC=off turn it off (a --home vault never syncs)
|
||||||
|
|
||||||
Lost the master password? The offline recovery key from init works:
|
|
||||||
logicsrc vault recover
|
|
||||||
Email recovery (opt-in, $5 lifetime) is a second way back in, through your account email:
|
|
||||||
logicsrc vault recovery buy CoinPay checkout link
|
|
||||||
logicsrc vault recovery enable emails you a recovery code to keep
|
|
||||||
logicsrc vault recover --email that code + a fresh emailed one-time code
|
|
||||||
logicsrc vault recovery status | disable
|
|
||||||
|
|
||||||
Help for any command: logicsrc vault <command> --help (or: logicsrc vault help <command>)
|
Help for any command: logicsrc vault <command> --help (or: logicsrc vault help <command>)
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|
@ -76,5 +68,5 @@ export function registerOpenCredsCommands(program: Command): void {
|
||||||
.addHelpText("after", VAULT_GUIDE);
|
.addHelpText("after", VAULT_GUIDE);
|
||||||
|
|
||||||
// Logged in: the vault syncs to the account around every command.
|
// Logged in: the vault syncs to the account around every command.
|
||||||
registerCredsCommands(vault, { remote: accountRemoteFor, emailRecovery: accountRecoveryFor });
|
registerCredsCommands(vault, { remote: accountRemoteFor });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { createHash, createHmac, generateKeyPairSync, pbkdf2Sync, randomBytes } from "node:crypto";
|
import { createHash, createHmac, generateKeyPairSync, pbkdf2Sync, randomBytes } from "node:crypto";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { generateRandomSecret } from "./rotation-catalog.js";
|
import { generateRandomSecret } from "./rotation-catalog.js";
|
||||||
import { localVersion } from "./update.js";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Built-in rotators for `method: "provider"`. Each one is two-phase:
|
* Built-in rotators for `method: "provider"`. Each one is two-phase:
|
||||||
|
|
@ -62,14 +61,11 @@ export class RotatorError extends Error {}
|
||||||
|
|
||||||
const day = (d: Date) => d.toISOString().slice(0, 10);
|
const day = (d: Date) => d.toISOString().slice(0, 10);
|
||||||
|
|
||||||
/** Names this CLI on every provider call, so CoinPay's logs and throttle can tell it apart from the apps. */
|
|
||||||
export const ROTATOR_USER_AGENT = `logicsrc-cli/${localVersion()} (+https://logicsrc.com)`;
|
|
||||||
|
|
||||||
async function call(ctx: RotatorContext, url: string, init: RequestInit & { token: string }): Promise<{ status: number; body: any }> {
|
async function call(ctx: RotatorContext, url: string, init: RequestInit & { token: string }): Promise<{ status: number; body: any }> {
|
||||||
const { token, headers, ...rest } = init;
|
const { token, headers, ...rest } = init;
|
||||||
const res = await ctx.fetch(url, {
|
const res = await ctx.fetch(url, {
|
||||||
...rest,
|
...rest,
|
||||||
headers: { "user-agent": ROTATOR_USER_AGENT, authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", ...(headers as Record<string, string> | undefined) }
|
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", ...(headers as Record<string, string> | undefined) }
|
||||||
});
|
});
|
||||||
const text = await res.text();
|
const text = await res.text();
|
||||||
let body: any = null;
|
let body: any = null;
|
||||||
|
|
@ -253,7 +249,7 @@ async function coinpayLogin(ctx: RotatorContext): Promise<CoinpaySession> {
|
||||||
try {
|
try {
|
||||||
res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, {
|
res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json", "user-agent": ROTATOR_USER_AGENT },
|
headers: { "content-type": "application/json" },
|
||||||
body: JSON.stringify({ email: ctx.env.COINPAY_ROTATE_EMAIL, password: ctx.env.COINPAY_ROTATE_PASSWORD })
|
body: JSON.stringify({ email: ctx.env.COINPAY_ROTATE_EMAIL, password: ctx.env.COINPAY_ROTATE_PASSWORD })
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import { EmailRecoveryError } from "@logicsrc/opencreds";
|
|
||||||
import { createRecoveryClient } from "./vault-sync.js";
|
|
||||||
|
|
||||||
type Call = { url: string; method: string; auth: string | null; body: unknown };
|
|
||||||
|
|
||||||
function fakeFetch(answers: Record<string, { status: number; body: unknown }>) {
|
|
||||||
const calls: Call[] = [];
|
|
||||||
const impl = (async (url: string, init: RequestInit = {}) => {
|
|
||||||
const method = init.method ?? "GET";
|
|
||||||
calls.push({
|
|
||||||
url,
|
|
||||||
method,
|
|
||||||
auth: new Headers(init.headers).get("authorization"),
|
|
||||||
body: init.body ? JSON.parse(String(init.body)) : undefined,
|
|
||||||
});
|
|
||||||
const answer = answers[`${method} ${new URL(url).pathname}`] ?? { status: 404, body: { error: "nope" } };
|
|
||||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
|
||||||
}) as unknown as typeof fetch;
|
|
||||||
return { impl, calls };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("the email-recovery client", () => {
|
|
||||||
it("talks to /api/opencreds/recovery with the person's key", async () => {
|
|
||||||
const { impl, calls } = fakeFetch({
|
|
||||||
"GET /api/opencreds/recovery": { status: 200, body: { enrolled: true, enrolledAt: "2026-11-30T00:00:00.000Z", email: "m***@x.test", purchased: true, priceUsd: 5 } },
|
|
||||||
"POST /api/opencreds/recovery/claim": { status: 200, body: { escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" } },
|
|
||||||
"DELETE /api/opencreds/recovery": { status: 200, body: { disabled: true } },
|
|
||||||
});
|
|
||||||
const client = createRecoveryClient("https://app.example/", "lsk_test", "me@x.test", impl);
|
|
||||||
expect(client.label).toBe("app.example (me@x.test)");
|
|
||||||
expect((await client.status()).enrolled).toBe(true);
|
|
||||||
expect(await client.claim("12345678")).toEqual({ escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" });
|
|
||||||
expect(await client.disable()).toEqual({ disabled: true });
|
|
||||||
expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([
|
|
||||||
"GET https://app.example/api/opencreds/recovery",
|
|
||||||
"POST https://app.example/api/opencreds/recovery/claim",
|
|
||||||
"DELETE https://app.example/api/opencreds/recovery",
|
|
||||||
]);
|
|
||||||
expect(calls.every((c) => c.auth === "Bearer lsk_test")).toBe(true);
|
|
||||||
expect(calls[1]!.body).toEqual({ code: "12345678" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("surfaces a 402 with the checkout link", async () => {
|
|
||||||
const { impl } = fakeFetch({
|
|
||||||
"POST /api/opencreds/recovery/enroll": {
|
|
||||||
status: 402,
|
|
||||||
body: { error: "Email recovery is a $5 lifetime add-on and is not purchased yet.", code: "payment_required", checkoutUrl: "https://coinpay.test/pay/cs_1" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const client = createRecoveryClient("https://app.example", "lsk_test", undefined, impl);
|
|
||||||
const err = await client
|
|
||||||
.enroll({ escrowBlob: "", escrowIv: "", serverShare: "", userShare: "", vaultCreatedAt: "" })
|
|
||||||
.catch((e: unknown) => e);
|
|
||||||
expect(err).toBeInstanceOf(EmailRecoveryError);
|
|
||||||
expect((err as EmailRecoveryError).status).toBe(402);
|
|
||||||
expect((err as EmailRecoveryError).code).toBe("payment_required");
|
|
||||||
expect((err as EmailRecoveryError).checkoutUrl).toBe("https://coinpay.test/pay/cs_1");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,18 +1,6 @@
|
||||||
import { join, resolve } from "node:path";
|
import { join, resolve } from "node:path";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { EmailRecoveryError } from "@logicsrc/opencreds";
|
import type { Envelope, RemoteItem, RemoteVault, SyncRemote, VaultMeta, VaultStore } from "@logicsrc/opencreds";
|
||||||
import type {
|
|
||||||
EmailRecoveryClient,
|
|
||||||
EmailRecoveryStatus,
|
|
||||||
Envelope,
|
|
||||||
EscrowEnrollment,
|
|
||||||
EscrowMaterial,
|
|
||||||
RemoteItem,
|
|
||||||
RemoteVault,
|
|
||||||
SyncRemote,
|
|
||||||
VaultMeta,
|
|
||||||
VaultStore,
|
|
||||||
} from "@logicsrc/opencreds";
|
|
||||||
import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing";
|
import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -104,80 +92,3 @@ export function createAccountRemote(apiUrl: string, token: string, email?: strin
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Email recovery for the personal vault (`logicsrc vault recovery …`,
|
|
||||||
* `logicsrc vault recover --email`): apps/pwa /api/opencreds/recovery.
|
|
||||||
*
|
|
||||||
* Same scope rule as sync: it protects the account's vault, so a --home vault
|
|
||||||
* gets it only with LOGICSRC_VAULT_SYNC=on. Turning sync off does not turn
|
|
||||||
* recovery off; the two are independent.
|
|
||||||
*/
|
|
||||||
export function accountRecoveryFor(store: VaultStore): EmailRecoveryClient | undefined {
|
|
||||||
const setting = (process.env.LOGICSRC_VAULT_SYNC || "").toLowerCase();
|
|
||||||
if (setting !== "on" && resolve(store.baseDir) !== resolve(defaultVaultDir())) return undefined;
|
|
||||||
const identity = readIdentity();
|
|
||||||
if (!identity?.apiToken) return undefined;
|
|
||||||
return createRecoveryClient(resolveApiUrl(identity), identity.apiToken, identity.email);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createRecoveryClient(
|
|
||||||
apiUrl: string,
|
|
||||||
token: string,
|
|
||||||
email?: string,
|
|
||||||
fetchImpl: typeof fetch = fetch,
|
|
||||||
): EmailRecoveryClient {
|
|
||||||
const base = apiUrl.replace(/\/+$/, "");
|
|
||||||
const host = (() => {
|
|
||||||
try {
|
|
||||||
return new URL(base).host;
|
|
||||||
} catch {
|
|
||||||
return base;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
async function call(method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {
|
|
||||||
const res = await fetchImpl(`${base}/api/opencreds/recovery${path}`, {
|
|
||||||
method,
|
|
||||||
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(body ? { "content-type": "application/json" } : {}) },
|
|
||||||
body: body ? JSON.stringify(body) : undefined,
|
|
||||||
signal: AbortSignal.timeout(30_000),
|
|
||||||
});
|
|
||||||
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new EmailRecoveryError(
|
|
||||||
String(json.error || `${host} answered HTTP ${res.status}`),
|
|
||||||
res.status,
|
|
||||||
typeof json.code === "string" ? json.code : undefined,
|
|
||||||
typeof json.checkoutUrl === "string" ? json.checkoutUrl : undefined,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: email ? `${host} (${email})` : host,
|
|
||||||
async status() {
|
|
||||||
return (await call("GET", "")) as unknown as EmailRecoveryStatus;
|
|
||||||
},
|
|
||||||
async checkout() {
|
|
||||||
const body = await call("POST", "/checkout");
|
|
||||||
return { url: String(body.url), priceUsd: Number(body.priceUsd) };
|
|
||||||
},
|
|
||||||
async enroll(payload: EscrowEnrollment) {
|
|
||||||
const body = await call("POST", "/enroll", payload);
|
|
||||||
return { enrolled: Boolean(body.enrolled), email: String(body.email ?? "") };
|
|
||||||
},
|
|
||||||
async start() {
|
|
||||||
const body = await call("POST", "/start");
|
|
||||||
return { sent: Boolean(body.sent), email: typeof body.email === "string" ? body.email : undefined };
|
|
||||||
},
|
|
||||||
async claim(code: string) {
|
|
||||||
return (await call("POST", "/claim", { code })) as unknown as EscrowMaterial;
|
|
||||||
},
|
|
||||||
async disable() {
|
|
||||||
const body = await call("DELETE", "");
|
|
||||||
return { disabled: Boolean(body.disabled) };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -285,13 +285,3 @@ describe("validate", () => {
|
||||||
expect(result.code).toBe(2);
|
expect(result.code).toBe(2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("email recovery in the standalone binary", () => {
|
|
||||||
it("is an account feature: recover --email and recovery commands exit 1 and point at logicsrc login", async () => {
|
|
||||||
for (const args of [["recover", "--email"], ["recovery", "status"], ["recovery", "enable"]]) {
|
|
||||||
const result = await cli(args);
|
|
||||||
expect(result.code, args.join(" ")).toBe(1);
|
|
||||||
expect(result.stderr).toMatch(/logicsrc login/);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -58,13 +58,6 @@ import { createVault, resetRecoveryKey, rewrapUserKey, unlockVault, unlockWithRe
|
||||||
import { formatDiagnostics, hasErrors, validateDocument } from "./validate.js";
|
import { formatDiagnostics, hasErrors, validateDocument } from "./validate.js";
|
||||||
import { DivergedVaultError, describeSync, pullVault, pushVault, readSyncState, syncVault, type SyncRemote } from "./sync.js";
|
import { DivergedVaultError, describeSync, pullVault, pushVault, readSyncState, syncVault, type SyncRemote } from "./sync.js";
|
||||||
import type { VaultStore } from "./store.js";
|
import type { VaultStore } from "./store.js";
|
||||||
import {
|
|
||||||
enrollEmailRecovery,
|
|
||||||
runEmailRecovery,
|
|
||||||
type EmailRecoveryClient,
|
|
||||||
type EmailRecoveryError,
|
|
||||||
type EmailRecoveryResult,
|
|
||||||
} from "./email-recovery.js";
|
|
||||||
|
|
||||||
/** Exit codes are part of the contract; see docs/opencreds/cli.md. */
|
/** Exit codes are part of the contract; see docs/opencreds/cli.md. */
|
||||||
export const EXIT = {
|
export const EXIT = {
|
||||||
|
|
@ -309,12 +302,6 @@ export interface RegisterOptions {
|
||||||
* `opencreds` binary passes nothing, so it never syncs.
|
* `opencreds` binary passes nothing, so it never syncs.
|
||||||
*/
|
*/
|
||||||
remote?: (store: VaultStore) => SyncRemote | undefined;
|
remote?: (store: VaultStore) => SyncRemote | undefined;
|
||||||
/**
|
|
||||||
* The account's email-recovery endpoints, if any (opt-in, paid). Called per
|
|
||||||
* command; return undefined when there is no logged-in account. Without it,
|
|
||||||
* `recover --email` and `recovery …` explain that they need `logicsrc login`.
|
|
||||||
*/
|
|
||||||
emailRecovery?: (store: VaultStore) => EmailRecoveryClient | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Commands that never touch a vault on disk, plus `sync`, which syncs itself.
|
// Commands that never touch a vault on disk, plus `sync`, which syncs itself.
|
||||||
|
|
@ -487,33 +474,12 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const recoveryClient = (store: VaultStore): EmailRecoveryClient => {
|
|
||||||
const client = options.emailRecovery?.(store);
|
|
||||||
if (!client) {
|
|
||||||
fail(
|
|
||||||
options.emailRecovery
|
|
||||||
? "Email recovery needs your account: run `logicsrc login` first. It protects the default vault only."
|
|
||||||
: "Email recovery is an account feature: use `logicsrc vault` after `logicsrc login`.",
|
|
||||||
EXIT.USAGE,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return client;
|
|
||||||
};
|
|
||||||
|
|
||||||
parent
|
parent
|
||||||
.command("recover")
|
.command("recover")
|
||||||
.description("unlock with the recovery key (or --email) and set a new master password")
|
.description("unlock with the recovery key and set a new master password")
|
||||||
.option("--email", "recover through your account email instead of the offline recovery key (needs `recovery enable` first)")
|
.action(async function (this: Command) {
|
||||||
.addHelpText("after", examples(`
|
|
||||||
$CLI recover type the offline recovery key printed by \`init\`
|
|
||||||
$CLI recover --email the code from your enrollment email + a fresh emailed one-time code (works locked)`))
|
|
||||||
.action(async function (this: Command, opts: { email?: boolean }) {
|
|
||||||
await run(async () => {
|
await run(async () => {
|
||||||
const store = storeFor(this);
|
const store = storeFor(this);
|
||||||
if (opts.email) {
|
|
||||||
await recoverByEmail(store, recoveryClient(store));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const meta = requireMeta(store);
|
const meta = requireMeta(store);
|
||||||
const recoveryKey = await promptSecret("Recovery key: ");
|
const recoveryKey = await promptSecret("Recovery key: ");
|
||||||
let userKey: Uint8Array;
|
let userKey: Uint8Array;
|
||||||
|
|
@ -533,154 +499,6 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ------------------------------------------------------ email recovery ---
|
|
||||||
|
|
||||||
async function recoverByEmail(store: VaultStore, client: EmailRecoveryClient): Promise<void> {
|
|
||||||
requireMeta(store);
|
|
||||||
process.stderr.write(
|
|
||||||
'Email recovery needs the recovery code from the "Your LogicSRC vault email-recovery code" email.\n',
|
|
||||||
);
|
|
||||||
let result: EmailRecoveryResult;
|
|
||||||
try {
|
|
||||||
result = await runEmailRecovery({
|
|
||||||
store,
|
|
||||||
client,
|
|
||||||
say: (line) => process.stderr.write(`${line}\n`),
|
|
||||||
prompts: {
|
|
||||||
recoveryCode: () => promptSecret("Recovery code from the enrollment email: "),
|
|
||||||
oneTimeCode: () => promptSecret("One-time code from the email just sent: "),
|
|
||||||
newPassword: () => promptNewSecret("New master password: ", "Repeat: "),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
const code = (err as EmailRecoveryError).code;
|
|
||||||
fail((err as Error).message, code === "recovery_code_mismatch" || code === "escrow_stale" ? EXIT.CRYPTO : EXIT.USAGE);
|
|
||||||
}
|
|
||||||
unlockedKey = result.userKey;
|
|
||||||
store.appendAudit(
|
|
||||||
auditEvent({ action: "vault.recovery_reset", namespace: result.meta.namespace, reason: "email-recovery" }),
|
|
||||||
);
|
|
||||||
process.stdout.write(`Master password changed through email recovery. Not one item was re-encrypted.\n\n`);
|
|
||||||
process.stdout.write(` New recovery key ${result.recoveryKey}\n\n`);
|
|
||||||
process.stdout.write("Write it down now; it will not be shown again. The old recovery key no longer works.\n");
|
|
||||||
if (result.reenrolled) {
|
|
||||||
process.stdout.write(
|
|
||||||
`Email recovery is re-armed: a NEW recovery code was emailed to ${result.reenrolledEmail}. ` +
|
|
||||||
"The code you just used no longer works.\n",
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.stderr.write(
|
|
||||||
"\n!!! WARNING: your vault is recovered, but email recovery could NOT be re-armed" +
|
|
||||||
(result.reenrollError ? ` (${result.reenrollError})` : "") +
|
|
||||||
".\n!!! The recovery code you just used may still work on the server. Run `" + cli + " recovery enable`\n" +
|
|
||||||
"!!! now to replace it, or `" + cli + " recovery disable` to turn email recovery off.\n",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const recovery = parent
|
|
||||||
.command("recovery")
|
|
||||||
.description("email recovery (opt-in, $5 lifetime): get back in through your account email if the password is lost")
|
|
||||||
.addHelpText("after", examples(`
|
|
||||||
$CLI recovery status enrolled? since when? which email? purchased?
|
|
||||||
$CLI recovery buy print the CoinPay checkout link ($5, lifetime)
|
|
||||||
$CLI recovery enable enroll this vault (unlocks it); emails you a recovery code to keep
|
|
||||||
$CLI recovery disable turn it off; the server deletes its escrow share and copy
|
|
||||||
$CLI recover --email the day you need it: works with the vault locked
|
|
||||||
|
|
||||||
What the server keeps: a copy of your vault key encrypted under a random key E,
|
|
||||||
and one half of E (S), encrypted under the server's own key. The other half is
|
|
||||||
the recovery code in the enrollment email; the server never stores it.
|
|
||||||
Recovering needs that email plus a fresh one-time code. Without enrollment the
|
|
||||||
vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`));
|
|
||||||
|
|
||||||
recovery
|
|
||||||
.command("status")
|
|
||||||
.description("is email recovery enrolled and purchased (works locked)")
|
|
||||||
.option("--json", "machine-readable output")
|
|
||||||
.action(async function (this: Command, opts: { json?: boolean }) {
|
|
||||||
await run(async () => {
|
|
||||||
const client = recoveryClient(storeFor(this));
|
|
||||||
const status = await client.status();
|
|
||||||
if (opts.json) {
|
|
||||||
process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.stdout.write(` Account ${client.label}\n`);
|
|
||||||
process.stdout.write(
|
|
||||||
` Purchased ${status.purchased ? "yes (lifetime)" : `no ($${status.priceUsd} lifetime: \`${cli} recovery buy\`)`}\n`,
|
|
||||||
);
|
|
||||||
process.stdout.write(
|
|
||||||
` Enrolled ${status.enrolled ? `yes, since ${status.enrolledAt ?? "?"}` : `no${status.purchased ? ` (\`${cli} recovery enable\`)` : ""}`}\n`,
|
|
||||||
);
|
|
||||||
if (status.email) process.stdout.write(` Email ${status.email}\n`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
recovery
|
|
||||||
.command("buy")
|
|
||||||
.description("print the CoinPay checkout link for email recovery ($5 lifetime)")
|
|
||||||
.action(async function (this: Command) {
|
|
||||||
await run(async () => {
|
|
||||||
const client = recoveryClient(storeFor(this));
|
|
||||||
const status = await client.status();
|
|
||||||
if (status.purchased) {
|
|
||||||
process.stdout.write(`Email recovery is already purchased. Turn it on with \`${cli} recovery enable\`.\n`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const { url, priceUsd } = await client.checkout();
|
|
||||||
process.stdout.write(`Pay $${priceUsd} (lifetime) here, then run \`${cli} recovery enable\`:\n\n ${url}\n`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
recovery
|
|
||||||
.command("enable")
|
|
||||||
.description("enroll this vault in email recovery; running it again re-keys and emails a new code")
|
|
||||||
.action(async function (this: Command) {
|
|
||||||
await run(async () => {
|
|
||||||
const store = storeFor(this);
|
|
||||||
const client = recoveryClient(store);
|
|
||||||
const meta = requireMeta(store);
|
|
||||||
const status = await client.status();
|
|
||||||
if (!status.purchased) {
|
|
||||||
const checkout = await client.checkout().catch(() => undefined);
|
|
||||||
fail(
|
|
||||||
`Email recovery is a $${status.priceUsd} lifetime add-on and is not purchased yet.` +
|
|
||||||
(checkout ? ` Pay here, then run this again:\n\n ${checkout.url}\n` : ` Run \`${cli} recovery buy\`.`),
|
|
||||||
EXIT.USAGE,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const userKey = await unlock(store);
|
|
||||||
let result: { enrolled: boolean; email: string };
|
|
||||||
try {
|
|
||||||
result = await enrollEmailRecovery(client, meta, userKey);
|
|
||||||
} catch (err) {
|
|
||||||
const e = err as EmailRecoveryError;
|
|
||||||
fail(`${e.message}${e.checkoutUrl ? `\n\n ${e.checkoutUrl}\n` : ""}`, EXIT.USAGE);
|
|
||||||
}
|
|
||||||
process.stdout.write(
|
|
||||||
`Email recovery is on. Your recovery code was emailed to ${result.email}.\n` +
|
|
||||||
"Keep that email: it is half of the way back in, and it is not stored anywhere else.\n" +
|
|
||||||
(status.enrolled ? "The previous recovery code no longer works.\n" : ""),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
recovery
|
|
||||||
.command("disable")
|
|
||||||
.description("turn email recovery off; the server deletes its escrow share and copy")
|
|
||||||
.action(async function (this: Command) {
|
|
||||||
await run(async () => {
|
|
||||||
const client = recoveryClient(storeFor(this));
|
|
||||||
const { disabled } = await client.disable();
|
|
||||||
process.stdout.write(
|
|
||||||
disabled
|
|
||||||
? "Email recovery is off. The server deleted its share, so the emailed recovery code is useless now.\n"
|
|
||||||
: "Email recovery was not enabled.\n",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- items ---
|
// ---------------------------------------------------------------- items ---
|
||||||
|
|
||||||
const add = parent
|
const add = parent
|
||||||
|
|
@ -1291,9 +1109,7 @@ function registerSync(
|
||||||
: `vault sync: skipped (${message}); changes stay on this machine and go up next time.`,
|
: `vault sync: skipped (${message}); changes stay on this machine and go up next time.`,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
// `recovery …` talks to the account, not the vault files: nothing to sync around it.
|
const autosync = (command: Command) => !NO_AUTOSYNC.has(command.name()) && process.env.OPENCREDS_SYNC !== "off";
|
||||||
const autosync = (command: Command) =>
|
|
||||||
!NO_AUTOSYNC.has(command.name()) && command.parent?.name() !== "recovery" && process.env.OPENCREDS_SYNC !== "off";
|
|
||||||
|
|
||||||
parent.hook("preAction", async (_self, command) => {
|
parent.hook("preAction", async (_self, command) => {
|
||||||
if (!autosync(command)) return;
|
if (!autosync(command)) return;
|
||||||
|
|
|
||||||
|
|
@ -1,318 +0,0 @@
|
||||||
/**
|
|
||||||
* Email recovery: the XOR split, the escrow copy, the recovery code format, and
|
|
||||||
* the whole `recover --email` flow against a fake account server that behaves
|
|
||||||
* like apps/pwa (stores S and the blob, mails U and one-time codes, never keeps U).
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { mkdtempSync, rmSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
EmailRecoveryError,
|
|
||||||
RecoveryCodeMismatchError,
|
|
||||||
combineEscrowKey,
|
|
||||||
enrollEmailRecovery,
|
|
||||||
formatRecoveryCode,
|
|
||||||
openEscrow,
|
|
||||||
parseRecoveryCode,
|
|
||||||
prepareEnrollment,
|
|
||||||
recoverUserKeyByEmail,
|
|
||||||
runEmailRecovery,
|
|
||||||
sealEscrow,
|
|
||||||
splitEscrowKey,
|
|
||||||
xorBytes,
|
|
||||||
type EmailRecoveryClient,
|
|
||||||
type EscrowEnrollment,
|
|
||||||
type EscrowMaterial,
|
|
||||||
} from "./email-recovery.js";
|
|
||||||
import { createItem, encryptItem } from "./items.js";
|
|
||||||
import { fromBase64, randomBytes, toBase64 } from "./primitives.js";
|
|
||||||
import { createVaultStore } from "./store.js";
|
|
||||||
import { createVault, unlockVault, unlockWithRecoveryKey } from "./vault-key.js";
|
|
||||||
|
|
||||||
const FAST = { kdf: "pbkdf2-sha256" as const, iterations: 100_000 };
|
|
||||||
const dirs: string[] = [];
|
|
||||||
afterEach(() => {
|
|
||||||
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("the XOR split", () => {
|
|
||||||
it("splits E into two shares that recombine, and neither share is E", () => {
|
|
||||||
const E = randomBytes(32);
|
|
||||||
const { serverShare, userShare } = splitEscrowKey(E);
|
|
||||||
expect(serverShare).not.toEqual(E);
|
|
||||||
expect(userShare).not.toEqual(E);
|
|
||||||
expect(combineEscrowKey(serverShare, userShare)).toEqual(E);
|
|
||||||
expect(xorBytes(userShare, E)).toEqual(serverShare);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("gives a fresh server share every time", () => {
|
|
||||||
const E = randomBytes(32);
|
|
||||||
expect(splitEscrowKey(E).serverShare).not.toEqual(splitEscrowKey(E).serverShare);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuses shares of the wrong size", () => {
|
|
||||||
expect(() => splitEscrowKey(randomBytes(16))).toThrow();
|
|
||||||
expect(() => combineEscrowKey(randomBytes(32), randomBytes(31))).toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("the escrow copy of the user key", () => {
|
|
||||||
it("round-trips K under E, bound to the vault", async () => {
|
|
||||||
const { meta, userKey } = await createVault("pw", { params: FAST });
|
|
||||||
const sealed = await sealEscrow(userKey, meta);
|
|
||||||
const material = { ...sealed, vaultCreatedAt: meta.createdAt! };
|
|
||||||
expect(await openEscrow(sealed.escrowKey, material, meta.namespace)).toEqual(userKey);
|
|
||||||
// Another vault's createdAt is different associated data: the tag fails.
|
|
||||||
await expect(openEscrow(sealed.escrowKey, { ...material, vaultCreatedAt: "2001-01-01T00:00:00Z" }, meta.namespace)).rejects.toBeInstanceOf(
|
|
||||||
RecoveryCodeMismatchError,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("a wrong U fails cleanly with a mismatch error, not a crypto stack", async () => {
|
|
||||||
const { meta, userKey } = await createVault("pw", { params: FAST });
|
|
||||||
const { payload } = await prepareEnrollment(meta, userKey);
|
|
||||||
const material: EscrowMaterial = { ...payload };
|
|
||||||
const wrongU = randomBytes(32);
|
|
||||||
const err = await recoverUserKeyByEmail({ meta, material, userShare: wrongU }).catch((e) => e);
|
|
||||||
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
|
|
||||||
expect(err.message).toMatch(/doesn't match/);
|
|
||||||
// The right U opens it.
|
|
||||||
expect(await recoverUserKeyByEmail({ meta, material, userShare: fromBase64(payload.userShare) })).toEqual(userKey);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuses material enrolled for a different vault", async () => {
|
|
||||||
const a = await createVault("pw", { params: FAST });
|
|
||||||
const b = await createVault("pw", { params: FAST });
|
|
||||||
const { payload } = await prepareEnrollment(a.meta, a.userKey);
|
|
||||||
const err = await recoverUserKeyByEmail({
|
|
||||||
meta: { ...b.meta, createdAt: "2030-01-01T00:00:00Z" },
|
|
||||||
material: payload,
|
|
||||||
userShare: fromBase64(payload.userShare),
|
|
||||||
}).catch((e) => e);
|
|
||||||
expect(err).toBeInstanceOf(EmailRecoveryError);
|
|
||||||
expect(err.code).toBe("vault_mismatch");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("wipes E, S and U on request", async () => {
|
|
||||||
const { meta, userKey } = await createVault("pw", { params: FAST });
|
|
||||||
const prepared = await prepareEnrollment(meta, userKey);
|
|
||||||
expect(fromBase64(prepared.payload.userShare).some((b) => b !== 0)).toBe(true);
|
|
||||||
prepared.wipe(); // no throw; the base64 copies in the payload are what gets sent
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("the recovery code", () => {
|
|
||||||
it("is twelve groups of five and parses back to U", async () => {
|
|
||||||
const U = randomBytes(32);
|
|
||||||
const code = await formatRecoveryCode(U);
|
|
||||||
expect(code).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){11}$/);
|
|
||||||
expect(await parseRecoveryCode(code)).toEqual(U);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("tolerates case, spaces, missing dashes and Crockford's confusables", async () => {
|
|
||||||
const U = randomBytes(32);
|
|
||||||
const code = await formatRecoveryCode(U);
|
|
||||||
const sloppy = code.toLowerCase().replace(/-/g, " ").replace(/0/g, "o").replace(/1/g, "l");
|
|
||||||
expect(await parseRecoveryCode(sloppy)).toEqual(U);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("catches a typo with the check group, before anything is spent", async () => {
|
|
||||||
const U = randomBytes(32);
|
|
||||||
const code = await formatRecoveryCode(U);
|
|
||||||
// Change one data character to a different valid one.
|
|
||||||
const i = 7;
|
|
||||||
const swapped = code[i] === "A" ? "B" : "A";
|
|
||||||
const typo = code.slice(0, i) + swapped + code.slice(i + 1);
|
|
||||||
const err = await parseRecoveryCode(typo).catch((e) => e);
|
|
||||||
expect(err).toBeInstanceOf(EmailRecoveryError);
|
|
||||||
expect(err.code).toBe("recovery_code_typo");
|
|
||||||
// A typo in the check group itself is caught too.
|
|
||||||
const last = code.at(-1) === "Z" ? "Y" : "Z";
|
|
||||||
expect((await parseRecoveryCode(code.slice(0, -1) + last).catch((e) => e)).code).toBe("recovery_code_typo");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects the wrong length and bad characters", async () => {
|
|
||||||
expect((await parseRecoveryCode("ABCDE-FGHJK").catch((e) => e)).code).toBe("recovery_code_invalid");
|
|
||||||
const code = await formatRecoveryCode(randomBytes(32));
|
|
||||||
expect((await parseRecoveryCode(code.replace(/^./, "U")).catch((e) => e)).code).toBe("recovery_code_invalid");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
/** A fake apps/pwa: keeps S and the blob, "mails" U and one-time codes, and never stores U. */
|
|
||||||
function fakeServer() {
|
|
||||||
let enrollment: (EscrowMaterial & { active: boolean }) | null = null;
|
|
||||||
let otp: { code: string; used: boolean } | null = null;
|
|
||||||
const inbox: string[] = [];
|
|
||||||
const state = { starts: 0, claims: 0, failEnroll: false };
|
|
||||||
const client: EmailRecoveryClient = {
|
|
||||||
label: "fake.test (me@example.com)",
|
|
||||||
async status() {
|
|
||||||
return { enrolled: Boolean(enrollment?.active), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5 };
|
|
||||||
},
|
|
||||||
async checkout() {
|
|
||||||
return { url: "https://coinpay.test/pay/cs_1", priceUsd: 5 };
|
|
||||||
},
|
|
||||||
async enroll(p: EscrowEnrollment) {
|
|
||||||
if (state.failEnroll) throw new EmailRecoveryError("Could not send the enrollment email", 502, "email_failed");
|
|
||||||
enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, active: true };
|
|
||||||
inbox.push(await formatRecoveryCode(fromBase64(p.userShare)));
|
|
||||||
otp = null;
|
|
||||||
return { enrolled: true, email: "m***@example.com" };
|
|
||||||
},
|
|
||||||
async start() {
|
|
||||||
if (!enrollment?.active) throw new EmailRecoveryError("not enrolled", 404, "not_enrolled");
|
|
||||||
state.starts++;
|
|
||||||
otp = { code: String(Math.floor(Math.random() * 1e8)).padStart(8, "0"), used: false };
|
|
||||||
return { sent: true, email: "m***@example.com" };
|
|
||||||
},
|
|
||||||
async claim(code: string) {
|
|
||||||
state.claims++;
|
|
||||||
if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code");
|
|
||||||
otp.used = true;
|
|
||||||
const { active: _active, ...material } = enrollment!;
|
|
||||||
return material;
|
|
||||||
},
|
|
||||||
async disable() {
|
|
||||||
const was = Boolean(enrollment?.active);
|
|
||||||
enrollment = null;
|
|
||||||
return { disabled: was };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
return { client, inbox, state, otp: () => otp?.code ?? "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function vaultOnDisk() {
|
|
||||||
const dir = mkdtempSync(join(tmpdir(), "opencreds-email-recovery-"));
|
|
||||||
dirs.push(dir);
|
|
||||||
const store = createVaultStore(dir);
|
|
||||||
const created = await createVault("old master password", { params: FAST });
|
|
||||||
store.writeMeta(created.meta);
|
|
||||||
const item = createItem("login", { name: "GitHub", login: { username: "me", password: "hunter2" } });
|
|
||||||
store.writeEnvelope(await encryptItem(created.userKey, item, created.meta.namespace));
|
|
||||||
return { store, ...created };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("recover --email, end to end against a fake server", () => {
|
|
||||||
it("new password unlocks; the old password and the old recovery key do not; the used code is dead", async () => {
|
|
||||||
const { store, meta, userKey, recoveryKey: oldRecoveryKey } = await vaultOnDisk();
|
|
||||||
const server = fakeServer();
|
|
||||||
await enrollEmailRecovery(server.client, meta, userKey);
|
|
||||||
const enrolledCode = server.inbox.at(-1)!;
|
|
||||||
|
|
||||||
const said: string[] = [];
|
|
||||||
const result = await runEmailRecovery({
|
|
||||||
store,
|
|
||||||
client: server.client,
|
|
||||||
say: (l) => said.push(l),
|
|
||||||
prompts: {
|
|
||||||
recoveryCode: async () => enrolledCode,
|
|
||||||
oneTimeCode: async () => server.otp(),
|
|
||||||
newPassword: async () => "brand new master password",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.userKey).toEqual(userKey);
|
|
||||||
expect(result.recoveryKey).not.toBe(oldRecoveryKey);
|
|
||||||
expect(said.join("\n")).toMatch(/one-time code was emailed to m\*\*\*@example\.com/);
|
|
||||||
|
|
||||||
const onDisk = store.readMeta()!;
|
|
||||||
expect(onDisk.createdAt).toBe(meta.createdAt);
|
|
||||||
expect(await unlockVault(onDisk, "brand new master password")).toEqual(userKey);
|
|
||||||
await expect(unlockVault(onDisk, "old master password")).rejects.toThrow(/Wrong master password/);
|
|
||||||
await expect(unlockWithRecoveryKey(onDisk, oldRecoveryKey)).rejects.toThrow(/Wrong recovery key/);
|
|
||||||
expect(await unlockWithRecoveryKey(onDisk, result.recoveryKey)).toEqual(userKey);
|
|
||||||
|
|
||||||
// Re-armed with fresh shares: a new code was mailed and the old one no longer opens anything.
|
|
||||||
expect(result.reenrolled).toBe(true);
|
|
||||||
expect(server.inbox).toHaveLength(2);
|
|
||||||
expect(server.inbox[1]).not.toBe(enrolledCode);
|
|
||||||
await server.client.start();
|
|
||||||
const material = await server.client.claim(server.otp());
|
|
||||||
await expect(
|
|
||||||
recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(enrolledCode) }),
|
|
||||||
).rejects.toBeInstanceOf(RecoveryCodeMismatchError);
|
|
||||||
expect(
|
|
||||||
await recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(server.inbox[1]!) }),
|
|
||||||
).toEqual(userKey);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("a wrong recovery code: clear mismatch error, the one-time code is spent, the vault untouched", async () => {
|
|
||||||
const { store, meta, userKey } = await vaultOnDisk();
|
|
||||||
const server = fakeServer();
|
|
||||||
await enrollEmailRecovery(server.client, meta, userKey);
|
|
||||||
const before = JSON.stringify(store.readMeta());
|
|
||||||
const otherCode = await formatRecoveryCode(randomBytes(32)); // well-formed, just not ours
|
|
||||||
let asked = false;
|
|
||||||
const err = await runEmailRecovery({
|
|
||||||
store,
|
|
||||||
client: server.client,
|
|
||||||
prompts: {
|
|
||||||
recoveryCode: async () => otherCode,
|
|
||||||
oneTimeCode: async () => server.otp(),
|
|
||||||
newPassword: async () => {
|
|
||||||
asked = true;
|
|
||||||
return "x";
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}).catch((e) => e);
|
|
||||||
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
|
|
||||||
expect(err.message).toMatch(/doesn't match/);
|
|
||||||
expect(asked).toBe(false);
|
|
||||||
expect(server.state.claims).toBe(1);
|
|
||||||
await expect(server.client.claim(server.otp())).rejects.toThrow(/Wrong one-time code/); // spent
|
|
||||||
expect(JSON.stringify(store.readMeta())).toBe(before);
|
|
||||||
expect((await server.client.status()).enrolled).toBe(true); // the purchase and enrollment stand
|
|
||||||
});
|
|
||||||
|
|
||||||
it("a typo in the recovery code costs nothing: no one-time code is requested", async () => {
|
|
||||||
const { store, meta, userKey } = await vaultOnDisk();
|
|
||||||
const server = fakeServer();
|
|
||||||
await enrollEmailRecovery(server.client, meta, userKey);
|
|
||||||
const code = server.inbox.at(-1)!;
|
|
||||||
const typo = code.slice(0, 3) + (code[3] === "A" ? "B" : "A") + code.slice(4);
|
|
||||||
const err = await runEmailRecovery({
|
|
||||||
store,
|
|
||||||
client: server.client,
|
|
||||||
prompts: { recoveryCode: async () => typo, oneTimeCode: async () => "", newPassword: async () => "x" },
|
|
||||||
}).catch((e) => e);
|
|
||||||
expect(err.code).toBe("recovery_code_typo");
|
|
||||||
expect(server.state.starts).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("if re-enrolling fails the vault is still recovered, and the result says so", async () => {
|
|
||||||
const { store, meta, userKey } = await vaultOnDisk();
|
|
||||||
const server = fakeServer();
|
|
||||||
await enrollEmailRecovery(server.client, meta, userKey);
|
|
||||||
const code = server.inbox.at(-1)!;
|
|
||||||
server.state.failEnroll = true;
|
|
||||||
const result = await runEmailRecovery({
|
|
||||||
store,
|
|
||||||
client: server.client,
|
|
||||||
prompts: { recoveryCode: async () => code, oneTimeCode: async () => server.otp(), newPassword: async () => "new pw" },
|
|
||||||
});
|
|
||||||
expect(result.reenrolled).toBe(false);
|
|
||||||
expect(result.reenrollError).toMatch(/enrollment email/);
|
|
||||||
expect(await unlockVault(store.readMeta()!, "new pw")).toEqual(userKey);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("the server never receives E, and U only in the enroll call", async () => {
|
|
||||||
const { meta, userKey } = await vaultOnDisk();
|
|
||||||
const seen: EscrowEnrollment[] = [];
|
|
||||||
const server = fakeServer();
|
|
||||||
const spy: EmailRecoveryClient = {
|
|
||||||
...server.client,
|
|
||||||
enroll: async (p) => {
|
|
||||||
seen.push({ ...p });
|
|
||||||
return server.client.enroll(p);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
await enrollEmailRecovery(spy, meta, userKey);
|
|
||||||
const p = seen[0]!;
|
|
||||||
const E = combineEscrowKey(fromBase64(p.serverShare), fromBase64(p.userShare));
|
|
||||||
for (const value of Object.values(p)) expect(value).not.toBe(toBase64(E));
|
|
||||||
expect(await openEscrow(E, p, meta.namespace)).toEqual(userKey);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,401 +0,0 @@
|
||||||
/**
|
|
||||||
* Email recovery (opt-in, paid): a way back into a personal vault after the
|
|
||||||
* master password AND the offline recovery key are gone, through the account's
|
|
||||||
* mailbox.
|
|
||||||
*
|
|
||||||
* The client generates a random escrow key E and encrypts the user key K under
|
|
||||||
* it. E is then split into two XOR shares:
|
|
||||||
*
|
|
||||||
* S random 32 bytes held by the server, encrypted under its escrow key
|
|
||||||
* U E XOR S mailed to the account once, as a recovery code; never stored
|
|
||||||
*
|
|
||||||
* Neither share alone says anything about E (each is uniformly random on its
|
|
||||||
* own), so neither the database, nor the database plus the server's env, nor
|
|
||||||
* the enrollment email alone opens the vault. Recovering needs U (the user's
|
|
||||||
* mailbox, from enrollment) and S, which the server releases only against a
|
|
||||||
* fresh one-time code mailed at recovery time.
|
|
||||||
*
|
|
||||||
* The server sees U in transit once, at enrollment, to put it in the email. A
|
|
||||||
* live server compromise at that moment, or an attacker holding both the
|
|
||||||
* mailbox and a live server, can recover the vault; that is the trade this
|
|
||||||
* feature makes, and why it is opt-in. See docs/opencreds/security.md.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { decryptItem } from "./items.js";
|
|
||||||
import { emailEscrowLabel } from "./kdf.js";
|
|
||||||
import { aesGcmDecrypt, aesGcmEncrypt, fromBase64, KEY_BYTES, randomBytes, sha256, toBase64, utf8Encode } from "./primitives.js";
|
|
||||||
import type { VaultStore } from "./store.js";
|
|
||||||
import type { Envelope, VaultMeta } from "./types.js";
|
|
||||||
import { assertProfile, resetRecoveryKey, rewrapUserKey } from "./vault-key.js";
|
|
||||||
|
|
||||||
/** Crockford base32, the same alphabet as the offline recovery key. */
|
|
||||||
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
||||||
|
|
||||||
/** U is 256 bits; 55 characters carry 275, the last 19 always zero, so the groups come out even. */
|
|
||||||
export const RECOVERY_CODE_DATA_CHARS = 55;
|
|
||||||
/** One trailing group of five is a 25-bit checksum, so a typo is caught before anything is spent. */
|
|
||||||
export const RECOVERY_CODE_CHECK_CHARS = 5;
|
|
||||||
export const RECOVERY_CODE_CHARS = RECOVERY_CODE_DATA_CHARS + RECOVERY_CODE_CHECK_CHARS;
|
|
||||||
/** Domain separation for the checksum hash; the server renders codes with the same rule. */
|
|
||||||
export const RECOVERY_CODE_CHECK_PREFIX = "opencreds:email-recovery-code:v1";
|
|
||||||
|
|
||||||
/** Something went wrong in a way the person can act on. */
|
|
||||||
export class EmailRecoveryError extends Error {
|
|
||||||
constructor(
|
|
||||||
message: string,
|
|
||||||
readonly status?: number,
|
|
||||||
readonly code?: string,
|
|
||||||
readonly checkoutUrl?: string,
|
|
||||||
) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The recovery code decrypted nothing: it is not the code for this enrollment. */
|
|
||||||
export class RecoveryCodeMismatchError extends EmailRecoveryError {
|
|
||||||
constructor() {
|
|
||||||
super(
|
|
||||||
"That recovery code doesn't match this vault's email recovery. Use the code from the most recent " +
|
|
||||||
"\"vault email-recovery code\" email; an older one stops working when recovery is re-enabled.",
|
|
||||||
undefined,
|
|
||||||
"recovery_code_mismatch",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What the client sends to enroll. U (`userShare`) is mailed by the server and never stored. */
|
|
||||||
export interface EscrowEnrollment {
|
|
||||||
escrowBlob: string;
|
|
||||||
escrowIv: string;
|
|
||||||
serverShare: string;
|
|
||||||
userShare: string;
|
|
||||||
vaultCreatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What the server releases on a successful claim. */
|
|
||||||
export interface EscrowMaterial {
|
|
||||||
escrowBlob: string;
|
|
||||||
escrowIv: string;
|
|
||||||
serverShare: string;
|
|
||||||
vaultCreatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EmailRecoveryStatus {
|
|
||||||
enrolled: boolean;
|
|
||||||
enrolledAt: string | null;
|
|
||||||
/** Masked, e.g. a***@example.com. */
|
|
||||||
email: string | null;
|
|
||||||
purchased: boolean;
|
|
||||||
priceUsd: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The account's email-recovery endpoints. The logicsrc CLI provides one. */
|
|
||||||
export interface EmailRecoveryClient {
|
|
||||||
label: string;
|
|
||||||
status(): Promise<EmailRecoveryStatus>;
|
|
||||||
checkout(): Promise<{ url: string; priceUsd: number }>;
|
|
||||||
/** Throws EmailRecoveryError with status 402 and a checkoutUrl when not purchased. */
|
|
||||||
enroll(payload: EscrowEnrollment): Promise<{ enrolled: boolean; email: string }>;
|
|
||||||
start(): Promise<{ sent: boolean; email?: string }>;
|
|
||||||
claim(code: string): Promise<EscrowMaterial>;
|
|
||||||
disable(): Promise<{ disabled: boolean }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- shares ---
|
|
||||||
|
|
||||||
export function xorBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
|
|
||||||
if (a.length !== b.length) throw new Error("XOR shares must be the same length");
|
|
||||||
const out = new Uint8Array(a.length);
|
|
||||||
for (let i = 0; i < a.length; i++) out[i] = a[i]! ^ b[i]!;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Split E into a random server share S and the user share U = E XOR S. */
|
|
||||||
export function splitEscrowKey(escrowKey: Uint8Array): { serverShare: Uint8Array; userShare: Uint8Array } {
|
|
||||||
if (escrowKey.length !== KEY_BYTES) throw new Error(`The escrow key must be ${KEY_BYTES} bytes`);
|
|
||||||
const serverShare = randomBytes(KEY_BYTES);
|
|
||||||
return { serverShare, userShare: xorBytes(escrowKey, serverShare) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** E = S XOR U. */
|
|
||||||
export function combineEscrowKey(serverShare: Uint8Array, userShare: Uint8Array): Uint8Array {
|
|
||||||
if (serverShare.length !== KEY_BYTES || userShare.length !== KEY_BYTES) {
|
|
||||||
throw new Error(`Both escrow shares must be ${KEY_BYTES} bytes`);
|
|
||||||
}
|
|
||||||
return xorBytes(serverShare, userShare);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Overwrite key material that is no longer needed. Best effort: JS gives no stronger guarantee. */
|
|
||||||
export function wipe(...buffers: Array<Uint8Array | undefined>): void {
|
|
||||||
for (const b of buffers) b?.fill(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --------------------------------------------------------------- escrow ---
|
|
||||||
|
|
||||||
/** AAD binds the escrow copy to its purpose and to one vault (createdAt survives password changes). */
|
|
||||||
export function escrowAad(namespace: string, vaultCreatedAt: string): Uint8Array {
|
|
||||||
return utf8Encode(`${emailEscrowLabel(namespace)}|${vaultCreatedAt}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Encrypt the user key under a fresh random escrow key E. */
|
|
||||||
export async function sealEscrow(
|
|
||||||
userKey: Uint8Array,
|
|
||||||
meta: VaultMeta,
|
|
||||||
): Promise<{ escrowKey: Uint8Array; escrowBlob: string; escrowIv: string }> {
|
|
||||||
assertProfile(meta, ["user"]);
|
|
||||||
if (!meta.createdAt) throw new Error("This vault has no createdAt; it cannot be enrolled in email recovery");
|
|
||||||
const escrowKey = randomBytes(KEY_BYTES);
|
|
||||||
const { iv, ciphertext } = await aesGcmEncrypt(escrowKey, userKey, escrowAad(meta.namespace, meta.createdAt));
|
|
||||||
return { escrowKey, escrowBlob: toBase64(ciphertext), escrowIv: toBase64(iv) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Decrypt the user key with E. A wrong E (a wrong U) fails the GCM tag: {@link RecoveryCodeMismatchError}. */
|
|
||||||
export async function openEscrow(
|
|
||||||
escrowKey: Uint8Array,
|
|
||||||
material: Pick<EscrowMaterial, "escrowBlob" | "escrowIv" | "vaultCreatedAt">,
|
|
||||||
namespace: string,
|
|
||||||
): Promise<Uint8Array> {
|
|
||||||
try {
|
|
||||||
return await aesGcmDecrypt(
|
|
||||||
escrowKey,
|
|
||||||
fromBase64(material.escrowIv),
|
|
||||||
fromBase64(material.escrowBlob),
|
|
||||||
escrowAad(namespace, material.vaultCreatedAt),
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
throw new RecoveryCodeMismatchError();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything enrollment sends, plus a `wipe` that zeroes E, S and U. The
|
|
||||||
* payload's base64 strings cannot be zeroed; they live only until the request
|
|
||||||
* is sent.
|
|
||||||
*/
|
|
||||||
export async function prepareEnrollment(
|
|
||||||
meta: VaultMeta,
|
|
||||||
userKey: Uint8Array,
|
|
||||||
): Promise<{ payload: EscrowEnrollment; wipe: () => void }> {
|
|
||||||
const { escrowKey, escrowBlob, escrowIv } = await sealEscrow(userKey, meta);
|
|
||||||
const { serverShare, userShare } = splitEscrowKey(escrowKey);
|
|
||||||
return {
|
|
||||||
payload: {
|
|
||||||
escrowBlob,
|
|
||||||
escrowIv,
|
|
||||||
serverShare: toBase64(serverShare),
|
|
||||||
userShare: toBase64(userShare),
|
|
||||||
vaultCreatedAt: meta.createdAt!,
|
|
||||||
},
|
|
||||||
wipe: () => wipe(escrowKey, serverShare, userShare),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Enroll (or re-enroll) this vault. The server mails U and keeps S; a prior enrollment stops working. */
|
|
||||||
export async function enrollEmailRecovery(
|
|
||||||
client: EmailRecoveryClient,
|
|
||||||
meta: VaultMeta,
|
|
||||||
userKey: Uint8Array,
|
|
||||||
): Promise<{ enrolled: boolean; email: string }> {
|
|
||||||
const prepared = await prepareEnrollment(meta, userKey);
|
|
||||||
try {
|
|
||||||
return await client.enroll(prepared.payload);
|
|
||||||
} finally {
|
|
||||||
prepared.wipe();
|
|
||||||
prepared.payload.userShare = "";
|
|
||||||
prepared.payload.serverShare = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------- recovery code ---
|
|
||||||
|
|
||||||
function encodeBits(bytes: Uint8Array, chars: number): string {
|
|
||||||
let out = "";
|
|
||||||
for (let i = 0; i < chars; i++) {
|
|
||||||
let v = 0;
|
|
||||||
for (let b = 0; b < 5; b++) {
|
|
||||||
const bit = i * 5 + b;
|
|
||||||
const byte = bit >> 3;
|
|
||||||
v = (v << 1) | (byte < bytes.length ? (bytes[byte]! >> (7 - (bit & 7))) & 1 : 0);
|
|
||||||
}
|
|
||||||
out += ALPHABET[v];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Decode `text` into `length` bytes; `padOk` is false when a bit past them is set. */
|
|
||||||
function decodeBits(text: string, length: number): { bytes: Uint8Array; padOk: boolean } {
|
|
||||||
const bytes = new Uint8Array(length);
|
|
||||||
let padOk = true;
|
|
||||||
for (let i = 0; i < text.length; i++) {
|
|
||||||
const v = ALPHABET.indexOf(text[i]!);
|
|
||||||
if (v < 0) throw new EmailRecoveryError(`Invalid character in recovery code: ${text[i]}`, undefined, "recovery_code_invalid");
|
|
||||||
for (let b = 0; b < 5; b++) {
|
|
||||||
const bit = i * 5 + b;
|
|
||||||
const set = (v >> (4 - b)) & 1;
|
|
||||||
const byte = bit >> 3;
|
|
||||||
if (byte < length) bytes[byte] = (bytes[byte] ?? 0) | (set << (7 - (bit & 7)));
|
|
||||||
else if (set) padOk = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { bytes, padOk };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkGroup(userShare: Uint8Array): Promise<string> {
|
|
||||||
const digest = await sha256(new Uint8Array([...utf8Encode(RECOVERY_CODE_CHECK_PREFIX), ...userShare]));
|
|
||||||
return encodeBits(digest, RECOVERY_CODE_CHECK_CHARS);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Render U for the enrollment email: 11 groups of data and one check group,
|
|
||||||
* twelve groups of five in all.
|
|
||||||
*/
|
|
||||||
export async function formatRecoveryCode(userShare: Uint8Array): Promise<string> {
|
|
||||||
if (userShare.length !== KEY_BYTES) throw new Error(`The user share must be ${KEY_BYTES} bytes`);
|
|
||||||
const text = encodeBits(userShare, RECOVERY_CODE_DATA_CHARS) + (await checkGroup(userShare));
|
|
||||||
return (text.match(/.{1,5}/g) ?? []).join("-");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a recovery code back into U, tolerating case, spaces and dashes and
|
|
||||||
* Crockford's confusables. A typo fails the check group here, before the
|
|
||||||
* one-time code is asked for or spent.
|
|
||||||
*/
|
|
||||||
export async function parseRecoveryCode(input: string): Promise<Uint8Array> {
|
|
||||||
const clean = String(input || "")
|
|
||||||
.toUpperCase()
|
|
||||||
.replace(/[^0-9A-Z]/g, "")
|
|
||||||
.replace(/O/g, "0")
|
|
||||||
.replace(/[IL]/g, "1");
|
|
||||||
if (clean.length !== RECOVERY_CODE_CHARS) {
|
|
||||||
throw new EmailRecoveryError(
|
|
||||||
`That recovery code has ${clean.length} characters; it should have ${RECOVERY_CODE_CHARS} (12 groups of 5). ` +
|
|
||||||
"Copy it again from the enrollment email.",
|
|
||||||
undefined,
|
|
||||||
"recovery_code_invalid",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { bytes, padOk } = decodeBits(clean.slice(0, RECOVERY_CODE_DATA_CHARS), KEY_BYTES);
|
|
||||||
const check = clean.slice(RECOVERY_CODE_DATA_CHARS);
|
|
||||||
if (!padOk || check !== (await checkGroup(bytes))) {
|
|
||||||
wipe(bytes);
|
|
||||||
throw new EmailRecoveryError(
|
|
||||||
"That recovery code has a typo (its last group, the check group, does not match). Copy it again from the enrollment email.",
|
|
||||||
undefined,
|
|
||||||
"recovery_code_typo",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return bytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- recovery ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* K from the server's material and the user's code. Checks the material is for
|
|
||||||
* this vault, and that K actually opens an item when there is one to try.
|
|
||||||
*/
|
|
||||||
export async function recoverUserKeyByEmail(input: {
|
|
||||||
meta: VaultMeta;
|
|
||||||
material: EscrowMaterial;
|
|
||||||
userShare: Uint8Array;
|
|
||||||
envelopes?: Envelope[];
|
|
||||||
}): Promise<Uint8Array> {
|
|
||||||
const { meta, material, userShare } = input;
|
|
||||||
assertProfile(meta, ["user"]);
|
|
||||||
if (material.vaultCreatedAt !== meta.createdAt) {
|
|
||||||
throw new EmailRecoveryError(
|
|
||||||
`Email recovery was enrolled for a different vault (created ${material.vaultCreatedAt}); this one was created ${meta.createdAt ?? "?"}.`,
|
|
||||||
undefined,
|
|
||||||
"vault_mismatch",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const serverShare = fromBase64(material.serverShare);
|
|
||||||
const escrowKey = combineEscrowKey(serverShare, userShare);
|
|
||||||
try {
|
|
||||||
const userKey = await openEscrow(escrowKey, material, meta.namespace);
|
|
||||||
const probe = input.envelopes?.[0];
|
|
||||||
if (probe) {
|
|
||||||
try {
|
|
||||||
await decryptItem(userKey, probe, meta.namespace);
|
|
||||||
} catch {
|
|
||||||
wipe(userKey);
|
|
||||||
throw new EmailRecoveryError(
|
|
||||||
"The escrowed key does not open this vault's items. Nothing was changed.",
|
|
||||||
undefined,
|
|
||||||
"escrow_stale",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return userKey;
|
|
||||||
} finally {
|
|
||||||
wipe(serverShare, escrowKey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EmailRecoveryPrompts {
|
|
||||||
/** The recovery code from the enrollment email. */
|
|
||||||
recoveryCode(): Promise<string>;
|
|
||||||
/** The 8-digit one-time code mailed by `start`. */
|
|
||||||
oneTimeCode(email: string | undefined): Promise<string>;
|
|
||||||
/** The new master password, already confirmed. */
|
|
||||||
newPassword(): Promise<string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EmailRecoveryResult {
|
|
||||||
meta: VaultMeta;
|
|
||||||
userKey: Uint8Array;
|
|
||||||
/** The new offline recovery key, to print once. */
|
|
||||||
recoveryKey: string;
|
|
||||||
reenrolled: boolean;
|
|
||||||
reenrolledEmail?: string;
|
|
||||||
reenrollError?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The whole `recover --email` flow over a store and a client.
|
|
||||||
*
|
|
||||||
* Order matters: the recovery code is checked (checksum) before a one-time code
|
|
||||||
* is requested, so a typo costs nothing; the one-time code is spent on claim;
|
|
||||||
* nothing on disk changes until K is proven. After the new password is set,
|
|
||||||
* email recovery is re-armed with fresh shares, so the code just used is dead.
|
|
||||||
*/
|
|
||||||
export async function runEmailRecovery(opts: {
|
|
||||||
store: VaultStore;
|
|
||||||
client: EmailRecoveryClient;
|
|
||||||
prompts: EmailRecoveryPrompts;
|
|
||||||
say?: (line: string) => void;
|
|
||||||
}): Promise<EmailRecoveryResult> {
|
|
||||||
const { store, client, prompts } = opts;
|
|
||||||
const say = opts.say ?? (() => {});
|
|
||||||
const meta = store.readMeta();
|
|
||||||
if (!meta) throw new EmailRecoveryError(`No vault at ${store.baseDir}`, undefined, "no_vault");
|
|
||||||
assertProfile(meta, ["user"]);
|
|
||||||
|
|
||||||
const userShare = await parseRecoveryCode(await prompts.recoveryCode());
|
|
||||||
const userKey = await (async () => {
|
|
||||||
try {
|
|
||||||
const started = await client.start();
|
|
||||||
say(`A one-time code was emailed to ${started.email ?? "your account email"}. It expires in 15 minutes.`);
|
|
||||||
const code = (await prompts.oneTimeCode(started.email)).replace(/\s+/g, "");
|
|
||||||
const material = await client.claim(code);
|
|
||||||
return await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() });
|
|
||||||
} finally {
|
|
||||||
wipe(userShare);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
const password = await prompts.newPassword();
|
|
||||||
if (!password) throw new EmailRecoveryError("A master password is required", undefined, "no_password");
|
|
||||||
const rewrapped = await rewrapUserKey(meta, userKey, password);
|
|
||||||
const reset = await resetRecoveryKey(rewrapped, userKey);
|
|
||||||
store.writeMeta(reset.meta);
|
|
||||||
|
|
||||||
const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false };
|
|
||||||
try {
|
|
||||||
const enrolled = await enrollEmailRecovery(client, reset.meta, userKey);
|
|
||||||
result.reenrolled = Boolean(enrolled.enrolled);
|
|
||||||
result.reenrolledEmail = enrolled.email;
|
|
||||||
} catch (err) {
|
|
||||||
result.reenrollError = (err as Error).message;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
@ -53,7 +53,6 @@ export {
|
||||||
wrapLabel,
|
wrapLabel,
|
||||||
authLabel,
|
authLabel,
|
||||||
recoveryLabel,
|
recoveryLabel,
|
||||||
emailEscrowLabel,
|
|
||||||
itemLabel,
|
itemLabel,
|
||||||
databaseLabel,
|
databaseLabel,
|
||||||
assertUsableNamespace,
|
assertUsableNamespace,
|
||||||
|
|
@ -178,33 +177,6 @@ export {
|
||||||
type SyncState,
|
type SyncState,
|
||||||
} from "./sync.js";
|
} from "./sync.js";
|
||||||
|
|
||||||
export {
|
|
||||||
EmailRecoveryError,
|
|
||||||
RecoveryCodeMismatchError,
|
|
||||||
RECOVERY_CODE_CHARS,
|
|
||||||
RECOVERY_CODE_CHECK_CHARS,
|
|
||||||
RECOVERY_CODE_CHECK_PREFIX,
|
|
||||||
RECOVERY_CODE_DATA_CHARS,
|
|
||||||
combineEscrowKey,
|
|
||||||
enrollEmailRecovery,
|
|
||||||
escrowAad,
|
|
||||||
formatRecoveryCode,
|
|
||||||
openEscrow,
|
|
||||||
parseRecoveryCode,
|
|
||||||
prepareEnrollment,
|
|
||||||
recoverUserKeyByEmail,
|
|
||||||
runEmailRecovery,
|
|
||||||
sealEscrow,
|
|
||||||
splitEscrowKey,
|
|
||||||
xorBytes,
|
|
||||||
type EmailRecoveryClient,
|
|
||||||
type EmailRecoveryPrompts,
|
|
||||||
type EmailRecoveryResult,
|
|
||||||
type EmailRecoveryStatus,
|
|
||||||
type EscrowEnrollment,
|
|
||||||
type EscrowMaterial,
|
|
||||||
} from "./email-recovery.js";
|
|
||||||
|
|
||||||
export { auditEvent, fingerprint, type AuditInput } from "./audit.js";
|
export { auditEvent, fingerprint, type AuditInput } from "./audit.js";
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|
|
||||||
|
|
@ -58,15 +58,6 @@ export function recoveryLabel(namespace: Namespace): string {
|
||||||
return `${namespace}:vault:recovery:v1`;
|
return `${namespace}:vault:recovery:v1`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Associated data for the email-recovery escrow copy of the user key. Not an
|
|
||||||
* HKDF label: the escrow key is random, not derived, so the label only binds
|
|
||||||
* the ciphertext to its purpose (and, with the vault's createdAt, to one vault).
|
|
||||||
*/
|
|
||||||
export function emailEscrowLabel(namespace: Namespace): string {
|
|
||||||
return `${namespace}:vault:email-escrow:v1`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function itemLabel(namespace: Namespace, version: number, id: string): string {
|
export function itemLabel(namespace: Namespace, version: number, id: string): string {
|
||||||
return `${namespace}:vault:item:${version}:${id}`;
|
return `${namespace}:vault:item:${version}:${id}`;
|
||||||
}
|
}
|
||||||
|
|
|
||||||