Remove Flamenet Files, and delete accounts outright

Files was folded into the messenger, so this repository is the account
service and nothing else. The file server, its web client, its tenant
schemas and the documentation for all of it are gone.

Removed: EnclaveServer and its routes, EnclaveAccess, EnclaveCrypto, the
browser client under client/, the Files spec and vectors, the tenant SQL
under sql/, the web build and the node CI job, and the Leaf dependency
that only ever rendered the file server's pages. The Dockerfile built
EnclaveServer and shipped Public/ and Resources/; it now builds the
account service alone.

Nothing was lost. Every table in the production Files database was empty
when this was written: no nodes, no blobs, no identities, no tenants.
flamenetfiles.com, www.flamenetfiles.com and files.flamenet.io were
served by that stack and now answer 404; the compose file, the env and a
schema dump are on the box under /srv/prod/backups/, and the two docker
volumes were kept rather than pruned.

The service now issues pseudonyms for one product. `050_retire_files.sql`
deletes the `files` rows and replaces the CHECK constraint rather than
dropping it, so a container still being drained cannot write one back.
Every account had a `files` pseudonym and none had a `files` identity,
which is why there is no key material to migrate: the row was bookkeeping
for a product nobody enrolled in.

That also settles the delete endpoint added on this branch. It was built
around keeping a shared account alive while another product still held an
identity, and with one product that rule can never fire. `AccountRemoval`
and its five tests are gone, the response no longer reports which of two
outcomes happened, and a delete simply removes the account. None of it
had shipped, so there is no wire compatibility to keep.

Verified: the suites pass, the live delete script passes against a real
Postgres and a running service, and the image builds and boots to its
"DATABASE_URL is required" refusal, which is the account service and not
a file server.

`flamenet/files/auth/v1` stays as the authentication context string. It
is a wire constant baked into every stored verifier, not a product name,
and changing it would lock out every existing account. Said so in
ARCHITECTURE.md so nobody tidies it later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Paul Hitt
2026-09-21 17:30:55 -04:00
co-authored by Claude Opus 5
parent 6daaf6eb69
commit 7abe9c0ab2
111 changed files with 321 additions and 15270 deletions
+1 -26
View File
@@ -6,7 +6,7 @@
# somebody's word that the tests passed locally.
#
# ⚠️ Two suites, and they answer different questions. `swift test` proves the
# lattice, the SQL and the accounts kit; the node suite proves the client
# lattice, the SQL and the accounts kit.
# modules the browser actually runs. TESTING.md's table is worth reading before
# trusting either to mean more than it does — neither says whether a route or a
# button is wired to any of it. The integration scripts do, and they need a live
@@ -48,28 +48,3 @@ server:
exit (fails > 0)
}' swift-test.log
timeout: 30m
client:
stage: test
image: node:22-slim
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'
script:
# 🔴 **The GLOB, never the directory.** `node --test client/test/` reports a
# single opaque failure and runs NOTHING — verified, not taken on trust from
# TESTING.md. A gate written that way would have gone red forever for a
# reason nobody could read, which is how a suite gets switched off.
- node --test client/test/*.mjs 2>&1 | tee node-test.log
- |
# Same reasoning as the server gate: the glob matching too little is how
# this passes while proving nothing, so the count is the assertion.
awk '
/^# pass [0-9]+$/ { passed = $3 + 0 }
/^# fail [0-9]+$/ { failed = $3 + 0 }
END {
printf "GATE: %d client tests passed, %d failed\n", passed, failed
if (passed < 85) { print "GATE: too few client tests ran"; exit 1 }
exit (failed > 0)
}' node-test.log
timeout: 15m
+45 -192
View File
@@ -1,213 +1,66 @@
# Enclave
# The Flamenet account service
A Drive-style file service with Solaris-Zones-shaped tenant separation and
Oracle-Label-Security-shaped classification inside each tenant.
One handle and one passphrase, checked here, so a relay never sees either.
Working name; rename freely.
## Two axes, two mechanisms
| Axis | Analogue | Boundary | Enforced by |
|---|---|---|---|
| **Tenant** | Solaris zone / Oracle PDB | process + schema + DB role | OS process separation, Postgres **grants** |
| **Label** | Trusted Extensions / Oracle OLS | rows within a tenant | Postgres **RLS** |
Keeping these separate is the whole design. A process per (tenant × label) would
be combinatorial -- compartment sets are power-set sized -- so tenants get
processes and labels get row policies. The two mechanisms are independent: a bug
in the label lattice cannot leak across tenants, because grants stop it.
This repository was a file service with an account service beside it. Flamenet
Files was folded into the messenger on 2026-09-21 and the file server was
removed, so what is left is the account service and the security core it is
built on.
## Layout
```
Sources/EnclaveLattice/ Label, Classification, Compartments, Clearance. No deps.
Sources/EnclaveAccess/ Policy decisions, labeled-tree rules. Depends on lattice only.
sql/001_shared.sql enclave.* helpers + enclave_control.* registry.
sql/002_tenant_template.sql Per-tenant schema, RLS policies, tree trigger.
Sources/EnclaveAccountsKit/ Handle rules, credential hashing, rate limiting. No server deps.
Sources/EnclaveLattice/ Label, Classification, Compartments, Clearance. No deps.
Sources/EnclaveAuth/ The signed session token, and the keys that sign and verify it.
Sources/EnclaveSQL/ A statement splitter, so schema files can be run as scripts.
Sources/EnclaveAccounts/ The service: registration, sign-in, deletion, token minting.
Sources/EnclaveAccounts/SQL/ The schema, as numbered scripts run by Fluent migrations.
```
The two libraries are deliberately free of Vapor, Fluent, and Foundation-heavy
types: the security core should be testable without a server, and reusable from
a CLI or a sync daemon.
The kit and the lattice are deliberately free of Vapor, Fluent, and
Foundation-heavy types. The security-critical decisions should be testable
without a server, which is why the rules that matter live there and not in a
controller.
## The tenant axis is invisible to application code
## The boundary
Each tenant gets a schema, a role, and a worker process. The role carries a
fixed search path:
`EnclaveAccounts` runs as its own process, under a role granted `USAGE` on
`enclave_accounts` and nothing else. A relay holds no grant here in return.
Neither can read the other's tables, and the signed token is the whole
interface between them.
```sql
ALTER ROLE tenant_acme SET search_path = t_acme, enclave;
```
That boundary is what makes a self-hosted relay safe to run against this
service: it can verify a session it did not mint, and it cannot mint one. The
private half of the signing key never leaves this process.
Fluent models then declare plain table names and resolve into the right schema
automatically. No tenant ID threaded through queries, no `.filter(\.$tenant)`
that someone can forget. A worker holding `tenant_acme` credentials physically
cannot address another tenant's tables -- there is no grant to do so.
## What the passphrase produces
Cost to be aware of: migrations run once per schema. The control plane loops
them; Fluent's `_fluent_migrations` lands inside each tenant schema, which gives
per-tenant version tracking for free.
One passphrase produces two unrelated secrets, separated by an HKDF context
after a single expensive stretch: an authentication secret under
`flamenet/files/auth/v1`, which is sent here, and an identity key under
`flamenet/messenger/identity/v1`, which never leaves the device.
## The label axis, and the one thing that must be right
A fully compromised account service can therefore impersonate somebody to
itself and decrypt nothing of theirs.
Every request runs inside a transaction that first pins the session label:
The `files` in that first context string is a wire constant, not a product.
It was named before the products were, it is baked into every account's stored
verifier, and changing it would lock every existing account out.
```swift
extension Request {
/// The ONLY sanctioned path to the database. `req.db` is not vended.
func labeled<T>(_ body: (any Database) async throws -> T) async throws -> T {
let label = try requireSessionLabel() // set by the auth middleware
return try await db.transaction { db in
guard let sql = db as? any SQLDatabase else { throw Abort(.internalServerError) }
// SET LOCAL takes no bind parameters; set_config(..., is_local: true)
// is the parameterised equivalent and is injection-safe.
try await sql.raw("""
SELECT set_config('enclave.classification', \(bind: String(label.classification.rawValue)), true),
set_config('enclave.compartments', \(bind: String(label.compartments.postgresBitPattern)), true)
""").run()
return try await body(db)
}
}
}
```
## What it stores
Three properties worth understanding:
An opaque id, a login handle, the parameters a client needs to stretch a
passphrase, and a verifier to compare against. There is no email column:
omitting it is the privacy-maximal choice and it makes account recovery
impossible, which is a trade the operator makes knowingly.
1. **`SET LOCAL` is transaction-scoped**, so a pooled connection cannot leak one
user's label into another's request. This is why the wrapper is a transaction
and not a connection hook.
2. **Forgetting it fails closed.** Unset GUCs read as NULL, every dominance test
evaluates to NULL, and RLS treats NULL as false -- the query returns nothing.
Safe, but the symptom is an empty result set rather than an error, so the
middleware asserts the label is present instead of relying on this.
3. **Do not expose `req.db`.** The single greatest risk in this design is a
handler that reaches past the wrapper. Make the raw database internal, vend
only `req.labeled`, and add a CI grep for direct `req.db` use.
A product server sees only `HMAC(service_secret, account_id || product)`, never
the account id. The account service could correlate across products, which is
precisely why it stores so little else.
## What Fluent gives you for free
RLS filters below the ORM, so `Node.find(id, on: db)` returns `nil` for a row
the session does not dominate -- identical to a row that does not exist. Your
handler's ordinary `guard let ... else { throw Abort(.notFound) }` is already
the correct inference-controlled response. The 404-not-403 rule that usually
takes discipline to maintain falls out of the stack.
`Decision.httpStatus` in `EnclaveAccess` exists for the paths where you compute
a decision in Swift rather than letting the database do it -- keep those few.
## The account service
A third boundary, orthogonal to the two above. `EnclaveAccounts` runs as its own
process with a role granted `USAGE` on `enclave_accounts` and nothing else — no
tenant schema, no `enclave_control`. The file server's role has no grant on
`enclave_accounts` in return. Neither can read the other's tables, and the
signed token is the whole interface.
One passphrase produces two unrelated secrets: an authentication secret under
`flamenet/<product>/auth/v1`, sent to the account service, and an encryption key
under `flamenet/<product>/identity/v1`, which never leaves the browser. A fully
compromised account service can therefore impersonate a user to itself and
decrypt nothing.
Each product server sees only `HMAC(service_secret, account_id || product)`, so
Files cannot correlate its users with Messenger's. The account service can,
which is precisely why it stores an opaque id, a login handle, a verifier, and
nothing else.
## Labeled-tree rules
Two invariants, enforced in `Tree.swift` and again as database constraints:
- **A child's label dominates its parent's.** A SECRET file inside a
CONFIDENTIAL folder is fine and normal; the inverse strands the child, since
nobody could traverse to it. The trigger's parent lookup runs under the
caller's RLS, so an invisible parent is rejected exactly like a missing one.
- **Names are polyinstantiated.** Uniqueness is
`(parent, name, classification, compartments)`. A plain `UNIQUE(parent, name)`
turns a constraint violation into an existence oracle: create "Payroll", get a
duplicate-key error, and you have learned that a file you cannot see exists.
Resolution prefers an exact session-label match, then the unique most-sensitive
visible instance, and reports genuine ambiguity rather than guessing -- two
incomparable siblings sharing a name have no defensible winner.
## Covert channels closed on purpose
- **No cross-label deduplication.** Identical bytes at two labels are two blobs.
Collapsing them lets a low-cleared user probe for high-labeled content by
watching storage accounting or upload timing.
- **Per-label quota.** A tenant-wide free-space figure signals high-label
activity to low-cleared users.
- **Labeled audit rows.** The log carries the label of what it describes, so the
audit trail cannot become the leak.
Each costs real efficiency. They are deliberate.
## Regrade
Moving a node down the lattice is the only privileged operation, and there is no
code path that mutates a node's label directly -- the RLS UPDATE policy's
`WITH CHECK` forbids relabelling by ordinary write. Downgrades go through
`regrade_requests`: justification, two distinct reviewers neither of whom is the
requester, and an immutable record. Upgrades are free.
This workflow, not the lattice, is where the product value sits.
## Encryption: zero-knowledge
Server holds ciphertext only. Three levels:
```
identity key per user, from passphrase; never leaves the client
│ wraps
label key one per label in use; wrapped to every cleared principal
│ wraps
node key one per file/folder
│ wraps
content key one per revision
```
**Node keys wrap to the node's LABEL key, never to the parent folder's key.**
The tree invariant permits a RESTRICTED file inside a CONFIDENTIAL folder, so
parent-derived keys -- the conventional Drive design -- would hand every holder
of the folder key content above their clearance. RLS would still refuse to serve
it; a backup, snapshot, or compromised server would not. `KeyHierarchy.validate`
and the `node_keys` trigger both enforce this.
Filenames are ciphertext; uniqueness and lookup run on
`HMAC(folder_key, normalise(name))`, keyed per folder so the server cannot
invert names or correlate them across folders.
### Consequences, stated plainly
- **No deduplication at all.** Convergent encryption would give the server a
confirmation-of-file oracle, and across labels that is also a covert channel.
- **No server-side search.** A client-side encrypted index is the honest answer,
and it caps practical library size.
- **Regrade cannot inspect content.** The guard workflow is procedural: cleared
reviewers decrypt in their own client. No server-side content scanning.
- **Downgrades need a cleared client.** Re-encrypting under the lower label key
is work the server cannot do, so `approved` waits for a client to rewrap and
only that client can move the request to `applied`.
- **Revocation is imperfect.** Removing a compartment rotates the label key, but
a user who held the old key retains it. Prior content stays readable to them
until re-encrypted. Design the rotation; do not paper over the gap.
- **Password reset destroys data** unless recovery phrases exist from day one.
### What Leaf still renders
Auth, the app shell, and the whole control plane -- tenant config, clearance
administration, audit metadata, regrade queues. None of that is E2E, so Leaf
does real work there. The file browser itself is a JS surface that decrypts
client-side.
### Claim discipline
The web client fetches its JavaScript from your server on every load. A
compromised or coerced server can serve key-capturing code, so **"we cannot read
your files" is not truthfully claimable for the web client** -- only for a
native client with a pinned, signed binary. Say "encrypted in your browser
before upload"; keep the absolute claim for the native apps, once they exist.
The schema's foreign keys are `ON DELETE CASCADE` from `accounts`, so removing
an account removes its pseudonyms, clearances and devices in one statement
rather than in a list somebody has to keep in step by hand.
+7 -19
View File
@@ -1,6 +1,6 @@
# ---- build ------------------------------------------------------------------
# Swift 6.2, not 6.0: the dependency graph (swift-log, async-http-client,
# leaf, swift-nio) declares tools versions 6.1 and 6.2, and an older toolchain
# swift-nio) declares tools versions 6.1 and 6.2, and an older toolchain
# fails resolution outright rather than falling back.
FROM swift:6.2-noble AS build
@@ -12,27 +12,16 @@ RUN swift package resolve --skip-update
COPY Sources ./Sources
COPY Tests ./Tests
COPY Resources ./Resources
COPY Public ./Public
COPY client ./client
COPY scripts ./scripts
# The browser loads the same crypto modules the Node suite tests, rather than a
# separately-built bundle, so what ships is what is tested.
RUN ./scripts/build-web.sh
# Static stdlib keeps the runtime image free of a Swift installation.
# One image, both products: they share the token target and are deployed as
# separate containers from the same build.
RUN swift build -c release --product EnclaveServer --static-swift-stdlib \
&& swift build -c release --product EnclaveAccounts --static-swift-stdlib
RUN swift build -c release --product EnclaveAccounts --static-swift-stdlib
WORKDIR /staging
RUN BIN="$(swift build --package-path /build -c release --show-bin-path)" \
&& cp "$BIN/EnclaveServer" "$BIN/EnclaveAccounts" ./ \
&& find -L "$BIN" -regex '.*\.resources$' -exec cp -Ra {} ./ \; \
&& cp -r /build/Resources ./Resources \
&& cp -r /build/Public ./Public
&& cp "$BIN/EnclaveAccounts" ./ \
&& find -L "$BIN" -regex '.*\.resources$' -exec cp -Ra {} ./ \;
# ---- runtime ----------------------------------------------------------------
FROM ubuntu:noble
@@ -46,9 +35,8 @@ RUN useradd --user-group --create-home --system --skel /dev/null --home-dir /app
WORKDIR /app
COPY --from=build --chown=enclave:enclave /staging /app
RUN mkdir -p /app/blobs && chown enclave:enclave /app/blobs
USER enclave:enclave
EXPOSE 8080
EXPOSE 8100
# No ENTRYPOINT: compose selects which binary this container runs.
CMD ["./EnclaveServer", "serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
CMD ["./EnclaveAccounts", "serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8100"]
+10 -19
View File
@@ -1,5 +1,5 @@
{
"originHash" : "f3d15427b1c47aec3f5a27ced39db57bf3b0b4e9cd97b53d1fe161094f8283f8",
"originHash" : "bd0f329e436ac80519fc0e1ea8bde2091c8e860d3a0cc6e0696036be312511ad",
"pins" : [
{
"identity" : "async-http-client",
@@ -73,24 +73,6 @@
"version" : "5.2.0"
}
},
{
"identity" : "leaf",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/leaf.git",
"state" : {
"revision" : "21852a898dc8681ec072f79968f1c21fb87da8cb",
"version" : "4.5.2"
}
},
{
"identity" : "leaf-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/leaf-kit.git",
"state" : {
"revision" : "64cc0a5c8dcf4fbd03be73b944f6850c0b82e439",
"version" : "1.14.3"
}
},
{
"identity" : "multipart-kit",
"kind" : "remoteSourceControl",
@@ -190,6 +172,15 @@
"version" : "1.6.0"
}
},
{
"identity" : "swift-configuration",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-configuration.git",
"state" : {
"revision" : "3533f65d3e36dcdffc91ce34ef4d3c9c1887fd4b",
"version" : "1.2.1"
}
},
{
"identity" : "swift-crypto",
"kind" : "remoteSourceControl",
+2 -27
View File
@@ -6,18 +6,14 @@ let package = Package(
platforms: [.macOS(.v14)],
products: [
.library(name: "EnclaveLattice", targets: ["EnclaveLattice"]),
.library(name: "EnclaveAccess", targets: ["EnclaveAccess"]),
.library(name: "EnclaveCrypto", targets: ["EnclaveCrypto"]),
.library(name: "EnclaveSQL", targets: ["EnclaveSQL"]),
.library(name: "EnclaveAccountsKit", targets: ["EnclaveAccountsKit"]),
.executable(name: "EnclaveServer", targets: ["EnclaveServer"]),
.executable(name: "EnclaveAccounts", targets: ["EnclaveAccounts"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.106.0"),
.package(url: "https://github.com/vapor/fluent.git", from: "4.9.0"),
.package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.9.0"),
.package(url: "https://github.com/vapor/leaf.git", from: "4.3.0"),
.package(url: "https://github.com/vapor/jwt.git", from: "5.0.0"),
.package(url: "https://github.com/apple/swift-crypto.git", "3.0.0"..<"4.0.0"),
],
@@ -32,11 +28,8 @@ let package = Package(
name: "EnclaveAccountsKit",
dependencies: [.product(name: "Crypto", package: "swift-crypto")]
),
.target(name: "EnclaveCrypto", dependencies: ["EnclaveLattice"]),
.target(name: "EnclaveAccess", dependencies: ["EnclaveLattice", "EnclaveCrypto"]),
// Shared by the account service and the file server: the token is the
// only thing that crosses between them.
// The signed session token, and the keys that sign and verify it.
.target(
name: "EnclaveAuth",
dependencies: [
@@ -59,25 +52,7 @@ let package = Package(
swiftSettings: [.swiftLanguageMode(.v5)]
),
.executableTarget(
name: "EnclaveServer",
dependencies: [
"EnclaveLattice", "EnclaveAccess", "EnclaveCrypto", "EnclaveAuth", "EnclaveSQL",
.product(name: "Vapor", package: "vapor"),
.product(name: "Fluent", package: "fluent"),
.product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
.product(name: "Leaf", package: "leaf"),
.product(name: "JWT", package: "jwt"),
],
resources: [.copy("SQL")],
// Fluent's property wrappers on model classes do not yet satisfy
// Swift 6 strict concurrency. The security core above is compiled in
// v6 mode; only this target is held back, and only until Fluent
// catches up.
swiftSettings: [.swiftLanguageMode(.v5)]
),
.testTarget(name: "EnclaveLatticeTests", dependencies: ["EnclaveAccess", "EnclaveAuth"]),
.testTarget(name: "EnclaveLatticeTests", dependencies: ["EnclaveLattice", "EnclaveAuth"]),
.testTarget(name: "EnclaveSQLTests", dependencies: ["EnclaveSQL"]),
.testTarget(name: "EnclaveAccountsKitTests", dependencies: ["EnclaveAccountsKit"]),
]
-212
View File
@@ -1,212 +0,0 @@
/* The application. Same tokens as the marketing site so the two do not feel
* like different products, but none of the hero furniture. */
/* The `hidden` attribute is only `display: none` from the user-agent
* stylesheet, so any author rule that sets `display` silently beats it. Every
* element this interface hides also carries a display rule — .nav-right is
* flex, .field is block — which left the sign-out button and the recovery and
* claim-code fields painted at all times regardless of state.
*
* This has to be !important: the whole point is to outrank the specific rules
* that would otherwise win. */
[hidden] { display: none !important; }
.app-nav { border-bottom: 1px solid var(--border); background: var(--panel); position: sticky; top: 0; z-index: 40; }
.app-nav .wrap { display: flex; align-items: center; gap: 14px; height: 62px; }
.nav-right { display: flex; align-items: center; gap: 14px; margin-left: auto; }
.who { font-size: 14px; color: var(--ink-3); }
.app-main { padding: 30px 0 90px; }
/* The current label, always visible. Which sensitivity you are working at is
the single most consequential piece of state in this interface, so it lives
in the chrome rather than in a form control halfway down the page. */
.label-chip {
display: inline-flex; align-items: center; gap: 9px;
border: 1px solid var(--border-2); background: var(--grad-soft);
border-radius: 999px; padding: 7px 14px; font: inherit; font-size: 14px;
font-weight: 600; color: var(--brand); cursor: pointer;
}
.label-chip:hover { border-color: var(--brand-2); }
.chip-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; }
.chip-caret { color: var(--ink-3); font-size: 11px; }
.banner { background: var(--grad-soft); border-bottom: 1px solid var(--border-2); }
.banner .wrap { padding: 11px 24px; font-size: 14.5px; color: var(--brand); }
.panel {
background: var(--panel); border: 1px solid var(--border);
border-radius: var(--radius); padding: 28px; box-shadow: var(--shadow);
}
.signin, .recovery, .picker { max-width: 480px; margin: 26px auto 0; }
.panel h2 { margin: 0 0 6px; font-size: 21px; font-weight: 700; letter-spacing: -.015em; }
.panel h3 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
.panel .sub { margin: 0 0 22px; color: var(--ink-2); font-size: 14.5px; }
.field { display: block; margin-bottom: 16px; }
.field > span { display: block; font-size: 13.5px; font-weight: 600; color: var(--ink-2); margin-bottom: 6px; }
.field small { display: block; margin-top: 6px; font-size: 13px; color: var(--ink-3); }
.field input, .field select {
width: 100%; font: inherit; font-size: 15px; padding: 11px 13px;
border: 1px solid var(--border-2); border-radius: 10px; background: var(--bg); color: var(--ink);
}
.field input:focus, .field select:focus { outline: 2px solid var(--brand-2); outline-offset: 1px; border-color: transparent; }
.btn-block { width: 100%; text-align: center; }
.btn-sm { padding: 9px 18px; font-size: 14.5px; }
.btn[disabled] { opacity: .6; cursor: default; transform: none !important; box-shadow: none; }
.linkish { background: none; border: 0; color: var(--brand); font: inherit; font-size: 14px;
cursor: pointer; padding: 0; }
.linkish:hover { text-decoration: underline; }
.switcher { display: flex; justify-content: center; align-items: center; gap: 10px;
margin-top: 18px; font-size: 14px; color: var(--ink-3); }
.hint { margin: 12px 0 0; font-size: 13.5px; min-height: 1.2em; text-align: center; color: var(--ink-3); }
.hint[data-kind="error"] { color: #b3261e; }
/* Shown once, so it gets the weight of a thing you are meant to stop and act
on rather than a notification that slides away. */
.recovery { border-left: 3px solid var(--accent); }
.recovery-code {
font-family: var(--mono); font-size: 18px; letter-spacing: .07em; font-weight: 600;
background: var(--bg-3); border: 1px dashed var(--border-2); border-radius: 10px;
padding: 18px 16px; margin: 4px 0 8px; text-align: center; user-select: all; word-break: break-all;
}
.compartment {
display: inline-flex; align-items: center; gap: 7px; margin: 0 10px 8px 0;
font-size: 14px; color: var(--ink-2); cursor: pointer;
}
.compartment input { accent-color: var(--brand); }
.crumbs-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 12px; }
.actions { margin-left: auto; display: flex; gap: 9px; }
#breadcrumb { display: flex; gap: 2px; align-items: center; flex-wrap: wrap; }
.crumb { border: 0; background: none; padding: 5px 9px; color: var(--brand); font: inherit;
font-size: 14.5px; cursor: pointer; border-radius: 7px; }
.crumb:hover { background: var(--bg-3); }
.crumb[aria-current] { color: var(--ink); font-weight: 650; cursor: default; }
.crumb-sep { color: var(--ink-3); font-size: 13px; }
/* Drop target is the whole list, so there is no small rectangle to aim at. */
.dropzone { position: relative; border: 1px solid var(--border); border-radius: var(--radius);
background: var(--panel); min-height: 180px; }
.dropzone.over { border-color: var(--brand-2); background: var(--grad-soft); }
.drop-hint { display: none; position: absolute; inset: 0; align-items: center; justify-content: center;
font-weight: 650; color: var(--brand); pointer-events: none; }
.dropzone.over .drop-hint { display: flex; }
#listing { list-style: none; margin: 0; padding: 6px; }
.row { display: flex; align-items: center; gap: 14px; padding: 11px 12px; border-radius: 10px; }
.row + .row { border-top: 1px solid var(--border); }
.row:hover { background: var(--bg-2); }
.row-ic { width: 34px; height: 34px; border-radius: 9px; flex: none; display: flex;
align-items: center; justify-content: center; background: var(--bg-3); color: var(--ink-3); }
.row-ic svg { width: 17px; height: 17px; }
.row.is-folder .row-ic { background: var(--grad-soft); color: var(--brand); }
.name { border: 0; background: none; text-align: left; flex: 1; font: inherit; font-size: 15px;
cursor: pointer; padding: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.row.is-folder .name { font-weight: 650; }
.name:disabled { color: var(--ink-3); cursor: default; font-style: italic; }
.tag { font-size: 12px; font-weight: 600; color: var(--brand); background: var(--grad-soft);
border-radius: 999px; padding: 4px 10px; white-space: nowrap; }
.size, .when { font-size: 13px; color: var(--ink-3); white-space: nowrap; }
.when { min-width: 7.5em; text-align: right; }
.size { min-width: 4.5em; text-align: right; }
.empty { padding: 44px 20px; text-align: center; color: var(--ink-3); }
.empty strong { display: block; color: var(--ink-2); font-size: 15.5px; margin-bottom: 6px; }
.empty p { margin: 0; font-size: 14px; }
.preview-head { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
.preview-head .spacer { flex: 1; }
#preview-panel { margin-top: 22px; }
#preview { white-space: pre-wrap; word-break: break-word; font-family: var(--mono);
font-size: 13px; max-height: 22rem; overflow: auto; margin: 0;
background: var(--bg-3); padding: 16px; border-radius: 10px; }
.toast { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
background: var(--ink); color: #fff; padding: 12px 20px; border-radius: 999px;
font-size: 14.5px; box-shadow: var(--shadow-lg); z-index: 60; max-width: 90vw; }
.toast[data-kind="error"] { background: #b3261e; }
/* A busy button says so, because the key derivation genuinely takes seconds and
a silent pause reads as a broken page. */
.spinner { display: inline-block; width: 13px; height: 13px; margin-right: 8px;
border: 2px solid rgba(255,255,255,.45); border-top-color: #fff;
border-radius: 50%; animation: spin .7s linear infinite; vertical-align: -2px; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }
@media (max-width: 620px) {
.who { display: none; }
.when { display: none; }
.app-nav .wrap { gap: 8px; }
.crumbs-row .actions { margin-left: 0; width: 100%; }
}
/* ---------- shares ---------- */
.share { border-left: 3px solid var(--brand); margin-top: 22px; }
.share-link {
font-family: var(--mono); font-size: 13px; word-break: break-all;
background: var(--bg-3); border: 1px dashed var(--border-2); border-radius: 10px;
padding: 14px 16px; margin: 4px 0 16px; user-select: all;
}
.shared-notice { max-width: 480px; margin: 26px auto 0; border-left: 3px solid var(--accent); }
.shared-notice p { margin: 6px 0 0; color: var(--ink-2); font-size: 14.5px; }
.row-share { border: 0; background: none; color: var(--ink-3); cursor: pointer;
font: inherit; font-size: 13px; padding: 4px 8px; border-radius: 6px; }
.row-share:hover { background: var(--bg-3); color: var(--brand); }
/* ---------- label administration ---------- */
.labels-panel { margin-bottom: 18px; }
.labels-head { margin: 22px 0 10px; font-size: 14px; text-transform: uppercase;
letter-spacing: .06em; color: var(--ink-3); font-weight: 700; }
.labels-list { list-style: none; margin: 0; padding: 0; }
.labels-list li { display: flex; align-items: center; gap: 12px; padding: 10px 0;
border-bottom: 1px solid var(--border); }
.labels-list .ordinal { font-family: var(--mono); font-size: 12.5px; color: var(--ink-3);
min-width: 2.5em; }
.labels-list input[type=text] { flex: 1; font: inherit; font-size: 14.5px; padding: 7px 10px;
border: 1px solid transparent; border-radius: 8px; background: transparent;
color: var(--ink); }
.labels-list input[type=text]:hover { border-color: var(--border-2); }
.labels-list input[type=text]:focus { outline: 2px solid var(--brand-2); outline-offset: 1px;
background: var(--bg); border-color: transparent; }
.labels-list .empty-note { color: var(--ink-3); font-size: 14px; padding: 12px 0; }
.labels-add { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; }
.labels-add input[type=number] { width: 4.5em; font: inherit; font-size: 14.5px; padding: 8px 10px;
border: 1px solid var(--border-2); border-radius: 8px;
background: var(--bg); color: var(--ink); }
.labels-add input[type=text] { flex: 1; min-width: 10em; font: inherit; font-size: 14.5px;
padding: 8px 10px; border: 1px solid var(--border-2);
border-radius: 8px; background: var(--bg); color: var(--ink); }
.label-remove { border: 0; background: none; color: var(--ink-3); cursor: pointer; font: inherit;
font-size: 13px; padding: 4px 8px; border-radius: 6px; }
.label-remove:hover { background: var(--bg-3); color: #b3261e; }
/* Sharing an area with another principal. */
#share-area-panel { margin-bottom: 18px; }
.panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
.panel-note { margin: 6px 0 16px; color: var(--ink-2); font-size: 14.5px; line-height: 1.55; }
.field-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.field-row input {
flex: 1 1 220px; min-width: 0; padding: 11px 14px;
border: 1px solid var(--border); border-radius: 10px;
background: var(--field, #fff); color: inherit; font: inherit;
}
.panel-hint { margin: 12px 0 0; font-size: 14px; min-height: 1.2em; }
.panel-hint[data-kind="error"] { color: var(--danger, #b3261e); }
.panel-hint[data-kind="ok"] { color: var(--ok, #1b7f4b); }
/* Links already made for a file. */
.share-list { list-style: none; margin: 0 0 6px; padding: 0; }
.share-list li {
display: flex; align-items: center; gap: 12px; padding: 9px 0;
border-bottom: 1px solid var(--border); font-size: 14px;
}
.share-list .when { color: var(--ink-3); }
.share-list .flag {
font-size: 12px; padding: 2px 8px; border-radius: 999px;
background: var(--chip, rgba(0,0,0,.06)); color: var(--ink-2);
}
.share-list .spacer { flex: 1; }
-942
View File
@@ -1,942 +0,0 @@
import { EnclaveAPI } from "./crypto/api.js";
import { AccountsAPI } from "./crypto/accounts.js";
import { Session } from "./crypto/session.js";
import {
generateRecoveryCode, decode as decodeRecoveryCode, encode as encodeRecoveryCode,
} from "./crypto/recovery.js";
import {
generateIdentity, protectIdentity, protectIdentityWithRecovery, exportPublicKey,
} from "./crypto/identity.js";
import { label as makeLabel, permits } from "./crypto/lattice.js";
import { fromUtf8, b64 } from "./crypto/bytes.js";
const $ = (id) => document.getElementById(id);
const show = (el, visible) => el.toggleAttribute("hidden", !visible);
const accounts = new AccountsAPI(
document.querySelector('meta[name="enclave-accounts"]')?.content ?? ""
);
let session = null;
let clearance = null;
let vocabulary = { levels: [], compartments: [] };
let path = []; // breadcrumb of { id, name }
let mode = "signin"; // "signin" | "register" | "recover"
// ---------------------------------------------------------------- messages
let toastTimer = null;
function toast(message, kind = "info") {
clearTimeout(toastTimer);
$("toast-text").textContent = message;
$("toast").dataset.kind = kind;
show($("toast"), true);
toastTimer = setTimeout(() => show($("toast"), false), kind === "error" ? 7000 : 3500);
}
/**
* Turn a transport or crypto failure into something a person can act on.
*
* The raw errors are accurate and useless: "OperationError" is what WebCrypto
* says when a passphrase is wrong, and a bare 409 is what the server says when
* a handle is taken.
*/
function friendly(error) {
const message = String(error?.message ?? error);
if (/OperationError|operation-specific reason/i.test(message)) {
return "That passphrase doesn't unlock this account.";
}
if (/checksum/i.test(message)) return "That recovery code has a typo in it.";
if (/28 characters/i.test(message)) return "A recovery code is 28 characters. Check for a missing chunk.";
if (/not available/i.test(message)) return "That handle is already taken.";
if (/handle or passphrase/i.test(message)) return "Handle or passphrase is incorrect.";
if (/handle or recovery code/i.test(message)) return "Handle or recovery code is incorrect.";
if (/no recovery code on file/i.test(message)) return "This account has no recovery code on file.";
if (/Failed to fetch|NetworkError/i.test(message)) {
return "Couldn't reach the server. Check your connection and try again.";
}
if (/exceeds clearance/i.test(message)) return "You're not cleared for that combination.";
if (/aren't cleared for this file/i.test(message)) return message;
if (/Switch to that file's own label/i.test(message)) return message;
if (/filed at this level|in this area/.test(message)) return message;
if (/Editing labels needs a clearance/.test(message)) return message;
if (/would be invisible to you/.test(message)) return message;
if (/-> 409/.test(message)) return "Something with that name already exists here.";
if (/-> 401|-> 403/.test(message)) return "Your session has expired. Sign in again.";
if (/-> 404/.test(message)) return "That isn't here any more.";
return message;
}
function busy(button, on, label) {
button.disabled = on;
if (on) {
button.dataset.idle = button.textContent;
button.innerHTML = `<span class="spinner"></span>${label ?? button.dataset.idle}`;
} else if (button.dataset.idle) {
button.textContent = button.dataset.idle;
}
}
// ---------------------------------------------------------------- labels
const levelName = (ordinal) =>
vocabulary.levels.find((l) => l.ordinal === ordinal)?.name ?? `Level ${ordinal}`;
const compartmentName = (bit) =>
vocabulary.compartments.find((c) => c.bit === bit)?.name ?? `Area ${bit}`;
function labelText(label) {
const areas = label.compartments.map(compartmentName);
return areas.length ? `${levelName(label.classification)} // ${areas.join(", ")}`
: levelName(label.classification);
}
function buildLabelPicker() {
const select = $("classification");
select.innerHTML = "";
for (let i = clearance.minimum.classification; i <= clearance.maximum.classification; i++) {
select.append(new Option(levelName(i), String(i)));
}
select.value = String(clearance.maximum.classification);
const box = $("compartments");
box.innerHTML = "";
const bits = clearance.maximum.compartments;
show($("compartments-field"), bits.length > 0);
for (const bit of bits) {
const wrapper = document.createElement("label");
wrapper.className = "compartment";
wrapper.innerHTML =
`<input type="checkbox" value="${bit}" checked> ${compartmentName(bit)}`;
box.append(wrapper);
}
}
const selectedLabel = () => makeLabel(
Number($("classification").value),
[...document.querySelectorAll("#compartments input:checked")].map((i) => Number(i.value))
);
// ---------------------------------------------------------------- labels
//
// Editing the vocabulary lives here rather than in a database console, because
// a feature whose data can only be entered by hand is not finished.
function renderLabels() {
const levels = $("levels-list");
levels.innerHTML = "";
if (!vocabulary.levels.length) {
levels.innerHTML = '<li class="empty-note">No levels named yet.</li>';
}
for (const level of [...vocabulary.levels].sort((a, b) => a.ordinal - b.ordinal)) {
levels.append(labelRow({
key: level.ordinal,
name: level.name,
rename: (name) => api().post("/api/vocabulary/levels", { ordinal: level.ordinal, name }),
remove: () => api().delete(`/api/vocabulary/levels/${level.ordinal}`),
}));
}
const areas = $("compartments-list");
areas.innerHTML = "";
if (!vocabulary.compartments.length) {
areas.innerHTML = '<li class="empty-note">No areas named yet. Files can still use them by number.</li>';
}
for (const area of [...vocabulary.compartments].sort((a, b) => a.bit - b.bit)) {
areas.append(labelRow({
key: area.bit,
name: area.name,
rename: (name) => api().post("/api/vocabulary/compartments", { bit: area.bit, name }),
remove: () => api().delete(`/api/vocabulary/compartments/${area.bit}`),
}));
}
}
/** The session's API client, for calls that are not about files. */
function api() { return session.api; }
function labelRow({ key, name, rename, remove }) {
const item = document.createElement("li");
const ordinal = document.createElement("span");
ordinal.className = "ordinal";
ordinal.textContent = key;
const input = document.createElement("input");
input.type = "text";
input.value = name;
input.maxLength = 48;
// Commit on blur or Enter rather than per keystroke: every save is a write
// that renames the label for everyone.
const commit = async () => {
const next = input.value.trim();
if (!next || next === name) { input.value = name; return; }
try {
await rename(next);
await reloadVocabulary();
toast(`Renamed to "${next}"`);
} catch (error) {
input.value = name;
toast(friendly(error), "error");
}
};
input.onblur = commit;
input.onkeydown = (event) => { if (event.key === "Enter") input.blur(); };
const drop = document.createElement("button");
drop.className = "label-remove";
drop.textContent = "Remove";
drop.onclick = async () => {
if (!confirm(`Remove the name "${name}"? Files filed here keep their number.`)) return;
try {
await remove();
await reloadVocabulary();
toast(`Removed "${name}"`);
} catch (error) {
toast(friendly(error), "error");
}
};
item.append(ordinal, input, drop);
return item;
}
async function reloadVocabulary() {
vocabulary = await api().get("/api/vocabulary");
renderLabels();
buildLabelPicker();
$("label-chip-text").textContent = labelText(session.label);
await refresh();
}
async function addLevel() {
const ordinal = Number($("new-level-ordinal").value);
const name = $("new-level-name").value.trim();
if (!Number.isInteger(ordinal) || ordinal < 0) return toast("Give the level a number.", "error");
// Naming something above your own clearance would make it invisible to you
// and revoke your ability to edit. Refused here as well as by the server,
// so the explanation arrives before the work does.
if (ordinal > clearance.maximum.classification) {
return toast("You can't name a level above your own clearance — it would be invisible to you.", "error");
}
if (!name) return toast("Give the level a name.", "error");
try {
await api().post("/api/vocabulary/levels", { ordinal, name });
$("new-level-ordinal").value = ""; $("new-level-name").value = "";
await reloadVocabulary();
toast(`Added ${name}`);
} catch (error) { toast(friendly(error), "error"); }
}
async function addCompartment() {
const bit = Number($("new-compartment-bit").value);
const name = $("new-compartment-name").value.trim();
if (!Number.isInteger(bit) || bit < 0 || bit > 63) return toast("Areas are numbered 0 to 63.", "error");
if (!clearance.maximum.compartments.includes(bit)) {
return toast("You can't name an area you're not in — it would be invisible to you.", "error");
}
if (!name) return toast("Give the area a name.", "error");
try {
await api().post("/api/vocabulary/compartments", { bit, name });
$("new-compartment-bit").value = ""; $("new-compartment-name").value = "";
await reloadVocabulary();
toast(`Added ${name}`);
} catch (error) { toast(friendly(error), "error"); }
}
// ---------------------------------------------------------------- listing
const currentFolder = () => (path.length ? path[path.length - 1].id : null);
function formatBytes(bytes) {
if (bytes < 1024) return `${bytes} B`;
const units = ["KB", "MB", "GB", "TB"];
let value = bytes / 1024, unit = 0;
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
}
function formatWhen(iso) {
if (!iso) return "";
const then = new Date(iso), now = new Date();
const minutes = Math.round((now - then) / 60000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes} min ago`;
if (minutes < 60 * 24) return `${Math.round(minutes / 60)} h ago`;
const sameYear = then.getFullYear() === now.getFullYear();
return then.toLocaleDateString(undefined,
sameYear ? { month: "short", day: "numeric" } : { year: "numeric", month: "short", day: "numeric" });
}
const FOLDER_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
const FILE_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg>';
function renderBreadcrumb() {
const bar = $("breadcrumb");
bar.innerHTML = "";
const crumb = (text, index, current) => {
const button = document.createElement("button");
button.className = "crumb";
button.textContent = text;
if (current) button.setAttribute("aria-current", "page");
else button.onclick = () => { path = path.slice(0, index); refresh(); };
return button;
};
bar.append(crumb("All files", 0, path.length === 0));
path.forEach((entry, i) => {
const separator = document.createElement("span");
separator.className = "crumb-sep";
separator.textContent = "/";
bar.append(separator, crumb(entry.name ?? "…", i + 1, i === path.length - 1));
});
}
function emptyState() {
const item = document.createElement("li");
item.className = "empty";
item.innerHTML = path.length
? `<strong>This folder is empty</strong><p>Drop a file here, or use Upload.</p>`
: `<strong>Nothing here yet at ${labelText(session.label)}</strong>
<p>Drop a file to encrypt and upload it, or switch to a different sensitivity.</p>`;
return item;
}
async function refresh() {
renderBreadcrumb();
const list = $("listing");
list.innerHTML = '<li class="empty">Loading…</li>';
try {
const rows = await session.list(currentFolder());
list.innerHTML = "";
if (!rows.length) return void list.append(emptyState());
// Folders first, then by name, the way every file browser does it.
rows.sort((a, b) =>
(b.isFolder - a.isFolder) || String(a.name ?? "").localeCompare(String(b.name ?? "")));
for (const row of rows) list.append(renderRow(row));
} catch (error) {
list.innerHTML = "";
toast(friendly(error), "error");
}
}
function renderRow(row) {
const item = document.createElement("li");
item.className = `row${row.isFolder ? " is-folder" : ""}`;
const icon = document.createElement("span");
icon.className = "row-ic";
icon.innerHTML = row.isFolder ? FOLDER_ICON : FILE_ICON;
const name = document.createElement("button");
name.className = "name";
// "another area" was wrong and confusing in the case that matters: a row at
// *your own* label, filed by somebody whose key you have not been given.
// The chip says you are in that area while the row says you are not, which
// reads as a bug rather than as the design.
name.textContent = row.name ?? "Encrypted for another key";
name.disabled = row.name === null;
name.title = row.name ?? "You hold no key for this item's area";
if (row.isFolder) {
name.onclick = () => { path.push({ id: row.id, name: row.name }); refresh(); };
} else {
name.onclick = () => open(row);
}
const tag = document.createElement("span");
tag.className = "tag";
tag.textContent = labelText(row.label);
const when = document.createElement("span");
when.className = "when";
when.textContent = formatWhen(row.updatedAt);
const size = document.createElement("span");
size.className = "size";
size.textContent = row.isFolder ? "" : formatBytes(row.sizeBytes);
item.append(icon, name, tag, when, size);
// Folders cannot be link-shared yet, and a row you cannot decrypt is not
// yours to hand to anyone.
if (!row.isFolder && row.name !== null && row.blobID) {
const share = document.createElement("button");
share.className = "row-share";
share.textContent = "Share";
share.title = "Create a link that only cleared people can open";
share.onclick = (event) => { event.stopPropagation(); beginShare(row); };
item.append(share);
}
return item;
}
// ---------------------------------------------------------------- files
let lastDecrypted = null;
function looksLikeText(bytes) {
const sample = bytes.subarray(0, 800);
let printable = 0;
for (const byte of sample) {
if (byte === 9 || byte === 10 || byte === 13 || (byte >= 32 && byte < 127)) printable++;
}
return sample.length === 0 || printable / sample.length > 0.85;
}
async function open(row) {
if (!row.blobID) return toast("There's no content on this item.", "error");
toast(`Decrypting ${row.name}…`);
try {
const bytes = await session.download(row);
lastDecrypted = { name: row.name, bytes };
$("preview-name").textContent = row.name;
if (looksLikeText(bytes)) {
$("preview").textContent = fromUtf8(bytes).slice(0, 20000);
show($("preview"), true);
} else {
$("preview").textContent =
`${formatBytes(bytes.length)} decrypted in this tab. Save it to open it.`;
}
show($("preview-panel"), true);
$("preview-panel").scrollIntoView({ behavior: "smooth", block: "nearest" });
toast(`Decrypted ${row.name}`);
} catch (error) {
toast(friendly(error), "error");
}
}
// ---------------------------------------------------------------- sharing
let currentShare = null;
let pendingShare = null;
/** Step one: offer the password field. Nothing is created yet. */
function beginShare(row) {
pendingShare = row;
currentShare = null;
$("share-title").textContent = `Share ${row.name}`;
$("share-note").textContent =
`Anyone with the link who is also cleared for ${labelText(row.label)} can open it. `
+ `Anyone else gets nothing, even with the link.`;
$("share-password").value = "";
show($("share-password-field"), true);
show($("share-link"), false);
show($("share-copy"), false);
show($("share-revoke"), false);
show($("share-create"), true);
show($("share-existing"), false);
show($("share-panel"), true);
$("share-panel").scrollIntoView({ behavior: "smooth", block: "nearest" });
loadExistingShares(row);
}
/**
* Links already made for this file, with a way to revoke them.
*
* The panel used to show only the link it had just created, so a link made last
* week could not be revoked from the interface at all — the API could list and
* revoke it, nothing ever asked. Somebody who has handed out a link is exactly
* the person who needs to see it later.
*/
async function loadExistingShares(row) {
const list = $("share-list");
list.innerHTML = "";
let shares = [];
try {
shares = (await session.listShares(row.id)) ?? [];
} catch {
// Not worth failing the whole panel over: creating a link is the
// primary job here and this is context beside it.
show($("share-existing"), false);
return;
}
show($("share-existing"), shares.length > 0);
for (const share of shares) {
const item = document.createElement("li");
const when = document.createElement("span");
when.className = "when";
when.textContent = share.expiresAt
? `expires ${new Date(share.expiresAt).toLocaleDateString()}`
: "no expiry";
item.append(when);
if (share.needsPassword) {
const flag = document.createElement("span");
flag.className = "flag";
flag.textContent = "password";
item.append(flag);
}
const spacer = document.createElement("span");
spacer.className = "spacer";
item.append(spacer);
const revoke = document.createElement("button");
revoke.className = "linkish";
revoke.textContent = "Revoke";
revoke.onclick = async () => {
busy(revoke, true, "Revoking…");
try {
await session.revokeShare(share.id);
toast("Link revoked");
// Deliberately not "the file is private again": anyone who
// already fetched the wrapped key still holds it. Revoking
// stops the server handing it out again, and that is all.
await loadExistingShares(row);
} catch (error) {
toast(friendly(error), "error");
} finally {
busy(revoke, false);
}
};
item.append(revoke);
list.append(item);
}
}
async function createShare(row) {
const password = $("share-password").value.trim() || null;
toast(`Creating a link for ${row.name}…`);
try {
const share = await session.createShare(row, { password });
// The secret goes in the fragment, which browsers never send. The server
// storing this share genuinely cannot open it.
const link = `${location.origin}/s/${share.id}#${share.secret}`;
currentShare = { id: share.id, name: row.name };
$("share-title").textContent = `Link for ${row.name}`;
$("share-note").textContent = password
? `Needs three things: this link, a clearance for ${labelText(row.label)}, and the `
+ `password. Send the password by another route — putting it in the same message `
+ `defeats the point of having one. Expires in 7 days.`
: `Anyone with this link who is also cleared for ${labelText(row.label)} can open it. `
+ `Anyone else gets nothing, even with the link. Expires in 7 days.`;
$("share-link").textContent = link;
show($("share-link"), true);
show($("share-password-field"), false);
show($("share-create"), false);
show($("share-copy"), true);
show($("share-revoke"), true);
toast("Link created");
} catch (error) {
toast(friendly(error), "error");
}
}
/**
* Open a file someone shared, after sign-in.
*
* The secret is read from the fragment and then cleared from the address bar,
* so it does not sit in a screenshot or get pasted onward by accident. It is
* still in history; the link is not a secret from the person holding it.
*/
async function openSharedLink(shareID, secret, password = null) {
toast("Opening shared file…");
try {
const { name, bytes } = await session.openSharedFile(shareID, secret, password);
lastDecrypted = { name, bytes };
$("preview-name").textContent = name;
$("preview").textContent = looksLikeText(bytes)
? fromUtf8(bytes).slice(0, 20000)
: `${formatBytes(bytes.length)} decrypted in this tab. Save it to open it.`;
show($("preview-panel"), true);
history.replaceState(null, "", "/app");
toast(`Opened ${name}`);
} catch (error) {
toast(friendly(error), "error");
}
}
function save() {
if (!lastDecrypted) return;
// Decrypted in memory here, so the download never touches the network.
const url = URL.createObjectURL(new Blob([lastDecrypted.bytes]));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = lastDecrypted.name;
anchor.click();
URL.revokeObjectURL(url);
}
async function uploadFiles(files) {
const list = [...files];
if (!list.length) return;
for (const [index, file] of list.entries()) {
toast(`Encrypting ${file.name}${list.length > 1 ? ` (${index + 1}/${list.length})` : ""}…`);
try {
const bytes = new Uint8Array(await file.arrayBuffer());
await session.uploadFile(file.name, bytes, currentFolder());
} catch (error) {
toast(`${file.name}: ${friendly(error)}`, "error");
break;
}
}
await refresh();
toast(list.length === 1
? `Uploaded ${list[0].name}, encrypted before it left this tab`
: `Uploaded ${list.length} files, encrypted before they left this tab`);
}
async function newFolder() {
const name = prompt("Name this folder");
if (!name?.trim()) return;
try {
await session.createFolder(name.trim(), currentFolder());
await refresh();
toast(`Created ${name.trim()}`);
} catch (error) {
toast(friendly(error), "error");
}
}
// ---------------------------------------------------------------- session
function setMode(next) {
mode = next;
const recovering = next === "recover";
show($("passphrase-field"), !recovering);
show($("recovery-field"), recovering);
show($("new-passphrase-field"), recovering);
show($("register-toggle"), !recovering);
$("signin-title").textContent =
recovering ? "Get back in" : next === "register" ? "Create your account" : "Welcome back";
$("signin-sub").textContent = recovering
? "Your recovery code sets a new passphrase and unlocks your files. You'll get a fresh code afterwards."
: next === "register"
? "Pick a handle and a passphrase. The passphrase never leaves this tab, and we can't reset it — you'll get a recovery code instead."
: "Your passphrase never leaves this tab. It builds your keys here, on your device.";
$("mode-toggle").textContent = recovering ? "Back to signing in" : "I've lost my passphrase";
$("register-toggle").textContent = next === "register" ? "I already have an account" : "Create an account";
$("signin-button").textContent =
recovering ? "Recover access" : next === "register" ? "Create account" : "Unlock";
$("signin-hint").textContent = "";
}
function hint(message, kind = "info") {
$("signin-hint").textContent = message;
$("signin-hint").dataset.kind = kind;
}
async function signIn() {
const handle = $("handle").value.trim();
if (!handle) return hint("Enter your handle to continue.", "error");
const button = $("signin-button");
busy(button, true, "Deriving keys…");
hint("This takes a few seconds on purpose — it's what makes a short passphrase hard to attack.");
let token, freshEntropy = null, nextEntropy = null;
// Set only when this call registered the account, so the identity does not
// have to be fetched back and unwrapped a moment after we built it.
let enrolledPair = null, enrolledCode = null;
try {
if (mode === "register") {
const passphrase = $("passphrase").value;
if (!passphrase) throw new Error("Choose a passphrase.");
// One code, bound to both halves: the account credential and the
// file key. Recovering one without the other locks you out anyway.
freshEntropy = (await generateRecoveryCode()).entropy;
// Built here, before the account exists, so both can be written in
// one transaction. Registering first and enrolling afterwards left
// a window where a closed tab stranded a handle that was taken,
// unusable, and impossible to enrol into.
enrolledPair = await generateIdentity();
enrolledCode = await encodeRecoveryCode(freshEntropy);
const [record, recovery] = await Promise.all([
protectIdentity(enrolledPair.privateKey, passphrase),
protectIdentityWithRecovery(enrolledPair.privateKey, freshEntropy),
]);
await accounts.register({
handle, passphrase, recoveryEntropy: freshEntropy,
identity: {
product: "files",
publicKey: b64(await exportPublicKey(enrolledPair.publicKey)),
protectedRecord: JSON.stringify(record),
recoveryRecord: JSON.stringify(recovery),
},
});
({ token } = await accounts.signIn({ handle, passphrase }));
} else if (mode === "recover") {
const code = $("recovery-code").value.trim();
const newPassphrase = $("new-passphrase").value;
if (!code) throw new Error("Enter your recovery code.");
if (!newPassphrase) throw new Error("Choose a new passphrase.");
const entropy = await decodeRecoveryCode(code);
nextEntropy = (await generateRecoveryCode()).entropy;
await accounts.rotate({ handle, entropy, newPassphrase, nextEntropy });
({ token } = await accounts.signIn({ handle, passphrase: newPassphrase }));
} else {
const passphrase = $("passphrase").value;
if (!passphrase) throw new Error("Enter your passphrase.");
({ token } = await accounts.signIn({ handle, passphrase }));
}
clearance = readClearance(token);
} catch (error) {
busy(button, false);
return hint(friendly(error), "error");
}
const api = new EnclaveAPI({ token });
try {
session = mode === "recover"
? await Session.recover({
api, accounts, token, code: $("recovery-code").value.trim(),
newPassphrase: $("new-passphrase").value, clearance, nextEntropy })
: enrolledPair
? Session.enrolled({
api, accounts, token, pair: enrolledPair, clearance, recoveryCode: enrolledCode })
: await Session.open({
api, accounts, token, passphrase: $("passphrase").value, clearance });
await session.loadLabelKeys();
vocabulary = await api.get("/api/vocabulary");
buildLabelPicker();
// Offered only to callers the server would accept, so nobody discovers
// the restriction by being refused.
show($("labels-button"), vocabulary.canEdit === true);
$("who").textContent = handle;
show($("signin"), false);
show($("session-bar"), true);
if (session.recoveryCode) {
$("recovery-code-out").textContent = session.recoveryCode;
show($("recovery-panel"), true);
return;
}
await enterWorkspace();
} catch (error) {
hint(friendly(error), "error");
} finally {
busy(button, false);
}
}
async function enterWorkspace() {
show($("recovery-panel"), false);
show($("shared-notice"), false);
show($("workspace"), true);
await applyLabel({ silent: true });
// Arrived via a share link: open it once signed in, asking for the
// password first only if the link actually has one.
if (sharedMatch && sharedSecret) {
let password = null;
try {
if (await session.shareNeedsPassword(sharedMatch[1])) {
password = prompt("This link needs the password it was sent with:");
if (!password) return toast("A password is needed to open this file.", "error");
}
} catch (error) {
return toast(friendly(error), "error");
}
await openSharedLink(sharedMatch[1], sharedSecret, password);
}
}
async function applyLabel({ silent = false } = {}) {
const label = selectedLabel();
if (!permits(clearance, label)) return toast("You're not cleared for that combination.", "error");
path = [];
await session.use(label);
$("label-chip-text").textContent = labelText(label);
show($("label-picker"), false);
$("label-chip").setAttribute("aria-expanded", "false");
// Which sensitivity you are filing under is worth stating in words, not
// just showing as a chip that could be misread at a glance.
$("banner-text").textContent =
`You're working at ${labelText(label)}. New files are filed here, and you'll only see what this reaches.`;
show($("banner"), true);
await refresh();
if (!silent) toast(`Now working at ${labelText(label)}`);
}
function signOut() {
// Everything sensitive is held in memory only, so a reload genuinely
// forgets it — no token to revoke, no key to wipe. The flag exists so the
// next page can say so, rather than dropping someone on a login form with
// no explanation of why they are looking at it.
location.replace("/app?signedout=1");
}
// ---------------------------------------------------------------- wiring
function readClearance(token) {
const [, payload] = token.split(".");
if (!payload) throw new Error("not a token");
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
const bits = (mask) => {
const out = [];
const value = BigInt.asUintN(64, BigInt(mask));
for (let i = 0; i < 64; i++) if ((value >> BigInt(i)) & 1n) out.push(i);
return out;
};
return {
maximum: makeLabel(json.mxc, bits(json.mxk)),
minimum: makeLabel(json.mnc, bits(json.mnk)),
};
}
$("signin-button").onclick = signIn;
for (const id of ["handle", "passphrase", "recovery-code", "new-passphrase"]) {
$(id).addEventListener("keydown", (event) => { if (event.key === "Enter") signIn(); });
}
$("mode-toggle").onclick = () => setMode(mode === "recover" ? "signin" : "recover");
$("register-toggle").onclick = () => setMode(mode === "register" ? "signin" : "register");
$("recovery-ack").onclick = () => {
session.recoveryCode = null;
$("recovery-code-out").textContent = "";
enterWorkspace();
};
$("recovery-copy").onclick = async () => {
try {
await navigator.clipboard.writeText($("recovery-code-out").textContent);
toast("Copied — put it somewhere that isn't this machine");
} catch {
toast("Couldn't copy. Select the code and copy it manually.", "error");
}
};
$("label-chip").onclick = () => {
const open = $("label-picker").hasAttribute("hidden");
show($("label-picker"), open);
$("label-chip").setAttribute("aria-expanded", String(open));
};
$("cancel-label").onclick = () => {
show($("label-picker"), false);
$("label-chip").setAttribute("aria-expanded", "false");
};
$("apply-label").onclick = () => applyLabel();
$("sign-out").onclick = signOut;
$("new-folder-button").onclick = newFolder;
$("upload-button").onclick = () => $("upload").click();
$("upload").onchange = (event) => { uploadFiles(event.target.files); event.target.value = ""; };
$("preview-save").onclick = save;
$("close-preview").onclick = () => show($("preview-panel"), false);
const dropzone = $("dropzone");
for (const type of ["dragenter", "dragover"]) {
dropzone.addEventListener(type, (event) => {
event.preventDefault();
dropzone.classList.add("over");
});
}
for (const type of ["dragleave", "drop"]) {
dropzone.addEventListener(type, (event) => {
event.preventDefault();
if (type === "dragleave" && dropzone.contains(event.relatedTarget)) return;
dropzone.classList.remove("over");
});
}
dropzone.addEventListener("drop", (event) => {
if (session && event.dataTransfer?.files?.length) uploadFiles(event.dataTransfer.files);
});
// Arriving from "Get started" should land on the right form, not make someone
// hunt for the link that switches it.
const sharedMatch = location.pathname.match(/^\/s\/([0-9a-fA-F-]{36})$/);
const sharedSecret = location.hash.slice(1);
if (sharedMatch) show($("shared-notice"), true);
const entry = new URLSearchParams(location.search);
setMode(entry.has("new") ? "register" : "signin");
if (entry.has("signedout")) {
hint("You're signed out. Your keys were only ever held in this tab, so they're gone.");
}
$("app-signin-link").href = "/app";
$("share-create").onclick = () => { if (pendingShare) createShare(pendingShare); };
$("share-password").addEventListener("keydown", (event) => {
if (event.key === "Enter" && pendingShare) createShare(pendingShare);
});
$("share-copy").onclick = async () => {
try {
await navigator.clipboard.writeText($("share-link").textContent);
toast("Link copied");
} catch {
toast("Couldn't copy. Select the link and copy it manually.", "error");
}
};
$("close-share").onclick = () => show($("share-panel"), false);
$("share-revoke").onclick = async () => {
if (!currentShare) return;
try {
await session.revokeShare(currentShare.id);
show($("share-panel"), false);
toast(`Link for ${currentShare.name} revoked. Anyone who already opened it keeps what they downloaded.`);
currentShare = null;
} catch (error) {
toast(friendly(error), "error");
}
};
// ------------------------------------------------------------ sharing an area
function shareAreaHint(message, kind = "info") {
const el = $("share-area-hint");
el.textContent = message;
el.dataset.kind = kind;
}
$("share-area-button").onclick = () => {
const opening = $("share-area-panel").hasAttribute("hidden");
show($("share-area-panel"), opening);
if (!opening) return;
$("share-area-label").textContent = labelText(session.label);
$("share-area-handle").value = "";
shareAreaHint("");
$("share-area-handle").focus();
};
$("close-share-area").onclick = () => show($("share-area-panel"), false);
$("share-area-submit").onclick = async () => {
const handle = $("share-area-handle").value.trim();
if (!handle) return shareAreaHint("Enter the handle to share with.", "error");
const button = $("share-area-submit");
busy(button, true, "Wrapping…");
shareAreaHint("");
try {
await session.shareArea(handle);
// Named plainly, because "shared" understates it: this is durable read
// access to everything at the label, not a one-off.
shareAreaHint(
`${handle} can now read everything in ${labelText(session.label)}.`, "ok");
$("share-area-handle").value = "";
toast("Key given to " + handle);
} catch (error) {
shareAreaHint(friendly(error), "error");
} finally {
busy(button, false);
}
};
$("labels-button").onclick = () => {
const opening = $("labels-panel").hasAttribute("hidden");
if (opening) renderLabels();
show($("labels-panel"), opening);
};
$("close-labels").onclick = () => show($("labels-panel"), false);
$("add-level").onclick = addLevel;
$("add-compartment").onclick = addCompartment;
for (const id of ["new-level-name", "new-compartment-name"]) {
$(id).addEventListener("keydown", (event) => {
if (event.key === "Enter") (id === "new-level-name" ? addLevel : addCompartment)();
});
}
-346
View File
@@ -1,346 +0,0 @@
/* Flamenet Files — site theme.
*
* Deliberately the same design system as Flamenet Messenger: violet primary
* with an amber accent on white, committed to a single light look rather than
* following the system scheme. Written fresh against those tokens rather than
* copied from the Messenger repo, which is private while this one is public.
*
* Everything is self-hosted. The server sends `default-src 'self'`, so a CDN
* font or an analytics tag would simply not load — the intended failure mode
* rather than an inconvenience. Hence the system font stack.
*/
:root {
--bg: #ffffff;
--bg-2: #f7f8fc;
--bg-3: #f1f3f9;
--panel: #ffffff;
--ink: #212529;
--ink-2: #5b6472;
--ink-3: #838b99;
--border: #eaedf5;
--border-2: #dde2ee;
--brand: #5842bc;
--brand-2: #7b63e8;
--brand-ink: #ffffff;
--accent: #fdb900;
--grad: linear-gradient(115deg, var(--brand) 0%, var(--brand-2) 100%);
--grad-soft: linear-gradient(115deg, rgba(88,66,188,.10), rgba(123,99,232,.08));
--radius: 16px;
--radius-lg: 22px;
--wrap: 1180px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--shadow: 0 1px 2px rgba(13,18,32,.04), 0 12px 32px rgba(13,18,32,.07);
--shadow-lg: 0 2px 4px rgba(13,18,32,.05), 0 28px 60px rgba(13,18,32,.13);
}
html { color-scheme: light; scroll-behavior: smooth; }
/* See app.css: an author `display` rule outranks the `hidden` attribute. */
[hidden] { display: none !important; }
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--ink);
font-family: var(--font); font-size: 17px; line-height: 1.65;
-webkit-font-smoothing: antialiased;
}
.wrap { width: 100%; max-width: var(--wrap); margin: 0 auto; padding: 0 24px; }
.wrap-narrow { max-width: 780px; }
a { color: inherit; }
.skip { position: absolute; left: -9999px; background: var(--ink); color: var(--bg); padding: 10px 16px; border-radius: 8px; }
.skip:focus { left: 16px; top: 16px; z-index: 100; }
/* ---------- topbar + nav ---------- */
.topbar { background: var(--bg-3); border-bottom: 1px solid var(--border); font-size: 14px; color: var(--ink-2); }
.topbar .wrap { display: flex; align-items: center; gap: 10px; height: 40px; }
.topbar-tag {
background: var(--grad); color: var(--brand-ink); font-weight: 700;
font-size: 11.5px; letter-spacing: .06em; text-transform: uppercase;
padding: 3px 9px; border-radius: 999px;
}
.nav {
position: sticky; top: 0; z-index: 50;
background: color-mix(in srgb, var(--bg) 82%, transparent);
backdrop-filter: saturate(180%) blur(14px);
border-bottom: 1px solid var(--border);
}
.nav-inner { display: flex; align-items: center; gap: 16px; height: 74px; }
.brand {
display: flex; align-items: center; gap: 11px;
font-weight: 700; letter-spacing: -.02em; font-size: 17px;
text-decoration: none; flex: none;
}
.mark {
width: 26px; height: 26px; border-radius: 8px; flex: none;
background: var(--grad); box-shadow: 0 4px 12px rgba(88,66,188,.34);
position: relative;
}
/* A folder notch, cut with a pseudo-element so no asset is fetched. */
.mark::after {
content: ""; position: absolute; left: 5px; top: 8px;
width: 16px; height: 3px; border-radius: 2px; background: rgba(255,255,255,.9);
}
.nav-links { display: flex; gap: 26px; margin-left: auto; font-size: 15.5px; }
.nav-links a { text-decoration: none; color: var(--ink-2); font-weight: 550; }
.nav-links a:hover { color: var(--ink); }
.nav-cta { flex: none; display: flex; gap: 14px; align-items: center; margin-left: auto; }
.nav-signin { text-decoration: none; color: var(--ink-2); font-weight: 600; font-size: 15px; white-space: nowrap; }
.nav-signin:hover { color: var(--brand); }
/* ---------- buttons ---------- */
.btn {
display: inline-block; text-decoration: none; font-weight: 650; font-size: 15.5px;
padding: 14px 28px; border-radius: 999px; border: 1px solid transparent;
transition: transform .16s ease, box-shadow .16s ease, background .16s ease;
cursor: pointer;
}
.btn-primary { background: var(--grad); color: var(--brand-ink); box-shadow: 0 8px 22px rgba(88,66,188,.32); }
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 14px 32px rgba(88,66,188,.42); }
.btn-ghost { border-color: var(--border-2); color: var(--ink); background: var(--panel); }
.btn-ghost:hover { transform: translateY(-2px); box-shadow: var(--shadow); }
.btn-outline { border-color: var(--border-2); color: var(--ink); background: transparent; padding: 10px 20px; font-size: 15px; }
.btn-nav { background: var(--grad); color: var(--brand-ink); padding: 10px 22px; font-size: 15px; box-shadow: 0 6px 16px rgba(88,66,188,.3); }
.btn-nav:hover { transform: translateY(-1px); }
/* ---------- hero ---------- */
.hero { position: relative; overflow: hidden; padding: 104px 0 96px; border-bottom: 1px solid var(--border); }
.hero::before, .hero::after { content: ""; position: absolute; border-radius: 50%; pointer-events: none; }
.hero::before {
width: 47%; height: 132%; top: -16%; right: 0;
border-radius: 44% 0 0 44% / 50% 0 0 50%;
background: var(--grad);
}
.hero::after {
width: 340px; height: 340px; top: 4%; right: 10%;
background: radial-gradient(circle, rgba(255,255,255,.30), transparent 70%);
filter: blur(34px);
}
.hero-inner {
position: relative; z-index: 1;
display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 56px; align-items: center;
}
.hero-copy { max-width: 34em; }
.hero h1 { margin: 0 0 22px; font-size: clamp(38px, 4.6vw, 54px); line-height: 1.14; letter-spacing: -.02em; font-weight: 750; }
.lede { margin: 0 0 32px; font-size: 19.5px; color: var(--ink-2); max-width: 30em; }
.cta-row { display: flex; flex-wrap: wrap; gap: 14px; }
.hero-note { margin: 22px 0 0; font-size: 14px; color: var(--ink-3); }
.hero-chips { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 26px; }
.chip {
display: inline-flex; align-items: center; gap: 8px;
background: var(--panel); border: 1px solid var(--border);
border-radius: 999px; padding: 7px 15px; font-size: 14px; color: var(--ink-2);
}
.chip-ic { display: flex; color: var(--brand); }
.chip-ic svg { width: 14px; height: 14px; }
/* Product art: a labelled file list, the signature image for this product the
way a chat thread is for Messenger. */
.hero-art { display: flex; justify-content: center; }
.window {
width: 100%; max-width: 430px; border-radius: var(--radius-lg);
background: var(--panel); box-shadow: var(--shadow-lg); overflow: hidden;
transform: rotate(-1deg);
}
.window-bar {
display: flex; align-items: center; gap: 8px;
padding: 14px 18px; border-bottom: 1px solid var(--border); background: var(--bg-2);
}
.window-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--border-2); }
.window-label { margin-left: auto; font-family: var(--mono); font-size: 11.5px; color: var(--brand); font-weight: 700; }
.window-body { padding: 10px 8px; }
.frow { display: flex; align-items: center; gap: 12px; padding: 11px 14px; border-radius: 10px; }
.frow + .frow { margin-top: 2px; }
.frow-ic { width: 30px; height: 30px; border-radius: 8px; background: var(--grad-soft); color: var(--brand);
display: flex; align-items: center; justify-content: center; flex: none; }
.frow-ic svg { width: 15px; height: 15px; }
.frow-name { font-size: 14.5px; font-weight: 600; }
.frow-tag { margin-left: auto; font-family: var(--mono); font-size: 11px; color: var(--ink-3); white-space: nowrap; }
/* ---------- proof band ---------- */
.proof-band { background: var(--bg-2); border-bottom: 1px solid var(--border); padding: 40px 0; text-align: center; }
.proof-lead { margin: 0 0 20px; color: var(--ink-2); font-size: 16px; }
.proof { display: flex; flex-wrap: wrap; justify-content: center; gap: 14px 44px; color: var(--ink-3); font-size: 15px; }
.proof strong { color: var(--brand); }
/* ---------- sections ---------- */
.band { padding: 96px 0; }
.band-alt { background: var(--bg-2); }
.band-center { text-align: center; }
.band-center .band-lede { margin-left: auto; margin-right: auto; }
.eyebrow {
display: inline-flex; align-items: center; gap: 8px;
padding: 7px 16px; margin-bottom: 18px;
border-radius: 999px; border: 1px solid var(--border-2);
background: var(--grad-soft); color: var(--brand);
font-size: 13px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase;
}
.eyebrow::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); }
.hl { background: var(--grad); -webkit-background-clip: text; background-clip: text; color: transparent; }
.band h2 { margin: 0 0 18px; font-size: clamp(28px, 3.2vw, 40px); letter-spacing: -.02em; line-height: 1.2; font-weight: 750; }
.band-lede { margin: 0 0 52px; color: var(--ink-2); font-size: 18.5px; max-width: 47em; }
/* ---------- cards ---------- */
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 42px 30px; }
.cards-2 { grid-template-columns: repeat(2, 1fr); }
.card { border-radius: var(--radius-lg); padding: 22px 14px; transition: transform .18s ease; }
.card:hover { transform: translateY(-5px); }
.card h3 { margin: 0 0 10px; font-size: 17.5px; letter-spacing: -.015em; font-weight: 700; }
.card p { margin: 0; color: var(--ink-2); font-size: 15px; line-height: 1.6; }
.card-icon {
display: flex; align-items: center; justify-content: center;
width: 62px; height: 62px; margin: 0 auto 20px;
border-radius: 50%; background: var(--grad); color: #fff;
box-shadow: 0 10px 24px rgba(88,66,188,.28);
}
.card-icon svg { width: 27px; height: 27px; display: block; }
/* ---------- steps ---------- */
.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px; text-align: left; }
.step { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 30px 26px; }
.step-n {
display: flex; align-items: center; justify-content: center;
width: 34px; height: 34px; border-radius: 50%; margin-bottom: 16px;
background: var(--grad); color: var(--brand-ink); font-weight: 750; font-size: 15px;
}
.step h3 { margin: 0 0 8px; font-size: 17px; font-weight: 700; }
.step p { margin: 0; color: var(--ink-2); font-size: 15px; }
/* ---------- honest ---------- */
/* The limitations section. Same visual weight as the features above it, on
purpose: a product that hides its edges in smaller type is doing something
other than being honest. */
.honest { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; text-align: left; }
.honest-card {
background: var(--panel); border: 1px solid var(--border);
border-left: 3px solid var(--accent);
border-radius: var(--radius); padding: 28px 26px;
}
.honest-card h3 { margin: 0 0 10px; font-size: 16.5px; font-weight: 700; line-height: 1.35; }
.honest-card p { margin: 0 0 14px; color: var(--ink-2); font-size: 15px; }
.card-link { font-size: 14.5px; font-weight: 650; color: var(--brand); text-decoration: none; }
.card-link:hover { text-decoration: underline; }
/* ---------- split + code ---------- */
.split { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 56px; align-items: center; }
.code {
background: #171a24; color: #e6e8ef; border-radius: var(--radius);
padding: 22px 24px; font-family: var(--mono); font-size: 13.5px; line-height: 1.75;
overflow-x: auto; box-shadow: var(--shadow-lg);
}
.code .c { color: #7f8aa3; }
.code .k { color: #c3b0ff; }
.fineprint { color: var(--ink-3); font-size: 14.5px; max-width: 47em; }
/* ---------- footer ---------- */
.footer { background: var(--bg-2); border-top: 1px solid var(--border); padding: 76px 0 40px; }
.footer-cta { text-align: center; padding-bottom: 60px; border-bottom: 1px solid var(--border); }
.footer-cta h2 { margin: 0 0 12px; font-size: clamp(26px, 3vw, 36px); letter-spacing: -.02em; font-weight: 750; }
.footer-cta p { margin: 0 0 26px; color: var(--ink-2); }
.footer-cta-row { justify-content: center; }
.footer-cols { display: grid; grid-template-columns: 1.4fr repeat(3, 1fr); gap: 34px; padding: 48px 0 36px; }
.footer-brand { display: flex; align-items: center; gap: 11px; font-weight: 700; letter-spacing: -.02em; }
.footer-col h4 { margin: 0 0 14px; font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-3); }
.footer-col a { display: block; text-decoration: none; color: var(--ink-2); font-size: 15px; margin-bottom: 9px; }
.footer-col a:hover { color: var(--brand); }
.footer-legal { border-top: 1px solid var(--border); padding-top: 26px; color: var(--ink-3); font-size: 14px; display: flex; flex-wrap: wrap; gap: 8px 20px; }
.footer-legal a { color: var(--brand); font-weight: 650; text-decoration: none; }
.footer-legal a:hover { text-decoration: underline; }
.heart { color: #e0245e; }
/* ---------- responsive ---------- */
@media (max-width: 980px) {
.hero { padding: 68px 0 72px; }
.hero::before { display: none; }
.hero-inner, .split { grid-template-columns: 1fr; gap: 44px; }
.cards, .cards-2, .steps, .honest { grid-template-columns: 1fr 1fr; }
.footer-cols { grid-template-columns: 1fr 1fr; }
/* Wrap the nav onto a second row rather than hiding it. A hamburger would
need JavaScript to open, and these links are the whole site. */
.nav-inner { height: auto; padding: 12px 0; flex-wrap: wrap; row-gap: 10px; }
.nav-links { order: 3; width: 100%; margin-left: 0; gap: 20px; font-size: 14.5px; }
.band { padding: 68px 0; }
}
@media (max-width: 620px) {
body { font-size: 16px; }
.cards, .cards-2, .steps, .honest, .footer-cols { grid-template-columns: 1fr; }
.btn { padding: 12px 22px; }
.topbar .wrap { font-size: 13px; }
.nav-links { gap: 14px; font-size: 14px; flex-wrap: wrap; row-gap: 6px; }
.hero h1 { font-size: 34px; }
.lede { font-size: 17.5px; }
}
/* ---------- comparison ---------- */
/* Wide by nature, so it scrolls inside its own box rather than making the page
scroll sideways. */
.cmp-scroll { overflow-x: auto; margin: 0 0 18px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--panel); }
.cmp { border-collapse: collapse; width: 100%; min-width: 760px; font-size: 15px; text-align: left; }
.cmp th, .cmp td { padding: 16px 18px; border-bottom: 1px solid var(--border); vertical-align: top; }
.cmp thead th { background: var(--bg-2); font-size: 14px; font-weight: 700; letter-spacing: -.01em; white-space: nowrap; }
.cmp thead th:first-child { width: 26%; }
.cmp tbody th { font-weight: 650; color: var(--ink); font-size: 14.5px; }
.cmp td { color: var(--ink-2); font-size: 14.5px; line-height: 1.55; }
.cmp tr:last-child th, .cmp tr:last-child td { border-bottom: 0; }
/* Our own column is tinted, but the cells still say what they say. */
.cmp .own { background: var(--grad-soft); }
.cmp thead .own { background: linear-gradient(115deg, rgba(88,66,188,.16), rgba(123,99,232,.13)); color: var(--brand); }
.yes { color: #1a7f4b; font-weight: 650; }
.no { color: #9aa0aa; }
.part { color: #a4740a; font-weight: 600; }
.cmp-note { color: var(--ink-3); font-size: 13.5px; }
/* ---------- donate ---------- */
.donate { border: 1px solid var(--border); border-radius: var(--radius);
padding: 26px 24px; background: var(--panel); box-shadow: var(--shadow); }
.donate fieldset { border: 0; padding: 0; margin: 0 0 22px; }
.donate legend { font-size: 13px; font-weight: 700; letter-spacing: .06em;
text-transform: uppercase; color: var(--ink-3); margin-bottom: 12px; padding: 0; }
.donate-freq { display: block; }
.donate-freq label { margin-right: 22px; font-size: 15px; }
.donate-amounts { display: flex; flex-wrap: wrap; gap: 10px; }
.donate-amounts label {
border: 1px solid var(--border-2); border-radius: 999px; padding: 10px 18px;
font-size: 15px; font-weight: 600; cursor: pointer; display: inline-flex;
align-items: center; gap: 8px; background: var(--bg);
}
.donate-amounts label:has(input:checked) {
border-color: var(--brand); background: var(--grad-soft); color: var(--brand);
}
.donate input[type=radio] { accent-color: var(--brand); }
.donate-custom input[type=number] { width: 5.5em; font: inherit; font-size: 15px;
border: 0; border-bottom: 1px solid var(--border-2); background: transparent;
padding: 2px 4px; color: inherit; }
.donate-custom input[type=number]:focus { outline: none; border-bottom-color: var(--brand); }
.thanks { border: 1px solid var(--border); border-left: 3px solid var(--brand);
border-radius: var(--radius); padding: 20px 22px; margin-bottom: 26px;
background: var(--panel); }
.thanks p { margin: 6px 0 0; color: var(--ink-2); font-size: 15px; }
.donate-error { border: 1px solid var(--border-2); border-left: 3px solid var(--accent);
border-radius: var(--radius); padding: 16px 20px; margin-bottom: 24px;
color: var(--ink-2); font-size: 15px; background: var(--bg-2); }
.source-list { list-style: none; margin: 0 0 30px; padding: 0; }
.source-list li { padding: 16px 0; border-top: 1px solid var(--border); color: var(--ink-2); font-size: 15.5px; }
.source-list li:last-child { border-bottom: 1px solid var(--border); }
.source-list a { color: var(--brand); font-weight: 650; text-decoration: none; }
.source-list a:hover { text-decoration: underline; }
.source-list code { font-family: var(--mono); font-size: .92em; }
+42 -121
View File
@@ -1,134 +1,55 @@
# Roadmap
# The Flamenet account service
Open items, with their real blockers rather than optimistic ones.
One Flamenet handle and passphrase, checked here, so a relay never sees either.
## 1. FlameNet account service
A relay can keep its own accounts and most do. This service exists for the
other case: one credential that works across relays, verified by a signed token
that any relay can check and none can mint.
One credential across FlameNet products. The cryptographic half is already
built: `deriveIdentityKEK` stretches the passphrase once and then derives a
**separate key per product** under a distinct context string, so a compromise of
the Messenger identity key yields nothing about the Files identity key. Shared
login does not mean shared key material.
It stores an opaque id, a handle, the parameters a client needs to stretch a
passphrase, and a verifier to compare against. There is no email column.
What remains is entirely a **metadata** question: who learns that the same human
uses two products.
## What it is not
### Proposal: share across the E2E products, keep flamenet.io out
This repository was a file service, Flamenet Files, with the account service
beside it. Files was folded into the messenger on 2026-09-21 and the file
server, its web client, its tenant schemas and its documentation were removed.
Anything you remember here about blobs, tenants, labels or classification is
gone with it. `ARCHITECTURE.md` describes what is left.
| Tier | Products | Account service |
|---|---|---|
| A | Messenger, Files | shared |
| B | flamenet.io | separate |
## Running it
Three reasons the line sits there:
```bash
docker compose up -d
```
1. **flamenet.io is WordPress, and WordPress remembers everything** — IPs, user
agents, login times, post history, plugin logs. That install was compromised
in July 2026 and the vector was never identified. Putting it in the
authentication path for a zero-knowledge product means a WordPress compromise
becomes a Files compromise.
2. **The two have opposite metadata shapes.** flamenet.io is social: forum
posts, buddy lists, presence — a semi-public identity. Files is private
storage. Messenger and Files are both minimal-metadata by construction, so
they belong together; the social site does not.
3. **The linkage is the leak, not the account row.** "This forum handle also
stores 40GB" is exactly the inference worth preventing, and it is created by
the shared account itself, not by anything either product stores.
`docker-compose.yml` brings up Postgres, runs the migrations, and starts the
service on port 8100. It needs `ENCLAVE_JWT_SECRET` and
`ENCLAVE_ACCOUNTS_SECRET`, both at least 32 characters, and a
`POSTGRES_PASSWORD`. `SELF-HOSTING.md` covers a real deployment;
`deploy/RUNBOOK-accounts.md` covers the one we run.
### Minimising linkage inside tier A
## The routes
- The account service stores an opaque account id, an authentication verifier,
per-product public keys, and a creation timestamp. Nothing else. Every
additional field is a field that exists in a breach, a log, and a subpoena.
- **Product-scoped pseudonyms.** Each product server sees only
`HKDF(account_id, "<product>")`. The Files server never learns the Messenger
identifier and cannot correlate its users with Messenger's. The account
service can, which is precisely why it should hold as little as possible.
- Tokens carry the product-scoped pseudonym and the clearance. Never the account
id, never a flamenet.io handle.
- An **opt-in, one-way link** to flamenet.io remains available: stored on the
WordPress side only, user-initiated, revocable. flamenet.io may learn that an
account has Files; Files never learns the flamenet.io handle.
| | |
|---|---|
| `POST /accounts` | Register. Takes a derived secret, never a passphrase. |
| `GET /accounts/:handle/params` | The stretch parameters. Answers for handles that do not exist, on purpose. |
| `POST /accounts/passphrase` | Change a passphrase. |
| `POST /accounts/rotate` | Re-establish access with a recovery code. |
| `POST /accounts/delete` | Delete an account and everything keyed to it. |
| `POST /sessions` | Sign in. Returns the signed token a relay verifies. |
| `GET /.well-known/jwks.json` | The public half, so a relay can verify without being able to mint. |
| `GET` / `POST /identity` | Read or enrol a per-product identity record. Enrolment is optional and nothing currently uses it. |
| `POST /identity/rekey` | Re-wrap an identity record under a new passphrase. |
| `GET /identity/principals/:pseudonym` | Somebody's public key, by their product pseudonym. |
| `POST /clearance/check` | Ask whether a pseudonym holds a clearance. |
Undecided, and the owner's call: whether email is stored at all. Omitting it
maximises privacy and makes account recovery close to impossible.
Every route that takes a passphrase answers in constant time and gives an
unknown handle and a wrong passphrase the same reply, so none of them can be
used to find out who has an account.
## 2. iOS and Android apps
## Testing
The native clients are not a convenience — they are what makes the strongest
claim honest. A web page fetches its JavaScript from the server on every load,
so a compromised host can serve key-capturing code; a signed, pinned binary
cannot be swapped that way. Until a native client ships, the accurate phrasing
stays "encrypted in your browser before upload".
[docs/SPEC.md](docs/SPEC.md) exists for this: byte layouts are normative so
CryptoKit and Android implementations interoperate with the JS reference. Add an
interop test in both directions, as flamenet-e2e does.
⚠️ Blockers already known from the Messenger app, which never shipped: no
signing team, a beta Xcode living in iCloud, and an unset export-compliance key.
Those are release-channel problems, not code problems, and they will recur here.
## 3. Run Messenger and Files together, self-hosted
Compose profiles (`docker compose --profile messenger up`) are the mechanism,
and they are cheap.
⚠️ The blocker is that **there is no standalone Messenger service to compose
in**. It exists as a WordPress plugin, and the relay that would back a
standalone deployment is not deployed. Scaffolding a profile now would produce
something that cannot start. This should follow the account service (item 1),
which is the piece both products actually need to share.
## 4. Client crypto — remaining
Built and tested in three languages against one set of published vectors: key
hierarchy, identity protection, per-product derivation, name digests and
encryption, chunked content AEAD with truncation and reorder resistance,
recovery codes, and share links with an optional password as a third factor.
The vectors run in JavaScript, Swift and Kotlin — and on an Android device as
well as on the JVM, because Android's security provider is not the JDK's and a
JVM-only suite cannot see the difference. It could not: the obvious X25519
implementation passed every JVM test and threw on the first tap on a phone.
Recovery uses Crockford base32 rather than a word list. A twelve-word phrase is
friendlier to transcribe and BIP-39 is the obvious source, but vendoring 2048
byte-exact words is a supply-chain decision to make deliberately rather than
improvise — a single wrong entry silently produces codes that cannot be decoded.
`encode`/`decode` are the only place the alphabet appears, so a word-list codec
drops in beside them when that call is made.
Not built:
- **Key rotation on clearance revocation.** Revoking a compartment should rotate
the label key and re-encrypt; today a revoked holder keeps the old key and
prior content stays readable to them.
- **Post-quantum wrapping.** Identity keys are long-lived, so harvest-now-
decrypt-later applies. A hybrid ML-KEM-768 variant takes a new version byte.
No PQ claim until every client has it.
- **Argon2id.** PBKDF2 ships because it is dependency-free; Argon2id resists GPU
attack materially better and needs a WASM bundle. The KDF id is versioned and
recorded per account so it can arrive as id 2.
## 5. Server — remaining
Built since this list was written: blob upload and download against a local
store, token minting and clearance administration in the account service, tenant
provisioning, share links, label vocabulary editing, and handing a label key to
another cleared principal.
Still remaining:
- **Object storage.** Blobs live on a local volume. Backblaze B2 behind the same
`BlobStore` interface is the intended next step, and it needs a
bucket-scoped key rather than the existing one.
- **Regrade endpoints.** The table and its two-person constraints exist; the
routes do not. Reclassifying a file is the operation most likely to be got
wrong under pressure, which is exactly why it has a two-person rule and why
it should not be done in psql.
- **Key rotation, and therefore revocation.** Giving somebody an area cannot be
undone: the grant row can go, the key they already hold cannot. Real
revocation means re-keying the label and re-wrapping everything under it.
- **Tier assignment.** FlameNet's standing rule is that every feature is
tier-assigned, enforced in code, and shown on the plan page.
`TESTING.md`. The short version is `swift test` for the fast suites and
`./scripts/test-account-delete.sh` for the ones that need a real Postgres.
+6 -180
View File
@@ -1,12 +1,15 @@
# Roadmap
The Flamenet account service. Flamenet Files was folded into the messenger on
2026-09-21 and its items are gone from this list.
Open items, with their real blockers rather than optimistic ones.
## 1. FlameNet account service — built
Runs as its own binary in its own container, with its own database role granted
nothing outside `enclave_accounts`. It cannot read a single file row, and a
tenant role cannot read an account. The signed token is the entire interface.
a relay cannot read an account. The signed token is the entire interface.
- **Passphrase never reaches it.** The client derives an authentication secret
under `flamenet/files/auth/v1`, a different context from the encryption key,
@@ -76,58 +79,6 @@ Three reasons the line sits there:
Undecided, and the owner's call: whether email is stored at all. Omitting it
maximises privacy and makes account recovery close to impossible.
## 2. iOS and Android apps — built, and open source
**All of it is open source**, apps included:
[flamenet-files-ios](https://gitlab.com/paulhitt/flamenet-files-ios) and
[flamenet-files-android](https://gitlab.com/paulhitt/flamenet-files-android),
both MIT. The earlier plan was to open the engines and keep the app shells
closed; that was reversed once there was something worth reading.
Each repository carries the engine, a wire client, and a command-line tool that
runs a full round trip against a real server — which is how the cryptography
gets exercised without an emulator, and therefore how it gets exercised at all.
[docs/SPEC.md](docs/SPEC.md) stays normative and `client/src/` stays the
reference implementation, because three implementations that agree by accident
are three implementations that will eventually disagree.
The native clients are not a convenience — they are what makes the strongest
claim honest. A web page fetches its JavaScript from the server on every load,
so a compromised host can serve key-capturing code; a signed, pinned binary
cannot be swapped that way. Until a native client ships, the accurate phrasing
stays "encrypted in your browser before upload".
Interop is tested rather than assumed. The published vectors run in all three
languages, and one engine's upload has been downloaded byte-for-byte by another
against the same account.
⚠️ **Android needs API 33.** That is where the platform exposes X25519. Below it
a provider such as BouncyCastle has to be registered at startup and nothing does
that yet, so claiming a lower floor would be claiming something untrue.
⚠️ **A JVM test suite cannot validate Android crypto.** Android's provider is
Conscrypt and it disagrees with the JDK's: the obvious X25519 implementation
passed 21 JVM tests and threw on the first tap on a phone. Both engines now
speak DER, and the vectors run on-device as well.
⚠️ **iOS has no release channel.** No signing team, a beta Xcode living in
iCloud, and an unset export-compliance key — the same blockers that kept the
Messenger app from shipping. They are release problems, not code problems, and
they need an Apple Developer Program membership to clear. Android has no
equivalent blocker: a signed APK sideloads today.
## 3. Run Messenger and Files together, self-hosted
Compose profiles (`docker compose --profile messenger up`) are the mechanism,
and they are cheap.
⚠️ The blocker is that **there is no standalone Messenger service to compose
in**. It exists as a WordPress plugin, and the relay that would back a
standalone deployment is not deployed. Scaffolding a profile now would produce
something that cannot start. This should follow the account service (item 1),
which is the piece both products actually need to share.
## 4. Client crypto — remaining
Built and tested in three languages, against one set of published vectors: key
@@ -152,37 +103,6 @@ Not built:
attack materially better and needs a WASM bundle. The KDF id is versioned and
recorded per account so it can arrive as id 2.
## 5. Administration belongs in the interface, not in psql
A fair criticism of how this has been built: several things work only because
someone ran a command or a SQL statement. That is not a design, it is an
unfinished feature with a workaround attached.
**Missing outright, and should not be:**
- **Naming levels and compartments.** `EnclaveServer label` is the only way to
turn "classification 3" into "Restricted". There is no reason this is a CLI
command rather than a settings screen — it is tenant vocabulary, not a
privileged operation, and the endpoint to read it already exists.
- **Creating and retiring compartments.** Same.
- **Viewing and revoking your own share links.** The API supports listing and
revoking per node; the interface only ever shows the link it just made.
- **Seeing who holds an area.** Grants are recorded now, and either party to one
can read it, but nothing displays them. Somebody who has given an area away
should be able to see that they did — especially since it cannot be undone.
**Missing, but needs something first:**
- **Granting clearance.** `EnclaveAccounts grant` is deliberately a command,
because there is no administrator concept in the product at all — no role, no
audit of who granted what, no second pair of eyes. An admin screen without
those would be worse than the CLI, not better. The order is: admin role, then
audit, then the screen.
- **Provisioning a tenant.** Currently a migration run by hand.
The pattern to avoid repeating: when a feature needs data that only exists in
the database, build the way to put it there at the same time.
## 6. Anyone can create accounts in bulk
Registration is throttled, but not in a way that stops this. The limiter counts
@@ -206,13 +126,13 @@ What would actually help, roughly in order of how much:
- **A cost to registering** — a proof-of-work challenge, or invite codes if the
deployment is not meant to be open. Note that email verification, item 7, is
*not* this: a throwaway address costs an attacker nothing.
- **A per-tenant cap** on accounts without a clearance, since an account nobody
- **A cap** on accounts without a clearance, since an account nobody
has cleared can do nothing anyway.
### Half-created accounts — fixed
An account used to exist the moment registration succeeded, while its identity
was created separately, on the file server, at first use. A client that failed
was created separately, by the product server, at first use. A client that failed
between the two left an account with no identity — and if a recovery code had
been registered in that first step, that code was shown to nobody and could not
be reissued.
@@ -235,75 +155,6 @@ Two follow-ups remain, both smaller:
reporting them before deleting, because an automated delete that is wrong
about what "abandoned" means destroys real accounts.
### Tenant schemas have no upgrade path — fixed
`002_tenant_template.sql` runs once per tenant and never again, so a feature
that adds a table — share links did — reaches new deployments and no existing
one. A local database predating share links simply had no `shares` table, and
the failure surfaced as a 500 rather than as anything about migrations.
Self-hosters upgrading hit this, not just us.
Numbered scripts under `SQL/tenant/` are now each registered as their own
migration, so Fluent's own ledger decides what has run and there is no second
bookkeeping table to drift. The template stays frozen as the baseline;
incremental changes live only in the scripts, so a fresh tenant reaches the same
state an upgraded one does by the same route. Scripts must be idempotent.
### Nobody can share a label key — done
Two people cleared for the same label still cannot read each other's files.
`ensureLabelKey` mints a fresh random key per principal when none has been
granted, so every account is an island: the rows are visible, the names are not,
and the interface says "encrypted for another key".
The cryptography was already there. What was missing was anything that issued
the grant, and the reason it stayed missing was that the file server cannot see
clearances — a tenant role has no grant on the account schema, deliberately.
It is now split across the two places that can each see half of it:
- **The database** enforces what it can see. A second insert policy permits a row
for another principal only when the granter already holds a key at exactly
that label, and the row's label equals the session label. Nobody mints a key
for a label they cannot themselves assert.
- **The account service** enforces what only the control plane knows: that the
recipient is cleared. The file server asks, forwarding the caller's own token,
and refuses on anything but a clean answer.
That second endpoint is shaped to avoid being a membership oracle. It takes a
*handle* rather than an id, and answers with a pseudonym only when the account
exists, is enrolled, and is cleared — every other case is the same 404. A caller
learns nothing they would not learn by attempting the grant.
Worth being precise about what the clearance check is worth, because it is the
weaker half. A label key alone opens nothing: every row at that label stays
hidden by row-level security from a session whose token lacks the clearance. A
grant that slipped past would hand somebody ciphertext they can unwrap and a
server that will never serve it to them. Defence in depth, not the load-bearing
control.
Grants are recorded in `grant_audit`, readable by either party and by neither
anyone else — who holds a compartment is exactly what the read policy on
`label_key_grants` refuses to disclose, and the audit table must not become the
way around it.
**One consequence worth knowing.** Switching to an area no longer mints a key;
the first *write* does. Minting on arrival meant two people cleared for the same
label each self-granted a different key the moment they looked at it, so the
later gift always collided with the key the recipient had already made — sharing
would have failed almost every time in real use. The remaining collision is
real: if both people have already filed something at a label independently,
neither can be given the other's key without orphaning what they wrote, and the
server refuses with that explanation rather than silently choosing a loser.
Generations exist in the schema for this and are not yet used.
**Still open:** there is no revocation. Removing a grant row stops the key being
handed out again; it does not unlearn a key somebody already holds, and the
honest fix is re-keying the label and re-wrapping everything under it. Until
that exists, granting is one-way — which the interface says plainly rather than
implying otherwise with a delete button.
## 7. Email verification — decide the tradeoff first
Requested, and worth pausing on: **the account service deliberately stores no
@@ -329,28 +180,3 @@ If it goes in, worth doing properly:
Mail goes through the existing self-hosted Hitt Hosting mail server — no ESP.
Note that local SMTP auth fails in development, so `email_sent: false` there is
expected rather than a bug.
## 8. Object storage — Backblaze B2
Blobs are local files today, behind `BlobStore`, which is two methods. B2 speaks
the S3 API, so this is an S3 backend selected by configuration rather than a
rewrite.
Two things to get right:
- **Scope the key hard.** The existing B2 application key has `deleteFiles` and
`bypassGovernance`, which is far more than a file server needs. Issue a
bucket-scoped key without them.
- **Blobs are ciphertext, but the bucket is still metadata.** Object count,
sizes and timestamps are visible to anyone with read access to the bucket.
Object keys are already random and carry no label.
## 9. Server — remaining
- Blob storage backend. The `blobs` table exists; no upload path or object store
is wired.
- Control plane: token minting, tenant provisioning, clearance administration.
- Regrade endpoints. The table and its two-person constraints exist; the routes
do not.
- Tier assignment. FlameNet's standing rule is that every feature is
tier-assigned, enforced in code, and shown on the plan page.
-246
View File
@@ -1,246 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#(title)</title>
<meta name="robots" content="noindex">
<link rel="stylesheet" href="/landing.css">
<link rel="stylesheet" href="/app.css">
<meta name="enclave-accounts" content="#(accountsURL)">
</head>
<body>
<nav class="app-nav">
<div class="wrap">
<a class="brand" href="#(siteURL)">
<span class="mark" aria-hidden="true"></span>
<span>Flamenet&nbsp;Files</span>
</a>
<a class="nav-signin" id="app-signin-link" href="/app" hidden>Sign in</a>
<div class="nav-right" id="session-bar" hidden>
<button class="label-chip" id="label-chip" aria-expanded="false" aria-controls="label-picker">
<span class="chip-dot" aria-hidden="true"></span>
<span id="label-chip-text">…</span>
<span class="chip-caret" aria-hidden="true">▾</span>
</button>
<span class="who" id="who"></span>
<button class="linkish" id="sign-out">Sign out</button>
</div>
</div>
</nav>
<div class="banner" id="banner" hidden>
<div class="wrap"><span id="banner-text"></span></div>
</div>
<main class="app-main">
<div class="wrap">
<!-- ---------------------------------------------------------- sign in -->
<div class="panel shared-notice" id="shared-notice" hidden>
<strong>Someone shared a file with you</strong>
<p>Sign in to open it. You'll need to be cleared for its sensitivity — the
link on its own is not enough, by design.</p>
</div>
<section id="signin" class="panel signin">
<h2 id="signin-title">Welcome back</h2>
<p class="sub" id="signin-sub">
Your passphrase never leaves this tab. It builds your keys here, on your device.
</p>
<label class="field">
<span>Handle</span>
<input type="text" id="handle" autocomplete="username" spellcheck="false"
placeholder="the name you signed up with">
</label>
<label class="field" id="passphrase-field">
<span>Passphrase</span>
<input type="password" id="passphrase" autocomplete="current-password">
</label>
<label class="field" id="share-unlock-field" hidden>
<span>Link password</span>
<input type="text" id="share-unlock" autocomplete="off" spellcheck="false"
placeholder="the password you were sent separately">
</label>
<label class="field" id="recovery-field" hidden>
<span>Recovery code</span>
<input type="text" id="recovery-code" autocomplete="off" spellcheck="false"
placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX">
<small>Dashes and capitals are optional &mdash; type it however you wrote it down.</small>
</label>
<label class="field" id="new-passphrase-field" hidden>
<span>New passphrase</span>
<input type="password" id="new-passphrase" autocomplete="new-password">
</label>
<button class="btn btn-primary btn-block" id="signin-button">Unlock</button>
<p class="hint" id="signin-hint"></p>
<div class="switcher">
<button class="linkish" id="register-toggle">Create an account</button>
<span aria-hidden="true">&middot;</span>
<button class="linkish" id="mode-toggle">I've lost my passphrase</button>
</div>
</section>
<!-- ------------------------------------------------------- recovery -->
<section id="recovery-panel" class="panel recovery" hidden>
<h2>Write this down now</h2>
<p class="sub">
This is your recovery code &mdash; the only way back in if you forget your
passphrase. It is not stored anywhere, and this is the only time it will ever
be shown. We cannot send it again.
</p>
<div class="recovery-code" id="recovery-code-out"></div>
<div class="switcher" style="justify-content:flex-start;gap:14px">
<button class="btn btn-primary btn-sm" id="recovery-ack">I've written it down</button>
<button class="linkish" id="recovery-copy">Copy</button>
</div>
</section>
<!-- ------------------------------------------------------ workspace -->
<section id="workspace" hidden>
<div class="picker panel" id="label-picker" hidden>
<h3>What are you working on?</h3>
<p class="sub">
Everything you create is filed here, and you'll only see what this reaches.
</p>
<label class="field">
<span>Sensitivity</span>
<select id="classification"></select>
</label>
<div class="field" id="compartments-field">
<span>Areas</span>
<div id="compartments"></div>
</div>
<div class="switcher" style="justify-content:flex-start;gap:12px">
<button class="btn btn-primary btn-sm" id="apply-label">Switch to this</button>
<button class="linkish" id="cancel-label">Cancel</button>
</div>
</div>
<div class="panel" id="share-area-panel" hidden>
<div class="panel-head">
<h3>Share this area</h3>
<button class="btn btn-ghost btn-sm" id="close-share-area">Close</button>
</div>
<p class="panel-note" id="share-area-note">
Give someone else the key to <strong id="share-area-label">this area</strong>.
They will be able to read everything filed here, now and in future.
</p>
<div class="field-row">
<input id="share-area-handle" type="text" placeholder="their handle"
autocomplete="off" autocapitalize="none" spellcheck="false">
<button class="btn btn-primary btn-sm" id="share-area-submit">Give them the key</button>
</div>
<p class="fineprint">
They must already be cleared for this area. The key is wrapped to their
public key in this tab &mdash; the server stores something it cannot open,
and never sees the key itself.
</p>
<p class="panel-hint" id="share-area-hint"></p>
</div>
<div class="panel labels-panel" id="labels-panel" hidden>
<div class="preview-head">
<strong>Labels</strong>
<span class="spacer"></span>
<button class="linkish" id="close-labels">Close</button>
</div>
<p class="sub">
What this organisation calls its sensitivity levels and areas. Renaming
one changes how it reads everywhere &mdash; it does not move any file.
</p>
<h3 class="labels-head">Sensitivity levels</h3>
<ul class="labels-list" id="levels-list"></ul>
<div class="labels-add">
<input type="number" id="new-level-ordinal" min="0" max="255" placeholder="#" aria-label="Level number">
<input type="text" id="new-level-name" maxlength="48" placeholder="e.g. Confidential" aria-label="Level name">
<button class="btn btn-ghost btn-sm" id="add-level">Add level</button>
</div>
<h3 class="labels-head">Areas</h3>
<ul class="labels-list" id="compartments-list"></ul>
<div class="labels-add">
<input type="number" id="new-compartment-bit" min="0" max="63" placeholder="#" aria-label="Area number">
<input type="text" id="new-compartment-name" maxlength="48" placeholder="e.g. Finance" aria-label="Area name">
<button class="btn btn-ghost btn-sm" id="add-compartment">Add area</button>
</div>
</div>
<div class="crumbs-row">
<nav id="breadcrumb" aria-label="Location"></nav>
<div class="actions">
<button class="btn btn-ghost btn-sm" id="labels-button" hidden>Labels</button>
<button class="btn btn-ghost btn-sm" id="share-area-button">Share this area</button>
<button class="btn btn-ghost btn-sm" id="new-folder-button">New folder</button>
<input type="file" id="upload" multiple hidden>
<button class="btn btn-primary btn-sm" id="upload-button">Upload</button>
</div>
</div>
<div id="dropzone" class="dropzone">
<ul id="listing"></ul>
<div class="drop-hint" id="drop-hint">Drop files to encrypt and upload</div>
</div>
<div id="share-panel" class="panel share" hidden>
<div class="preview-head">
<strong id="share-title">Share link</strong>
<span class="spacer"></span>
<button class="linkish" id="close-share">Close</button>
</div>
<p class="sub" id="share-note"></p>
<label class="field" id="share-password-field">
<span>Password (optional) &mdash; tell the recipient separately, not in the same message</span>
<input type="text" id="share-password" autocomplete="off" spellcheck="false"
placeholder="leave blank for no password">
<small>A password is a third lock. The link and being cleared are still both required.</small>
</label>
<div class="share-link" id="share-link" hidden></div>
<!--
Links already made for this file. The interface used to show only the
one it had just created, which meant a link you made last week was
unrevokable from here — the API could list and revoke it, nothing
asked.
-->
<div id="share-existing" hidden>
<p class="labels-head">Links already made for this file</p>
<ul class="share-list" id="share-list"></ul>
</div>
<div class="switcher" style="justify-content:flex-start;gap:14px">
<button class="btn btn-primary btn-sm" id="share-create">Create link</button>
<button class="btn btn-ghost btn-sm" id="share-copy" hidden>Copy link</button>
<button class="linkish" id="share-revoke" hidden>Revoke</button>
</div>
</div>
<div id="preview-panel" class="panel" hidden>
<div class="preview-head">
<strong id="preview-name">Decrypted in this tab</strong>
<span class="spacer"></span>
<button class="btn btn-ghost btn-sm" id="preview-save">Save to my computer</button>
<button class="linkish" id="close-preview">Close</button>
</div>
<pre id="preview"></pre>
</div>
</section>
</div>
</main>
<div class="toast" id="toast" hidden><span id="toast-text"></span></div>
<script type="module" src="/js/app.js"></script>
</body>
</html>
-153
View File
@@ -1,153 +0,0 @@
#extend("layout"):
#export("content"):
<section class="band">
<div class="wrap">
<span class="eyebrow">Comparison</span>
<h2>How it compares to what you're <span class="hl">probably using</span>.</h2>
<p class="band-lede">
Proton Drive, Google Drive and iCloud Drive are all good products with far more
behind them than we have. This page is about where the designs actually differ,
including the several rows where we come off worse.
</p>
<div class="cmp-scroll">
<table class="cmp">
<thead>
<tr>
<th scope="col">&nbsp;</th>
<th scope="col" class="own">Flamenet Files</th>
<th scope="col">Proton Drive</th>
<th scope="col">Google Drive</th>
<th scope="col">iCloud Drive</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Provider can read your files</th>
<td class="own"><span class="yes">No</span> &mdash; encrypted in your browser</td>
<td><span class="yes">No</span> &mdash; end-to-end encrypted</td>
<td><span class="no">Yes by default.</span> Client-side encryption exists on some Workspace plans, with keys you hold elsewhere</td>
<td><span class="part">Depends.</span> Only if you turn on Advanced Data Protection; otherwise Apple holds a key</td>
</tr>
<tr>
<th scope="row">Filenames hidden from the provider</th>
<td class="own"><span class="yes">Yes</span></td>
<td><span class="yes">Yes</span></td>
<td><span class="no">No</span></td>
<td><span class="no">No</span> &mdash; filenames stay readable even with Advanced Data Protection on</td>
</tr>
<tr>
<th scope="row">Built-in sensitivity levels, enforced by the encryption</th>
<td class="own"><span class="yes">Yes.</span> The reason this exists</td>
<td><span class="no">No</span></td>
<td><span class="part">Labels and policy rules on business plans,</span> enforced by the service rather than by keys</td>
<td><span class="no">No</span></td>
</tr>
<tr>
<th scope="row">Need-to-know separate from seniority</th>
<td class="own"><span class="yes">Yes.</span> A top-level clearance still won't open a project you weren't brought into</td>
<td><span class="no">No</span></td>
<td><span class="no">No</span></td>
<td><span class="no">No</span></td>
</tr>
<tr>
<th scope="row">Run it on your own server</th>
<td class="own"><span class="yes">Yes.</span> Two containers</td>
<td><span class="no">No</span></td>
<td><span class="no">No</span></td>
<td><span class="no">No</span></td>
</tr>
<tr>
<th scope="row">Source you can read</th>
<td class="own"><span class="yes">All of it,</span> MIT &mdash; server, web, and both apps</td>
<td><span class="yes">Apps are open source</span></td>
<td><span class="no">No</span></td>
<td><span class="no">No</span></td>
</tr>
<tr>
<th scope="row">Phone and desktop apps</th>
<td class="own"><span class="no">None yet.</span> Browser only</td>
<td><span class="yes">Yes</span></td>
<td><span class="yes">Yes</span></td>
<td><span class="yes">Yes, built into the OS</span></td>
</tr>
<tr>
<th scope="row">Independent security audit</th>
<td class="own"><span class="no">Not yet</span></td>
<td><span class="yes">Published audits</span></td>
<td><span class="part">Compliance certifications</span> &mdash; a different kind of assurance</td>
<td><span class="part">Compliance certifications</span> &mdash; a different kind of assurance</td>
</tr>
<tr>
<th scope="row">Sharing with other people</th>
<td class="own"><span class="no">Not yet.</span> Single-account use today</td>
<td><span class="yes">Yes,</span> including links</td>
<td><span class="yes">Yes,</span> extensively</td>
<td><span class="yes">Yes</span></td>
</tr>
<tr>
<th scope="row">If you forget your password</th>
<td class="own">A one-time recovery code. Lose both and the files are gone</td>
<td>Recovery phrase or file. Lose both and the files are gone</td>
<td><span class="yes">Account recovery works</span> &mdash; because Google holds a key</td>
<td><span class="yes">Account recovery works,</span> unless Advanced Data Protection is on</td>
</tr>
<tr>
<th scope="row">Maturity</th>
<td class="own"><span class="no">Early.</span> Not released, and not somewhere to put anything you cannot lose</td>
<td><span class="yes">Mature,</span> years in production</td>
<td><span class="yes">Mature,</span> enormous scale</td>
<td><span class="yes">Mature,</span> enormous scale</td>
</tr>
</tbody>
</table>
</div>
<p class="cmp-note">
Compiled from the vendors' own published documentation. Their products change often
and ours will too, so check anything here that matters to your decision rather than
taking our word for it. Corrections are welcome at security@extant2000.com.
</p>
</div>
</section>
<section class="band band-alt band-center">
<div class="wrap">
<span class="eyebrow">Straight answers</span>
<h2>When you should pick <span class="hl">something else</span>.</h2>
<p class="band-lede">
A comparison page that concluded "use ours" in every case would not be worth
reading.
</p>
<div class="honest">
<article class="honest-card">
<h3>You want encrypted storage that just works, today</h3>
<p>
Use Proton Drive. It does the encryption part as well as we intend to, it has
been audited, it has apps on every platform, and it is a finished product. We
are not, yet.
</p>
</article>
<article class="honest-card">
<h3>You need to collaborate, or you live in the ecosystem</h3>
<p>
Google Drive and iCloud Drive are built around sharing, real-time editing and
deep OS integration. We deliberately trade all of that away, and the trade is
only worth it if you actually need what it buys.
</p>
</article>
<article class="honest-card">
<h3>Different sensitivities, one place, and it must hold</h3>
<p>
This is the case we are built for: material that shouldn't sit in one
undifferentiated pile, where "who can see this" has to be enforced by the
encryption and not only by a setting. Nobody else on this page does that.
</p>
<a class="card-link" href="/security">How that's enforced</a>
</article>
</div>
</div>
</section>
#endexport
#endextend
-175
View File
@@ -1,175 +0,0 @@
#extend("layout"):
#export("content"):
<section class="band">
<div class="wrap wrap-narrow">
<span class="eyebrow">Donate</span>
<h2>Help fund the <span class="hl">audit</span>.</h2>
#if(thanks):
<div class="thanks">
<strong>Thank you.</strong>
<p>
Your receipt is on its way from Stripe. It genuinely helps &mdash; this is
funded by people who want it to exist, not by anyone who wants your data.
</p>
</div>
#endif
#if(error):
<div class="donate-error">
#if(error == "amount"):
Please enter an amount between $#(minAmount) and $#(maxAmount).
#else:
Donations aren't available right now. Nothing was charged.
#endif
</div>
#endif
<p class="band-lede" style="margin-bottom:26px">
Flamenet Files is free, open source, and yours to self-host. There is nothing
to upsell you and no paid tier holding features back, so if it is going to be
paid for, it is paid for like this.
</p>
<h3>What the money is for</h3>
<p>
Mostly one thing: <strong>an independent security review</strong>. The code is
open and tested, and the design is published, but nobody outside this project
has audited it &mdash; and a product that asks you to trust its encryption
should be able to point at a review it did not write itself. That is the gap
donations close first. After it, hosting and the Apple and Google developer
fees the mobile apps will need.
</p>
<h3>What it isn't</h3>
<p class="fineprint" style="margin-bottom:30px">
This is a donation, not a purchase. There is no reward, no early access, no
equity, and it buys no influence over what gets built. Extant&nbsp;2000&nbsp;LLC
is a company rather than a charity, so it is <strong>not tax-deductible</strong>.
If you would rather give money to something more urgent than a file
encryptor, do that instead &mdash; that is a genuine suggestion.
</p>
#if(enabled):
<form class="donate" id="donate-form">
<fieldset class="donate-freq">
<legend>How often</legend>
<label><input type="radio" name="frequency" value="once" checked> Once</label>
<label><input type="radio" name="frequency" value="monthly"> Every month</label>
</fieldset>
<fieldset class="donate-amounts">
<legend>How much</legend>
<label><input type="radio" name="amount" value="5"> $5</label>
<label><input type="radio" name="amount" value="15" checked> $15</label>
<label><input type="radio" name="amount" value="50"> $50</label>
<label><input type="radio" name="amount" value="150"> $150</label>
<label class="donate-custom">
<input type="radio" name="amount" value="custom">
<span>Other</span>
<input type="number" name="custom_amount" min="#(minAmount)" max="#(maxAmount)"
step="1" placeholder="$" aria-label="Custom amount in dollars">
</label>
</fieldset>
<button class="btn btn-primary" type="submit" id="donate-continue">Continue to payment</button>
<p class="fineprint" style="margin:16px 0 0">
The payment form opens on this page &mdash; you are not sent anywhere else.
Card details go straight to Stripe from your browser and never touch this
server, which is what keeps us out of them.
</p>
<noscript>
<p class="donate-error" style="margin-top:16px">
The payment form needs JavaScript, because that is what keeps the card
fields inside Stripe's own frame rather than in a form this server
could read.
</p>
</noscript>
</form>
<div class="donate-error" id="donate-failed" hidden></div>
<!-- Filled in by Stripe once an amount is chosen. Empty until then: a
session is a real object on their side, and opening one per page view
would create a pile of abandoned ones. -->
<div id="donate-checkout"></div>
<p class="fineprint" id="donate-back" hidden style="margin:18px 0 0">
<a href="/donate">Choose a different amount</a>
</p>
<script src="https://js.stripe.com/v3/"></script>
<script>
(function () {
var form = document.getElementById("donate-form");
var mount = document.getElementById("donate-checkout");
var failed = document.getElementById("donate-failed");
var back = document.getElementById("donate-back");
var button = document.getElementById("donate-continue");
var checkout = null;
function fail(message) {
failed.textContent = message;
failed.hidden = false;
button.disabled = false;
button.textContent = "Continue to payment";
}
form.addEventListener("submit", async function (event) {
event.preventDefault();
failed.hidden = true;
button.disabled = true;
button.textContent = "One moment\u2026";
// Only ever one live session on the page. Submitting twice otherwise
// leaves the first frame mounted underneath the second.
if (checkout) { checkout.destroy(); checkout = null; }
var data = new URLSearchParams(new FormData(form));
var response;
try {
response = await fetch("/donate/session", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: data.toString()
});
} catch (error) {
return fail("Could not reach the server. Nothing was charged.");
}
var body = await response.json().catch(function () { return {}; });
if (!response.ok) {
// Vapor puts the sentence in `reason`, and it is written to be read.
return fail(body.reason || "Could not start a payment. Nothing was charged.");
}
try {
// Scoped to the connected account when there is one. A session opened
// on that account cannot be mounted by a Stripe built without it —
// and the failure is a frame that never appears, not an error anyone
// reads.
var account = "#(stripeAccount)";
var stripe = account
? Stripe("#(publishableKey)", { stripeAccount: account })
: Stripe("#(publishableKey)");
checkout = await stripe.initEmbeddedCheckout({ clientSecret: body.clientSecret });
form.hidden = true;
back.hidden = false;
checkout.mount(mount);
mount.scrollIntoView({ behavior: "smooth", block: "start" });
} catch (error) {
fail("Could not open the payment form. Nothing was charged.");
}
});
})();
</script>
#else:
<div class="donate-error">
Donations aren't configured on this server. If you are self-hosting, set
<code>FN_DONATE_PROVIDER</code>, <code>FN_DONATE_SECRET</code> and
<code>FN_DONATE_PUBLISHABLE_KEY</code>.
</div>
#endif
</div>
</section>
#endexport
#endextend
-254
View File
@@ -1,254 +0,0 @@
#extend("layout"):
#export("content"):
<header class="hero">
<div class="wrap hero-inner">
<div class="hero-copy">
<span class="eyebrow">Private file storage</span>
<h1>Files that only open for the <span class="hl">right people</span>.</h1>
<p class="lede">
Your files are locked in this browser before they upload, so the server keeps
sealed boxes it has no way to open. And every file carries a level, so people
see what they're cleared for and nothing else.
</p>
<div class="cta-row">
<a class="btn btn-primary" href="#(appURL)?new=1">Get started</a>
<a class="btn btn-ghost" href="#("#")how">See how it works</a>
</div>
<div class="hero-chips">
<span class="chip"><span class="chip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg></span>Encrypted in your browser</span>
<span class="chip"><span class="chip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg></span>No filenames on the server</span>
<span class="chip"><span class="chip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg></span>Free and open source</span>
</div>
</div>
<div class="hero-art" aria-hidden="true">
<div class="window">
<div class="window-bar">
<span class="window-dot"></span><span class="window-dot"></span><span class="window-dot"></span>
<span class="window-label">working at &nbsp;confidential // finance</span>
</div>
<div class="window-body">
<div class="frow">
<span class="frow-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg></span>
<span class="frow-name">Board pack</span>
<span class="frow-tag">confidential // finance</span>
</div>
<div class="frow">
<span class="frow-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg></span>
<span class="frow-name">Q3 forecast.xlsx</span>
<span class="frow-tag">confidential // finance</span>
</div>
<div class="frow">
<span class="frow-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg></span>
<span class="frow-name">Handbook.pdf</span>
<span class="frow-tag">internal</span>
</div>
</div>
</div>
</div>
</div>
</header>
<section class="proof-band">
<div class="wrap">
<p class="proof-lead">Free to use, open to read, and <strong>yours to run on your own server</strong></p>
<div class="proof">
<span><strong>Free</strong> forever</span>
<span><strong>No</strong> ads</span>
<span><strong>No</strong> trackers</span>
<span><strong>Open</strong> source</span>
<span><strong>Yours</strong> to host</span>
</div>
</div>
</section>
<section class="band band-center" id="features">
<div class="wrap">
<span class="eyebrow">Features</span>
<h2>What it <span class="hl">does for you</span>.</h2>
<p class="band-lede">
In everyday terms. The parts that deserve a longer explanation are further down,
including the ones that are not to our advantage.
</p>
<div class="cards">
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11V8a7 7 0 0 1 14 0v3"/><rect x="3" y="11" width="18" height="10" rx="2"/><path d="M12 15v2"/></svg></span>
<h3>Locked before it leaves your browser</h3>
<p>
Your file, and even its name, is sealed on your own machine before anything is
sent. What we store is a sealed box, and we hold nothing that opens it.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6h16"/><path d="M4 12h11"/><path d="M4 18h6"/></svg></span>
<h3>Every file has a level</h3>
<p>
Files are filed by sensitivity, from everyday to restricted. You choose the
level you're working at, and you see what that level reaches &mdash; no more.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8 12h8"/><path d="M12 8v8"/></svg></span>
<h3>Seniority isn't the same as need-to-know</h3>
<p>
Being cleared to the highest level does not quietly open a project you were
never brought into. Both have to line up before a file opens.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12s3.5-6 9-6 9 6 9 6-3.5 6-9 6-9-6-9-6z"/><path d="M4 4l16 16"/></svg></span>
<h3>What you can't see, you can't tell is there</h3>
<p>
A file above your level doesn't appear greyed out, and nothing says "access
denied". It looks exactly like a file that was never there &mdash; because the
alternative tells you something.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"/></svg></span>
<h3>Share a link that still checks who you are</h3>
<p>
Send someone a link and it only opens for people cleared for that file.
Forward it to anyone else and they get nothing &mdash; not a login prompt,
nothing. The link is half the key; being cleared is the other half.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 7a5 5 0 1 0-4.9 6H12v3h3v3h4v-4.1"/><circle cx="17.5" cy="6.5" r="1"/></svg></span>
<h3>One recovery code, kept by you</h3>
<p>
You get a code when you sign up. Write it down: it is the only way back in if
the passphrase goes, and it is shown exactly once because we never keep it.
</p>
</article>
<article class="card">
<span class="card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="14" width="18" height="6" rx="2"/><path d="M7 7.5h.01M7 17h.01"/></svg></span>
<h3>Run it on your own hardware</h3>
<p>
Two containers and a config file. No account with us, nothing that phones home,
and the whole thing is open to read before you trust it.
</p>
</article>
</div>
</div>
</section>
<section class="band band-alt band-center" id="how">
<div class="wrap">
<span class="eyebrow">How it works</span>
<h2>Three things to <span class="hl">know</span>.</h2>
<p class="band-lede">
There is no setup wizard and nothing to configure. The whole model is these
three ideas.
</p>
<div class="steps">
<article class="step">
<span class="step-n">1</span>
<h3>Your passphrase makes the keys</h3>
<p>
Keys are built on your device from a passphrase that is never sent anywhere.
You also get a one-time recovery code, because a passphrase alone would make
a bad day permanent.
</p>
</article>
<article class="step">
<span class="step-n">2</span>
<h3>You choose the level you're working at</h3>
<p>
Before you do anything, you say which level you're at. Everything you create is
filed there, and the list only shows what that level reaches.
</p>
</article>
<article class="step">
<span class="step-n">3</span>
<h3>Files are sealed here, filed there</h3>
<p>
Uploading seals the file in your browser first. Downloading unseals it in your
browser too. In between, the server is holding something it cannot read.
</p>
</article>
</div>
</div>
</section>
<section class="band band-center" id="honest">
<div class="wrap">
<span class="eyebrow">Straight answers</span>
<h2>Where the <span class="hl">limits</span> are.</h2>
<p class="band-lede">
Every system like this has edges. Here are ours, in the same size type as
everything else on this page.
</p>
<div class="honest">
<article class="honest-card">
<h3>A web page is only as trustworthy as the server that sent it</h3>
<p>
This page's code arrives from the same host that stores your files, so a host
that had been compromised could send code that quietly copies your keys. That
is true of every website that encrypts in the browser. A signed app you install
once is what removes the assumption, and we don't have one yet.
</p>
<a class="card-link" href="/security">What we can and cannot promise</a>
</article>
<article class="honest-card">
<h3>We can see the shape of your files, not what's in them</h3>
<p>
To hand you the right file, the server has to know how many there are, how big,
when they changed, and what level each one carries. It cannot read a filename
or a byte of content. Both of those things are true at once.
</p>
<a class="card-link" href="/security">Exactly what's stored</a>
</article>
<article class="honest-card">
<h3>Lose both secrets and the files are gone</h3>
<p>
There is no reset link and no back door, which is the same property that keeps
us out. If the passphrase and the recovery code are both lost, nobody &mdash;
including us &mdash; can open your files again.
</p>
<a class="card-link" href="/security">How recovery works</a>
</article>
</div>
<p class="fineprint" style="margin-top:34px">
No outside security audit has happened yet. The code is open and tested and the
design is published, but a paid review by a security firm is a different kind of
assurance, and one we would like to fund.
</p>
</div>
</section>
<section class="band band-alt" id="developers">
<div class="wrap split">
<div>
<span class="eyebrow">Self-hosting</span>
<h2>Your server, your <span class="hl">rules</span>.</h2>
<p class="band-lede" style="margin-bottom:26px">
Postgres and one application container. Nothing reaches out to us, and there is
no account with us to make.
</p>
<div class="cta-row">
<a class="btn btn-primary" href="/self-hosting">Read the guide</a>
<a class="btn btn-ghost" href="/source">Read the code</a>
</div>
</div>
<div class="code">
<span class="c"># fill in three secrets, then:</span><br>
<span class="k">docker</span> compose up --build<br><br>
<span class="c"># the app refuses to start if its database</span><br>
<span class="c"># role could bypass the level checks</span>
</div>
</div>
</section>
#endexport
#endextend
-105
View File
@@ -1,105 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#(title)</title>
<meta name="description" content="#(description)">
<meta property="og:title" content="#(title)">
<meta property="og:description" content="#(description)">
<meta property="og:type" content="website">
<meta property="og:url" content="#(siteURL)#(path)">
<link rel="canonical" href="#(siteURL)#(path)">
<link rel="stylesheet" href="/landing.css">
</head>
<body>
<a class="skip" href="#("#")main">Skip to content</a>
<div class="topbar">
<div class="wrap">
<span class="topbar-tag">Open</span>
<span>Free and open source &mdash;</span>
<a href="#(sourceURL)">read the code</a>
</div>
</div>
<nav class="nav">
<div class="wrap nav-inner">
<a class="brand" href="/">
<span class="mark" aria-hidden="true"></span>
<span>Flamenet&nbsp;Files</span>
</a>
<div class="nav-links" id="nav-links">
<a href="/#("#")features">Features</a>
<a href="/#("#")how">How it works</a>
<a href="/compare">Compare</a>
<a href="/security">Security</a>
<a href="/self-hosting">Self-hosting</a>
</div>
<div class="nav-cta">
<a class="btn btn-outline nav-donate" href="/donate">Donate</a>
<a class="nav-signin" href="#(appURL)">Sign&nbsp;in</a>
<a class="btn btn-nav" href="#(appURL)?new=1">Get&nbsp;started</a>
</div>
</div>
</nav>
<main id="main">
#import("content")
</main>
<footer class="footer">
<div class="wrap">
<div class="footer-cta">
<h2>Run it on your own <span class="hl">server</span>.</h2>
<p>Two containers and a config file. Nothing to sign up for, nothing that phones home.</p>
<div class="cta-row footer-cta-row">
<a class="btn btn-primary" href="/self-hosting">Run your own server</a>
<a class="btn btn-ghost" href="/security">Read the details</a>
</div>
</div>
<div class="footer-cols">
<div class="footer-brand">
<span class="mark" aria-hidden="true"></span>
<span>Flamenet&nbsp;Files</span>
</div>
<nav class="footer-col" aria-label="Product">
<h4>Product</h4>
<a href="#(appURL)">Sign in</a>
<a href="#(appURL)?new=1">Create an account</a>
<a href="/#("#")features">Features</a>
<a href="/#("#")how">How it works</a>
</nav>
<nav class="footer-col" aria-label="Details">
<h4>Details</h4>
<a href="/compare">Compare</a>
<a href="/security">Security</a>
<a href="/self-hosting">Self-hosting</a>
<a href="/source">Source code</a>
<a href="#(sourceURL)">Repository</a>
<a href="/donate">Donate</a>
</nav>
<nav class="footer-col" aria-label="Flamenet">
<h4>Flamenet</h4>
<a href="https://flamenetmessenger.com">Messenger</a>
<a href="https://flamenet.io">flamenet.io</a>
</nav>
</div>
<div class="footer-legal">
<span>&copy; 2026 Extant 2000 LLC</span>
<span>MIT licensed</span>
<span>Files are encrypted in your browser before upload.</span>
<span>Proudly hosted at <a href="https://hitthosting.com">Hitt Hosting</a>,
with <span class="heart" role="img" aria-label="love">&#10084;</span></span>
</div>
</div>
</footer>
</body>
</html>
-87
View File
@@ -1,87 +0,0 @@
#extend("layout"):
#export("content"):
<section class="band">
<div class="wrap wrap-narrow">
<span class="eyebrow">Security</span>
<h2>What this <span class="hl">protects</span>, and what it doesn't.</h2>
<p class="band-lede">
Written to be read before you trust it, not after something goes wrong.
</p>
<h3>What the server can see</h3>
<p>
Filenames and file contents are encrypted on your device. The server holds
ciphertext and, for names, a keyed fingerprint it cannot reverse. It does see
everything it needs to hand you the right file:
</p>
<ul>
<li>How your folders are arranged, and how many files are in them</li>
<li>The size of each file and when it changed</li>
<li>The level and compartments each file carries &mdash; this is what it enforces</li>
<li>Which people hold a key for which level</li>
</ul>
<p class="fineprint">
Someone who could watch that metadata over time could learn something about how
you work, even without reading a single file. We would rather say so than let you
find out later.
</p>
<h3>Two independent walls</h3>
<p>
Levels are enforced twice, by mechanisms that fail differently. The database
refuses to hand over a file your level does not reach. Separately, the key that
opens a file is wrapped to that file's level, so a stolen backup is no more
readable than the live system. A mistake in one does not undo the other.
</p>
<h3>The web app's honest limit</h3>
<p>
This site's code is delivered by the same host that stores your files. A host that
had been compromised, or compelled, could serve a modified page that copies your
keys as you type your passphrase. No amount of encryption inside the page fixes
that, because the page itself is the thing in question.
</p>
<p>
So the claim we make is that <strong>files are encrypted in your browser before
upload</strong> &mdash; not that we <em>could never</em> read them. A signed app,
installed once and updated deliberately, is what would let us say the stronger
thing. There isn't one yet.
</p>
<h3>Recovery, and its price</h3>
<p>
You get a recovery code when you sign up. It wraps the same key your passphrase
does, so either one gets you in, and neither reveals the other. It is shown once
and never stored, so we cannot resend it. Using it sets a new passphrase and issues
a fresh code; the old one stops working.
</p>
<p>
If both are lost, your files stay sealed forever. There is no reset link, because a
reset link would be a way in that we control &mdash; and then we would be able to
read your files, which is the thing we are trying not to be able to do.
</p>
<h3>What is not covered</h3>
<ul>
<li><strong>Your own device.</strong> Keys are made where you type. Malware there defeats all of this.</li>
<li><strong>Withdrawing access.</strong> Removing someone's clearance stops the server serving them new files, but someone who already held a key keeps it until that level's key is rotated and its files re-encrypted.</li>
<li><strong>Traffic analysis</strong> against the metadata listed above.</li>
<li><strong>Availability.</strong> There is no rate limiting or denial-of-service protection yet.</li>
</ul>
<h3>No outside audit yet</h3>
<p>
The code is open, the design is published, and the encryption engine is tested in
both directions against its own specification. A paid review by a security firm is
a different kind of assurance and has not happened.
</p>
<h3>Reporting something</h3>
<p>
Please email <strong>security@extant2000.com</strong> rather than opening a public
issue, if what you have found is exploitable.
</p>
</div>
</section>
#endexport
#endextend
-106
View File
@@ -1,106 +0,0 @@
#extend("layout"):
#export("content"):
<section class="band">
<div class="wrap wrap-narrow">
<span class="eyebrow">Self-hosting</span>
<h2>Run it <span class="hl">yourself</span>.</h2>
<p class="band-lede">
Postgres and one application container. No account with us, nothing that phones
home.
</p>
<div class="code" style="margin-bottom:34px">
<span class="c"># three secrets, generated separately</span><br>
cp .env.example .env<br>
openssl rand -base64 36<br><br>
docker compose up --build
</div>
<h3>The one thing that will bite you</h3>
<p>
<strong>The application must not connect to Postgres as a superuser.</strong>
Superusers bypass row-level security entirely, and so does any role granted
<code>BYPASSRLS</code>. If you point the app at the <code>postgres</code> user, every
level check silently stops applying &mdash; and nothing looks wrong. Queries return
rows, the app is fast, and everyone sees everything.
</p>
<p>
The shipped compose file uses two roles for this reason: one owns the schema and
runs migrations, and the application connects as a plain per-tenant role. The
server checks its own role at startup and refuses to serve traffic if it could
bypass the checks. Please do not remove that.
</p>
<h3>Two volumes, and you need both</h3>
<p>
<code>enclave-pgdata</code> holds the database and <code>enclave-blobs</code> holds
the encrypted files themselves. A backup of one without the other restores nothing
usable. Both are named volumes on purpose: an anonymous volume shows up as
"dangling" and a routine <code>docker volume prune</code> will delete it.
</p>
<p class="fineprint">
A database dump contains all ciphertext and all levels. It contains no key that
opens any of it &mdash; those exist only wrapped to each person's passphrase. That
is a good property for a leaked backup and an unforgiving one for a lost passphrase.
</p>
<h3>Put TLS in front of it</h3>
<p>
The app binds to loopback as shipped. Terminate TLS in a reverse proxy in front of
it. Serving this over plain HTTP defeats the encryption completely: anyone who can
rewrite the page can replace the code that does the encrypting.
</p>
<h3>Your own domains</h3>
<p>
Set <code>ENCLAVE_SITE_URL</code> and <code>ENCLAVE_APP_URL</code> to your own
hostnames so links and canonical URLs point at your deployment rather than ours.
</p>
<h3>The phone apps will find you</h3>
<p>
Nothing to configure. An app is given one address &mdash; yours &mdash; and asks
it which account service to authenticate against; your deployment answers
with the one bundled alongside it. There is no list of blessed hostnames
anywhere in the apps, so a self-hosted server is not a second-class case,
it is the same case.
</p>
<p>
You can check what your server advertises before installing anything:
</p>
<div class="code" style="margin-bottom:34px">
curl https://files.example.org/api/config
</div>
<h3>All three repositories</h3>
<p>
MIT, and between them the whole of it &mdash; there is no fourth component
running somewhere you cannot see.
</p>
<ul class="source-list">
<li>
<a href="#(sourceURL)"><code>flamenet-files</code></a>
&mdash; the server, the web client, the schema that enforces the labels,
and the normative specification everything else is written against.
</li>
<li>
<a href="https://gitlab.com/paulhitt/flamenet-files-ios"><code>flamenet-files-ios</code></a>
&mdash; the iOS app, its CryptoKit engine, and a command-line client that
runs a full round trip against any server, including yours.
</li>
<li>
<a href="https://gitlab.com/paulhitt/flamenet-files-android"><code>flamenet-files-android</code></a>
&mdash; the Android app and its Kotlin engine, with the same command-line
client.
</li>
</ul>
<p>
All three run the same
<a href="#(sourceURL)/-/tree/main/docs/vectors">test vectors</a>. A file
written by one client opens on any other, and their suites would fail before
you noticed otherwise.
</p>
</div>
</section>
#endexport
#endextend
-96
View File
@@ -1,96 +0,0 @@
#extend("layout"):
#export("content"):
<section class="band">
<div class="wrap wrap-narrow">
<span class="eyebrow">Source</span>
<h2>Open to <span class="hl">read</span>.</h2>
<p class="band-lede">
MIT licensed, and complete: the engine, the server, the web client, the
schema that enforces the labels, and the iOS and Android apps. Everything
that decides what you can see, and everything that touches a key, is here
to read.
</p>
<p class="band-lede">
Three separate repositories, because the phone apps are built and released
on their own schedule. The two mobile engines are ports of the same
specification as the browser's and are checked against the same test
vectors, so a file written by one client opens on any other &mdash; and if
that ever stopped being true, their test suites would say so before you
did.
</p>
<div class="cta-row" style="margin-bottom:44px">
<a class="btn btn-primary" href="#(sourceURL)">Browse the repository</a>
<a class="btn btn-ghost" href="#(sourceURL)/-/blob/main/docs/SPEC.md">Read the spec</a>
</div>
<h3>Where to start</h3>
<p>
Four files carry most of the weight. If you only read some of it, read these.
</p>
<ul class="source-list">
<li>
<a href="#(sourceURL)/-/blob/main/Sources/EnclaveLattice/Label.swift"><code>EnclaveLattice/Label.swift</code></a>
&mdash; what it means for one level to cover another. Dominance needs both
the level and the areas to line up, which is the whole idea in about thirty
lines.
</li>
<li>
<a href="#(sourceURL)/-/blob/main/Sources/EnclaveCrypto/KeyHierarchy.swift"><code>EnclaveCrypto/KeyHierarchy.swift</code></a>
&mdash; why a file's key is wrapped to its <em>level</em> and never to the
folder above it. The conventional design would hand a folder&rsquo;s holder
everything inside it.
</li>
<li>
<a href="#(sourceURL)/-/blob/main/sql/002_tenant_template.sql"><code>sql/002_tenant_template.sql</code></a>
&mdash; the database half. Row-level security, the rule that a file must sit
at or above its folder, and the reasons deduplication is switched off.
</li>
<li>
<a href="#(sourceURL)/-/blob/main/client/src/content.js"><code>client/src/content.js</code></a>
&mdash; how a file is encrypted in your browser, and what stops someone
truncating or reordering it afterwards.
</li>
</ul>
<h3>The specification</h3>
<p>
<a href="#(sourceURL)/-/blob/main/docs/SPEC.md">docs/SPEC.md</a> is normative:
exact byte layouts, so another implementation can be written and checked
against this one rather than trusted. The iOS and Android engines were
written from it and are held to it:
<a href="#(sourceURL)/-/tree/main/docs/vectors">the same test vectors</a>
run in all three languages, and a change that broke agreement between them
would fail before it shipped.
</p>
<h3>The apps</h3>
<p>
<a href="https://gitlab.com/paulhitt/flamenet-files-ios">flamenet-files-ios</a>
and
<a href="https://gitlab.com/paulhitt/flamenet-files-android">flamenet-files-android</a>
&mdash; separate repositories, because they build and release on their own
schedule. Each carries a port of the engine, a wire client, and a
command-line tool that runs a full round trip against a real server, so the
cryptography can be exercised without an emulator.
</p>
<h3>Related</h3>
<p>
<a href="https://gitlab.com/paulhitt/flamenet-e2e">flamenet-e2e</a> is the
encryption engine behind Flamenet Messenger &mdash; also MIT, also open. It is a
separate engine: a messenger needs forward secrecy, where old keys are
destroyed, and stored files need the opposite. They share an approach, not code.
</p>
<p class="fineprint" style="margin-top:30px">
Flamenet Files implements no cryptographic primitives of its own. The building
blocks come from the platform&rsquo;s own cryptography. No outside security
audit has happened yet &mdash;
<a href="/donate">that is what donations pay for first</a>.
</p>
</div>
</section>
#endexport
#endextend
+37 -83
View File
@@ -1,94 +1,48 @@
# Security
## Reporting
The Flamenet account service. What it is meant to protect, what it deliberately
does not, and how to report a problem.
Report vulnerabilities privately to **security@extant2000.com**. Please do not
open a public issue for anything exploitable.
## What this service protects
## What this system protects
- **Cross-tenant separation.** Enforced twice: separate OS processes, and
Postgres grants that give a tenant role `USAGE` on its own schema alone. A
logic bug in the label lattice cannot reach another tenant's data because the
grant is checked before any policy runs.
- **Label separation within a tenant.** Row-level security on every labeled
table, plus a key hierarchy in which a node's key is wrapped to its label key.
Both must fail for content to leak across labels.
- **Content confidentiality against the server.** Filenames and contents are
encrypted client side.
- **Inference control.** Undominated objects are reported as absent. Names are
polyinstantiated so constraint violations cannot confirm existence.
Deduplication is disabled and quota is per-label, both to close covert
channels.
- **The passphrase.** It never arrives here. A client stretches it and sends a
secret derived under a context string that is distinct from the one producing
its identity key, so a fully compromised account service can impersonate
somebody to itself and decrypt nothing of theirs.
- **The stored credential.** What is kept is a salted hash of that derived
secret. Brute-forcing it still means redoing the client's 650,000-iteration
stretch per guess.
- **Existence of an account.** Registration, sign-in, passphrase change,
recovery and deletion all run in constant time and answer an unknown handle
exactly as they answer a wrong passphrase. `GET /accounts/:handle/params`
hands out a deterministic fake for handles that do not exist, derived from the
service secret, so it cannot be used to enumerate who is here.
- **The power to mint a session.** Tokens are signed with Ed25519. The public
half is published at `/.well-known/jwks.json`, so a relay somebody else runs
can verify a Flamenet session and cannot forge one.
- **Correlation between relays.** A relay sees only
`HMAC(service_secret, account_id || product)`, never the account id.
## What it does not protect
- **The web client's supply chain.** The page's JavaScript is served by the
host that stores the data. A compromised or coerced server can serve
key-capturing code. This is inherent to browser-delivered end-to-end
encryption and is not solved here.
- **Recovery without the recovery code.** There is no email column, by choice.
Lose the passphrase and the recovery code and the account is unreachable.
That is the cost of storing nothing that identifies anybody.
- **Correlation by this service.** It could link a handle to activity it
mediates. That is exactly why it stores an opaque id, a handle, a verifier
and nothing else.
- **A compromised device.** Anything holding a live token or an unlocked vault
is outside what a server can defend.
The native clients exist now and address it in principle — a signed, pinned
binary cannot be swapped the way a page's script can. That only helps once one
is actually installed from a signed channel; the Android build sideloads
today, and iOS has no release channel yet. Until you are running one, the
accurate phrasing is still "encrypted in your browser before upload".
- **Metadata.** The server knows the shape of your tree, every node's label,
sizes, timestamps, and which principals hold which label keys. Traffic
analysis against that metadata is out of scope.
- **Clearance revocation.** Removing a compartment rotates the label key, but a
user who already held the old key keeps it. Content encrypted under the old
key stays readable to them until it is re-encrypted. There is no mechanism
today that forces re-encryption.
## Reporting
The same applies to giving somebody an area. A grant hands over the label key
itself, so it is durable read access to everything filed at that label, now
and in future, and deleting the grant row does not unlearn a key already held.
The interface says so rather than offering a delete button that would imply
otherwise. Revocation means re-keying the label and re-wrapping everything
under it, and that does not exist yet.
Open a confidential issue on this repository, or mail the address on
flamenet.io. A first reply inside seven days. Nothing here pays a bounty.
Two things do bound it. The recipient must be cleared, which the account
service decides and the file server refuses without. And a label key on its
own opens nothing: every row at that label stays hidden by row-level security
from a session whose token does not carry the clearance, so revoking the
clearance stops the server serving them anything new even though the key
survives.
- **Compromised endpoints.** Keys are derived on the client from a passphrase.
Malware on that device defeats everything above.
- **Availability.** Authentication and registration are rate limited — per
handle, per address, and registration on its own much tighter budget — and
every authentication attempt is held to a fixed time floor. That bounds online
guessing and bulk signup. It is not denial-of-service protection, and nothing
here is: a flood aimed at the service rather than at an account is somebody
else's layer.
## Scope note
The counters are held in Postgres. They were held in process memory until
August 2026, which meant every restart — a deploy, a crash, an OOM kill —
handed out a fresh budget from every address, so the stated limits described
the service only between restarts. They now survive a restart and are shared
by every replica rather than counted separately by each.
## Cryptographic posture
This project implements **no cryptographic primitives**. `EnclaveCrypto` defines
the key hierarchy's shape and its invariants; the primitives come from the
platform — WebCrypto in the browser, CryptoKit and CommonCrypto on iOS, JCA on
Android. Note that [flamenet-e2e](https://gitlab.com/paulhitt/flamenet-e2e) is a
messaging engine: a Drive needs a key hierarchy, not a ratchet, so the two share
an approach rather than code.
Four implementations of one specification is a liability unless they are held to
it, so they are: [docs/vectors](docs/vectors) runs in JavaScript, Swift and
Kotlin, and on an Android device as well as on the JVM — because Android's
provider is not the JDK's and a JVM-only suite cannot see the difference.
⚠️ **No outside audit has happened.** The construction has been reviewed only by
the people who wrote it, which is the weakest form of review there is.
## Accreditation
Implementing a Bell-LaPadula-style model is not the same as being authorized to
hold classified information. This project has no ATO, has not been assessed
against NIST 800-53 or ICD 503, and makes no claim of suitability for classified
data. It implements the *model*, for commercial multi-tenancy.
This repository was also a file service, Flamenet Files, whose security model
covered tenant separation, a label lattice, row-level security and client-side
content encryption. Files was folded into the messenger on 2026-09-21 and the
file server was removed, so none of that is in scope here any more. The
messenger's own guarantees are documented in `flamenet-e2e`.
+49 -139
View File
@@ -1,162 +1,72 @@
# Self-hosting Enclave
# Self-hosting the Flamenet account service
## The one thing that will bite you
You probably do not need this.
**The application must not connect to Postgres as a superuser or as the schema
owner.**
A relay keeps its own accounts by default, and that is not a lesser mode:
people register, message, exchange keys and verify the transparency log exactly
as they would anywhere else. This service exists for one thing, a Flamenet
credential that works across more than one relay, and running it only makes
sense if you run more than one.
Postgres superusers bypass row-level security unconditionally. So does any role
holding `BYPASSRLS`. `FORCE ROW LEVEL SECURITY` does not help. If you point
`DATABASE_URL` at the `postgres` user — which is what most quick-start compose
files do — every policy in this project becomes inert, and *nothing looks
wrong*: queries return rows, the UI works, performance is fine, and every user
sees every file regardless of label.
If you are hosting a relay, read `docs/HOSTING.md` in the relay repository
first. It explains the three shapes and which one you want.
`docker-compose.yml` therefore uses three roles:
## What it needs
| Role | Used by | Why |
|---|---|---|
| `enclave_owner` | the `migrate` services | installing policies, triggers and grants needs ownership |
| `tenant_<slug>` | the `app` service | plain role; RLS applies to it |
| `accounts_service` | the `accounts` service | granted `enclave_accounts` only — no tenant schema at all |
The server calls `RLSGuard.assertRowLevelSecurityApplies` at boot and refuses to
start if its own role can bypass RLS. Do not remove that check.
## Your accounts stay yours
`docker compose up` starts your own account service against your own database.
Nothing reaches flamenet.io, and no account you create exists anywhere but on
your hardware. That is the default and it needs no configuration.
The flamenet.io deployment points `ENCLAVE_ACCOUNTS_URL` at
`https://accounts.flamenet.io` instead, so one credential works across Flamenet
Messenger and Flamenet Files. You *can* do the same — it is a supported
configuration — but it puts your users' accounts on our server rather than
yours. Decide that deliberately rather than by copying a config file.
### ⚠️ The default addresses work in a browser and not on a phone
`ENCLAVE_ACCOUNTS_URL` and `ENCLAVE_SITE_URL` default to `127.0.0.1`, which is
correct for a browser on the machine running the stack and wrong for anything
else. The server hands those addresses to clients, so a phone dials
`127.0.0.1` and reaches *itself*. The symptom is "could not connect" against a
server that is plainly running, which is a poor way to spend an evening.
Set them to something a phone can reach — your machine's address on the network
while you are trying it out, and a real hostname once it is deployed. The apps
need no configuration beyond the one address you type into them; they ask the
server for the rest, which is precisely why the server has to answer with
something true.
If you are testing against a stack on your own machine, note that the Android
emulator reaches the host as `10.0.2.2` and the iOS simulator as `127.0.0.1`,
and one server can only advertise one of them. `scripts/local-for.sh ios` and
`scripts/local-for.sh android` flip it; it is a container restart, not a
rebuild.
⚠️ The two are not interchangeable after the fact. Accounts registered against
your local service do not exist on the shared one, and moving between them means
re-registering: the passphrase never leaves the client, so there is nothing to
export.
## The account service
`accounts` is the shared FlameNet account service. It runs as its own container
with a role granted nothing outside `enclave_accounts`, so it cannot read a
single file row — and the file server's role has no grant on the account tables
in return. The signed clearance token is the entire interface between them.
Two consequences worth knowing before you run it:
- **`ENCLAVE_JWT_SECRET` must match between `accounts` and `app`.** The account
service signs tokens with it; the file server verifies them. A mismatch looks
like every login being rejected.
- **`ENCLAVE_ACCOUNTS_SECRET` derives every product pseudonym.** Rotating it
changes who each account *is* to the file server, orphaning their data. Treat
it as permanent.
A new account has no clearance and sees nothing until you grant one. That is
deliberate — clearance is an administrative act, not something a browser session
can ask for:
```bash
docker compose run --rm accounts ./EnclaveAccounts grant --handle alice --max-class 3 --max-comp 0,1
```
## Setup
Postgres, and two secrets of at least 32 characters each.
```bash
cp .env.example .env
docker compose up -d
```
Generate each secret separately:
| Variable | |
|---|---|
| `POSTGRES_PASSWORD` | required |
| `ENCLAVE_JWT_SECRET` | required, 32+ characters. Signs session tokens. |
| `ENCLAVE_ACCOUNTS_SECRET` | required, 32+ characters. Derives pseudonyms and the decoy salts that stop handle enumeration. |
| `ENCLAVE_ACCOUNTS_DB_PASSWORD` | the login for the service's own restricted role |
| `ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS` | only if a browser calls this service. The apps are not browsers. |
| `ENCLAVE_BIND` | defaults to `127.0.0.1`. Leave it there and put a reverse proxy in front. |
| `ENCLAVE_ACCOUNTS_PORT` | defaults to `8100` |
```bash
openssl rand -base64 36
```
`docker-compose.yml` runs the migrations in their own one-shot service before
the server starts, so a half-migrated database never serves traffic.
Fill in `POSTGRES_PASSWORD`, `ENCLAVE_TENANT_PASSWORD`, `ENCLAVE_JWT_SECRET`,
`ENCLAVE_ACCOUNTS_SECRET` and `ENCLAVE_ACCOUNTS_DB_PASSWORD`. Then:
## ⛔ The two secrets you cannot change later
```bash
docker compose up --build
```
`ENCLAVE_ACCOUNTS_SECRET` derives every account's per-product pseudonym. Change
it and every existing account becomes a different person to every relay that
trusts you, orphaning their data with no way back. Set it once, back it up, and
treat losing it as losing the deployment.
The `migrate` service runs once, installs the shared helpers and the tenant
schema, and exits. `app` starts only after it completes successfully.
`ENCLAVE_JWT_SECRET` has to match whatever verifies the tokens. A mismatch
looks like every session being rejected for no visible reason.
## TLS
`ENCLAVE_BIND` defaults to `127.0.0.1`, so the app is not reachable from outside
the host as shipped. Put a TLS-terminating reverse proxy in front of it. Serving
this over plain HTTP defeats the client-side encryption entirely — an attacker
who can rewrite the page can replace the crypto.
## Tokens
The file server verifies clearance tokens; the account service mints them. Keep
lifetimes short (`ENCLAVE_TOKEN_HOURS`, default 12): revoking a clearance does
not invalidate a token already issued.
Rotating `ENCLAVE_JWT_SECRET` invalidates every outstanding session.
## Ports
`ENCLAVE_PORT` and `ENCLAVE_ACCOUNTS_PORT` set the published host ports, in case
something already holds 8080 or 8100. If you change them, update
`ENCLAVE_SITE_URL` and `ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS` to match — the account
service allow-lists origins explicitly rather than reflecting whatever asks, so
a mismatch shows up as the browser refusing the login request.
## Adding a tenant
Each tenant is a schema, a role, and its own worker process. Set
`ENCLAVE_TENANT` and run the `migrate` service again; then run another `app`
container with that tenant's `DATABASE_URL`. Do not serve two tenants from one
process — the process boundary is half of the isolation.
Prefer the asymmetric path: set `ENCLAVE_JWT_PRIVATE_KEY` to an Ed25519 seed
and relays verify through `/.well-known/jwks.json` instead. That is the
difference between a federation somebody else can join and one they cannot,
because the shared secret that *checks* a token is also the secret that *mints*
one.
## Backups
There are **two** volumes and you need both: `enclave-pgdata` holds the
database, and `enclave-blobs` holds the ciphertext files themselves. A backup of
one without the other restores nothing usable — the database would point at
blobs that no longer exist.
One database, `enclave-pgdata`. There is no blob store and no per-tenant
schema; the whole service is a handful of small tables. `pg_dump` it.
Both are **named** volumes. This is deliberate: an anonymous volume
is reported as "dangling" and a routine `docker volume prune` will destroy it,
along with every file your users have.
Back up with `pg_dump` from the owner role. Note that a dump contains all
ciphertext and all labels; it does not contain any key that opens the
ciphertext, since those exist only wrapped to user identity keys. Losing the
database loses the data; losing a user's passphrase loses that user's files
irrecoverably unless recovery phrases are implemented — they are not, yet.
A backup you have never restored is a belief, not a backup.
## Upgrades
Migrations do not run on restart. Run the `migrate` service deliberately:
Migrations run automatically from the `accounts-migrate` service on each
`docker compose up`. They are append-only: Fluent records what it has run and
never runs it twice, so editing an applied migration works on a fresh database
and silently does nothing on yours.
```bash
docker compose run --rm migrate
```
## The one that bit us
Production connects as `accounts_service`, a role whose `search_path` the schema
sets to `enclave_accounts`. Every table name in the models is unqualified and
relies on it. Connect as any other role and every query fails with
`relation "accounts" does not exist`, which reads like a broken migration and
is not.
-124
View File
@@ -1,124 +0,0 @@
import Foundation
/// When a couriered transfer may be dropped.
///
/// Separated from the code that does the dropping on purpose. This is the part
/// that decides whether somebody's file is deleted, and a decision worth that
/// much should be readable and testable without a database, a clock, or an
/// object store standing behind it.
public enum CourierSweep {
/// How the two modes differ. `stored` is what Files has always done and is
/// never swept; `courier` is held only until it lands.
public enum Mode: String, Sendable, Hashable {
case stored
case courier
}
/// What the server knows about one transfer.
public struct Transfer: Sendable, Hashable {
public let mode: Mode
public let createdAt: Date
/// Devices this transfer was addressed to.
public let intended: Int
/// How many of them have collected it.
public let collected: Int
/// When the last device collected, if all have.
public let completedAt: Date?
public init(mode: Mode, createdAt: Date, intended: Int,
collected: Int, completedAt: Date? = nil) {
self.mode = mode
self.createdAt = createdAt
self.intended = intended
self.collected = collected
self.completedAt = completedAt
}
/// 🔴 Zero intended devices is NOT complete.
///
/// A transfer addressed to nobody has not been collected by everybody;
/// it is a transfer whose recipients are not recorded yet. Reading the
/// empty set as satisfied would delete every blob in the instant
/// between its upload and its delivery rows being written — which is
/// exactly the window where the only copy may be in flight.
public var isComplete: Bool { intended > 0 && collected >= intended }
}
public struct Retention: Sendable, Hashable {
/// Grace after the last device collects. Not zero: a device can collect
/// and then fail to write the file to disk, and a few hours of overlap
/// costs storage where the alternative costs the file.
public let afterDelivery: TimeInterval
/// Backstop for a transfer that never lands, so an undelivered blob
/// does not become permanent storage by accident.
public let undelivered: TimeInterval
public init(afterDelivery: TimeInterval, undelivered: TimeInterval) {
self.afterDelivery = afterDelivery
self.undelivered = undelivered
}
/// The relay's numbers, deliberately: one day after delivery, thirty
/// for something that never arrived. Messenger has run these for
/// envelopes since it shipped.
public static let `default` = Retention(afterDelivery: 24 * 60 * 60,
undelivered: 30 * 24 * 60 * 60)
}
public enum Verdict: Sendable, Hashable {
/// Keep it, and why — the reason is carried so a sweep can say what it
/// did rather than only how many rows it touched.
case keep(Reason)
case drop(Reason)
public enum Reason: String, Sendable, Hashable {
/// Not a courier transfer. Never swept.
case stored
/// Still waiting for at least one device.
case awaitingCollection
/// Collected by everybody, still inside the grace window.
case withinGrace
/// Collected by everybody and past the grace window.
case delivered
/// Never collected, and past the backstop.
case expired
}
}
/// The whole decision, in one place.
///
/// ⚠️ `stored` is checked first and returns before anything else is
/// considered. A blob uploaded under "we keep this for you" is not
/// eligible for deletion on a delivery rule no matter how old it is or how
/// few devices ever asked for it, and putting that first makes it
/// impossible to reach the other branches by accident.
public static func verdict(_ t: Transfer,
retention: Retention = .default,
now: Date) -> Verdict {
guard t.mode == .courier else { return .keep(.stored) }
if t.isComplete {
// `completedAt` missing on a complete transfer means the server
// knows it landed but not when. Treat that as inside the grace
// window rather than outside it: guessing early deletes a file,
// guessing late costs a day of storage.
guard let completedAt = t.completedAt else { return .keep(.withinGrace) }
return now.timeIntervalSince(completedAt) >= retention.afterDelivery
? .drop(.delivered)
: .keep(.withinGrace)
}
return now.timeIntervalSince(t.createdAt) >= retention.undelivered
? .drop(.expired)
: .keep(.awaitingCollection)
}
/// Whether this transfer should be deleted now.
public static func shouldDrop(_ t: Transfer,
retention: Retention = .default,
now: Date) -> Bool {
if case .drop = verdict(t, retention: retention, now: now) { return true }
return false
}
}
-89
View File
@@ -1,89 +0,0 @@
import EnclaveLattice
/// Access-mode and decision types. The point of this module is that the *shape*
/// of a denial is part of the return type: a read denial and a write denial must
/// not be reported to the caller the same way, or the error channel leaks the
/// existence of data the caller is not cleared to know about.
public enum AccessMode: Sendable, Hashable {
case read
case write
}
public enum Decision: Sendable, Hashable {
case allow
/// The object exists but the subject does not dominate it.
/// MUST surface as HTTP 404 with the same body as a genuinely missing
/// resource. A 403 here tells the caller that something is there.
case denyNotVisible
/// The subject can see the object but may not modify it at this session
/// label. Safe to surface as 403 — visibility is already established.
case denyReadOnly
/// The session label itself is outside the principal's clearance. This is a
/// bad request from an authenticated caller, not a data-dependent denial,
/// so it carries no information about any object. Safe as 403.
case denyOutsideClearance
}
/// How writes relate to the session label.
public enum WriteRule: Sendable, Hashable {
/// Write only at exactly the session label (strong tranquility). The default:
/// it makes every write auditable and rules out blind writes entirely.
case equal
/// Bell-LaPadula *-property: may write at or above the session label.
/// Permits blind write-up, which most commercial deployments do not want
/// because the writer cannot then read back what they just wrote.
case starProperty
}
public struct Policy: Sendable, Hashable {
public var writeRule: WriteRule
public init(writeRule: WriteRule = .equal) {
self.writeRule = writeRule
}
/// Decide a single access. `subject` is the *session* label, already
/// validated against the principal's clearance by `session(at:for:)`.
public func decide(subject: Label, object: Label, mode: AccessMode) -> Decision {
// Simple security property: no read up. Dominance is required for the
// object to be visible at all, so this gate comes first for every mode.
guard subject.dominates(object) else { return .denyNotVisible }
switch mode {
case .read:
return .allow
case .write:
switch writeRule {
case .equal:
return subject == object ? .allow : .denyReadOnly
case .starProperty:
// Reachable only when subject == object, since write-up objects
// failed the dominance gate above and are already .denyNotVisible.
return object.dominates(subject) ? .allow : .denyReadOnly
}
}
}
/// Validate a requested session label against a principal's clearance.
/// Call this once at authentication; every later decision assumes it passed.
public func session(at label: Label, for clearance: Clearance) -> Decision {
clearance.permits(label) ? .allow : .denyOutsideClearance
}
}
extension Decision {
/// The HTTP status a denial must be reported as. Centralised so no handler
/// can independently decide to be "more helpful" than the policy allows.
public var httpStatus: Int {
switch self {
case .allow: 200
case .denyNotVisible: 404
case .denyReadOnly, .denyOutsideClearance: 403
}
}
}
-94
View File
@@ -1,94 +0,0 @@
import Foundation
import EnclaveLattice
import EnclaveCrypto
/// Rules for a labeled file hierarchy.
///
/// A directory tree is the hardest structure to label correctly, because a node
/// is only reachable through its ancestors. Two rules fall out of that, and both
/// are enforced here and again as database constraints.
public struct Node: Sendable, Hashable, Identifiable {
public let id: UUID
public let parentID: UUID?
public let name: NameDigest
public let label: Label
public let isFolder: Bool
public init(id: UUID, parentID: UUID?, name: NameDigest, label: Label, isFolder: Bool) {
self.id = id
self.parentID = parentID
self.name = name
self.label = label
self.isFolder = isFolder
}
}
public enum TreeViolation: Error, Sendable, Hashable {
/// A child whose label its parent's label does not sit below would be
/// unreachable: anyone cleared for the child could not traverse the parent.
case childDoesNotDominateParent(child: Label, parent: Label)
}
public enum Resolution: Sendable, Hashable {
case found(UUID)
/// No entry of that name is visible at this session label. Report as 404 —
/// indistinguishable from a name that exists at a label you cannot see.
case notVisible
/// Several visible entries share the name at mutually incomparable labels
/// and none matches the session label exactly. The caller must disambiguate
/// explicitly rather than have the server guess.
case ambiguous([UUID])
}
public enum Tree {
/// Invariant: every child's label dominates its parent's.
///
/// Note this permits a SECRET file inside a CONFIDENTIAL folder (the usual
/// case) and forbids the inverse, which would strand the child.
public static func validate(child: Label, parent: Label) throws {
guard child.dominates(parent) else {
throw TreeViolation.childDoesNotDominateParent(child: child, parent: parent)
}
}
/// The label a newly created node takes.
///
/// Under `WriteRule.equal` this is just the session label, and the tree
/// invariant is then automatic: the session could only traverse into the
/// parent by dominating it, so session ⊒ parent already holds.
public static func labelForNewNode(session: Label, parent: Label) -> Label {
Label.leastUpperBound(session, parent)
}
/// Entries of a folder visible at `session`, as a listing would show them.
public static func visibleChildren(of children: [Node], at session: Label) -> [Node] {
children.filter { session.dominates($0.label) }
}
/// Resolve one path component within a folder, honouring polyinstantiation:
/// the same name may exist at several labels, and each session sees its own.
public static func resolve(
name: NameDigest,
among children: [Node],
at session: Label
) -> Resolution {
let visible = children.filter { $0.name == name && session.dominates($0.label) }
if visible.isEmpty { return .notVisible }
// An exact label match always wins — that is the caller's own instance.
if let exact = visible.first(where: { $0.label == session }) {
return .found(exact.id)
}
// Otherwise take the unique most-sensitive visible instance, if there is
// one. Incomparable candidates have no defensible winner.
let maximal = visible.filter { candidate in
!visible.contains { $0.id != candidate.id && $0.label.dominates(candidate.label) }
}
if maximal.count == 1 { return .found(maximal[0].id) }
return .ambiguous(maximal.map(\.id))
}
}
@@ -62,7 +62,7 @@ struct AccountsCommand: AsyncCommand {
let accountID = try account.requireID()
if signature.revoke {
let product = signature.product ?? "files"
let product = signature.product ?? AccountController.products[0]
let tenant = signature.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default"
let removed = try await ClearanceModel.query(on: db)
.filter(\.$id == accountID).filter(\.$product == product).filter(\.$tenant == tenant)
@@ -104,19 +104,11 @@ struct AccountController: RouteCollection {
/// as consequential as signing into it, so it costs the same passphrase
/// and no less.
let authSecret: Data
/// Which product is asking. Defaults to files, matching the rest of
/// this controller, so an older client that omits it is not silently
/// read as asking about something else.
/// Which product is asking. Optional, and there is only one, so a
/// client that omits it is not guessed at.
let product: String?
}
struct DeleteAccountResponse: Content {
/// True when the account row itself was removed, false when another
/// product still held an identity and only this product's binding went.
/// The caller needs to be able to tell a person which happened.
let accountRemoved: Bool
}
struct SessionResponse: Content {
let token: String
let pseudonym: UUID
@@ -160,7 +152,7 @@ struct AccountController: RouteCollection {
throw Abort(.badRequest, reason: "kdfIterations is below the minimum work factor")
}
let identityProduct = input.identity?.product ?? "files"
let identityProduct = input.identity?.product ?? Self.products[0]
if let identity = input.identity {
try IdentityController.validate(publicKey: identity.publicKey)
guard Self.products.contains(identityProduct) else {
@@ -227,7 +219,11 @@ struct AccountController: RouteCollection {
}
/// Every product this service issues pseudonyms for.
static let products = ["files", "messenger"]
///
/// One, since Flamenet Files was folded into the messenger. Kept as a list
/// because the pseudonym derivation is per product and a second one would
/// go here, not because a second one is expected.
static let products = ["messenger"]
/// The client needs the stretch parameters before it can log in.
///
@@ -343,22 +339,25 @@ struct AccountController: RouteCollection {
return .ok
}
/// `POST /accounts/delete`, remove this account, or detach one product
/// from it when another product is still enrolled.
/// `POST /accounts/delete`, remove this account and everything keyed to it.
///
/// This existed nowhere until now, and its absence was visible from the
/// outside: deleting a Messenger account removed the relay's copy and left
/// the row here, so the handle stayed taken and the person stayed
/// registered with a service they believed they had left.
func destroy(request: Request) async throws -> DeleteAccountResponse {
func destroy(request: Request) async throws -> HTTPStatus {
try await ConstantTime.hold { try await self.destroyInner(request: request) }
}
private func destroyInner(request: Request) async throws -> DeleteAccountResponse {
private func destroyInner(request: Request) async throws -> HTTPStatus {
let input = try request.content.decode(DeleteAccountRequest.self)
let handle = try Self.normalize(handle: input.handle)
try await request.application.authThrottle.check(handle: handle, request: request)
let product = input.product ?? "files"
// Accepted and checked, though there is only one product to name. A
// client asking to leave something this service does not issue is
// confused about what it is talking to, and answering "done" would be
// the wrong thing to tell it.
let product = input.product ?? Self.products[0]
guard Self.products.contains(product) else {
throw Abort(.badRequest, reason: "unknown product '\(product)'")
}
@@ -383,41 +382,11 @@ struct AccountController: RouteCollection {
}
await request.application.authThrottle.succeeded(handle: handle, request: request)
let accountID = try account.requireID()
// Reading the enrolments and acting on them belong in ONE transaction.
// Split, an enrolment landing in the gap would be destroyed by a
// decision taken before it existed.
let removed = try await request.db.transaction { db -> Bool in
let enrolled = try await IdentityModel.query(on: db)
.filter(\.$id == accountID).all().map(\.product)
switch AccountRemoval.decide(deleting: product, enrolled: Set(enrolled)) {
case .removeAccount:
// Everything else keyed to the account is `ON DELETE CASCADE`
// in the schema, so pseudonyms, clearances, devices and any
// identity row go with this one statement.
try await account.delete(on: db)
return true
case .detachProduct:
try await IdentityModel.query(on: db)
.filter(\.$id == accountID)
.filter(\.$product == product)
.delete()
try await AccountProductModel.query(on: db)
.filter(\.$id == accountID)
.filter(\.$product == product)
.delete()
try await ClearanceModel.query(on: db)
.filter(\.$id == accountID)
.filter(\.$product == product)
.delete()
return false
}
}
return DeleteAccountResponse(accountRemoved: removed)
// Everything else keyed to the account is `ON DELETE CASCADE` in the
// schema, so pseudonyms, clearances, devices and any identity row go
// with this one statement.
try await account.delete(on: request.db)
return .ok
}
func session(request: Request) async throws -> SessionResponse {
@@ -428,7 +397,7 @@ struct AccountController: RouteCollection {
let input = try request.content.decode(SessionRequest.self)
let handle = try Self.normalize(handle: input.handle)
try await request.application.authThrottle.check(handle: handle, request: request)
let product = input.product ?? "files"
let product = input.product ?? Self.products[0]
let tenant = input.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default"
let account = try await AccountModel.query(on: request.db)
+34 -1
View File
@@ -107,6 +107,7 @@ func configure(_ app: Application) async throws {
app.migrations.add(AddAccountIdentities())
app.migrations.add(AddRateLimitCounters())
app.migrations.add(AddAccountDevices())
app.migrations.add(RetireTheFilesProduct())
if Environment.get("ENCLAVE_AUTO_MIGRATE") == "true" {
try await app.autoMigrate()
}
@@ -151,6 +152,38 @@ struct InstallAccountsSchema: AsyncMigration {
}
}
/// Flamenet Files folded into the messenger, so its pseudonyms go.
///
/// A separate migration, not an edit to `010_accounts.sql`: Fluent records what
/// it has run and never runs it twice, so changing an applied migration works
/// perfectly on a fresh database and silently does nothing on every existing
/// one. That is how `AddAccountIdentities` came to exist and the same applies
/// here.
struct RetireTheFilesProduct: AsyncMigration {
var name: String { "RetireTheFilesProduct" }
func prepare(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await runScript("SQL/050_retire_files", on: sql)
}
/// Deliberately one-way for the rows. Reverting restores the constraint so
/// a rollback can boot, but the pseudonyms are gone and re-deriving them
/// needs the service secret, which a migration has no business holding.
func revert(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw("""
ALTER TABLE enclave_accounts.account_products
DROP CONSTRAINT IF EXISTS account_products_product_check
""").run()
try await sql.raw("""
ALTER TABLE enclave_accounts.account_products
ADD CONSTRAINT account_products_product_check
CHECK (product IN ('files', 'messenger'))
""").run()
}
}
/// Identity records, added after the schema was already deployed.
///
/// A separate migration rather than an edit to the first one. Fluent records
@@ -259,7 +292,7 @@ struct GrantCommand: AsyncCommand {
throw Abort(.badRequest, reason: "compartment bit \(bit) is not in 0...63")
}
let product = signature.product ?? "files"
let product = signature.product ?? AccountController.products[0]
let tenant = signature.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default"
let accountID = try account.requireID()
@@ -0,0 +1,23 @@
-- Flamenet Files was folded into the messenger, so this service issues
-- pseudonyms for one product instead of two.
--
-- Registration minted a row per product from the start, so every account here
-- carries a `files` pseudonym that nothing has ever read: the `identities`
-- table, which is where a product's key material would live, was empty for
-- `files` on every account when this was written. So there is no key to
-- destroy and nothing to migrate; these rows are bookkeeping for a product
-- that no longer exists.
--
-- Written to be safe in either order against a deployed service. The deletes
-- come first so the tightened constraint has nothing left to reject, and the
-- constraint is replaced rather than dropped, so a stray `files` row can never
-- be written back by an older container still being drained.
DELETE FROM enclave_accounts.identities WHERE product = 'files';
DELETE FROM enclave_accounts.clearances WHERE product = 'files';
DELETE FROM enclave_accounts.account_products WHERE product = 'files';
ALTER TABLE enclave_accounts.account_products
DROP CONSTRAINT IF EXISTS account_products_product_check;
ALTER TABLE enclave_accounts.account_products
ADD CONSTRAINT account_products_product_check CHECK (product IN ('messenger'));
@@ -1,45 +0,0 @@
import Foundation
/// What "delete my account" means when the account is shared.
///
/// One handle here backs every product the service issues pseudonyms for, so a
/// person deleting their Messenger account and a person deleting their Flamenet
/// account are making the same request through two different apps, and the
/// service cannot tell them apart from the wire alone. Taking the wider reading
/// destroys files: the `identities` row for `files` wraps the key those files
/// are encrypted under, and nothing else holds a copy.
///
/// So the product asking is not what decides. What decides is whether anything
/// else is still enrolled once that product is gone. Enrolment means an
/// `identities` row: a product with one has key material on this account that
/// only the account can unwrap, and a product without one has nothing here but
/// a pseudonym, which is derived and would come back identical on a second
/// registration.
///
/// That makes the common case the whole account. Messenger never writes an
/// identity, so someone who only ever used Messenger has no enrolments at all,
/// and deleting from the phone removes the row, which is the behaviour that
/// was missing. Someone who also uses Files keeps their account and loses the
/// Messenger binding, which is the behaviour that would otherwise have been a
/// silent data loss.
public enum AccountRemoval {
public enum Outcome: Equatable, Sendable {
/// Nothing else is enrolled. The account row goes, and the schema's
/// cascades take the pseudonyms, clearances and devices with it.
case removeAccount
/// Another product still has key material here. Only this product's
/// binding goes.
case detachProduct
}
/// - Parameters:
/// - product: the product whose app made the request.
/// - enrolled: every product with an `identities` row on this account.
public static func decide(
deleting product: String,
enrolled: Set<String>
) -> Outcome {
enrolled.subtracting([product]).isEmpty ? .removeAccount : .detachProduct
}
}
-126
View File
@@ -1,126 +0,0 @@
import Foundation
import EnclaveLattice
/// The key hierarchy for zero-knowledge storage.
///
/// This module defines the *shape* of the hierarchy and the invariants that
/// keep it aligned with the lattice. It deliberately implements no primitives:
/// KEM, AEAD and KDF come from swift-crypto and the audited core in
/// `flamenet-e2e`. Inventing them here would be the single worst decision
/// available in this codebase.
///
/// ## The rule
///
/// **A node's key is wrapped to its LABEL key, never to its parent's key.**
///
/// The obvious Drive design derives each node key from its parent folder's key.
/// That is wrong here. The tree invariant permits a RESTRICTED file inside a
/// CONFIDENTIAL folder, so parent-derived keys would hand every holder of the
/// folder key the ability to decrypt content above their clearance. Row-level
/// security would still refuse to *serve* the ciphertext, but anyone with a
/// backup, a snapshot, or a compromised server would read it. Crypto must
/// enforce the lattice independently, or it quietly cancels it.
///
/// ## Three levels
///
/// ```
/// identity key per user, derived from passphrase; never leaves client
/// │ wraps
/// label key one per label actually in use in the tenant
/// │ wraps (wrapped to every user whose clearance permits it)
/// node key one per file/folder, random
/// │ wraps
/// content key one per revision
/// ```
///
/// Labels in use are dozens, not 2^64: keys are materialised on first use at a
/// label and wrapped to the cleared population then.
/// An opaque handle to a key held only in wrapped form on the server.
public struct WrappedKey: Hashable, Sendable, Codable {
public let ciphertext: Data
/// The key this blob is wrapped *to*, so a client knows what to unwrap with.
public let wrappedTo: KeyRef
public init(ciphertext: Data, wrappedTo: KeyRef) {
self.ciphertext = ciphertext
self.wrappedTo = wrappedTo
}
}
public enum KeyRef: Hashable, Sendable, Codable {
case identity(principalID: UUID)
case label(Label)
case node(UUID)
}
/// A label key, materialised on first use and wrapped to each cleared principal.
public struct LabelKeyGrant: Hashable, Sendable, Codable {
public let label: Label
public let principalID: UUID
public let wrapped: WrappedKey
/// Bumped when the label key rotates, which is what revocation triggers.
public let generation: Int
public init(label: Label, principalID: UUID, wrapped: WrappedKey, generation: Int) {
self.label = label
self.principalID = principalID
self.wrapped = wrapped
self.generation = generation
}
}
public enum KeyHierarchyError: Error, Sendable, Hashable {
/// A node key wrapped to anything other than its own label's key. This is
/// the mistake the whole module exists to prevent.
case nodeKeyNotWrappedToItsLabel(node: UUID, expected: Label, actual: KeyRef)
/// A label key granted to a principal whose clearance does not permit it.
case grantExceedsClearance(label: Label, principalID: UUID)
}
public enum KeyHierarchy {
/// Check that a node's key is wrapped to its own label key.
/// Call on every node-key write; it is cheap and it is the invariant.
public static func validate(nodeID: UUID, nodeLabel: Label, key: WrappedKey) throws {
guard case .label(let wrappedLabel) = key.wrappedTo, wrappedLabel == nodeLabel else {
throw KeyHierarchyError.nodeKeyNotWrappedToItsLabel(
node: nodeID, expected: nodeLabel, actual: key.wrappedTo
)
}
}
/// Check that a label key is only ever granted within a clearance.
public static func validate(grant: LabelKeyGrant, clearance: Clearance) throws {
guard clearance.permits(grant.label) else {
throw KeyHierarchyError.grantExceedsClearance(
label: grant.label, principalID: grant.principalID
)
}
}
}
/// Server-side name matching without server-side name knowledge.
///
/// Filenames are ciphertext, and encryption must be randomised, so two
/// encryptions of "Payroll" differ and no uniqueness constraint can see them as
/// equal. Uniqueness and lookup therefore run on a deterministic digest:
///
/// digest = HMAC(folder_key, normalise(name))
///
/// Keyed with the folder key so the server cannot correlate names across
/// folders, cannot dictionary-attack them, and cannot invert them.
///
/// The existence oracle stays closed because the unique index also spans the
/// label: a low-cleared user inserting a colliding digest at their own label
/// never touches the higher-labeled row.
public struct NameDigest: Hashable, Sendable, Codable {
public let bytes: Data
/// For a zero-knowledge deployment: the HMAC computed on the client.
public init(hmac: Data) { self.bytes = hmac }
/// For a server-readable deployment, or for tests.
public init(plaintext: String) {
self.bytes = Data(plaintext.precomposedStringWithCanonicalMapping.utf8)
}
}
@@ -1,78 +0,0 @@
import Fluent
import Foundation
import Vapor
import EnclaveLattice
/// Name a classification level or a compartment.
///
/// A command rather than an endpoint, for the same reason granting a clearance
/// is: the vocabulary is administrative, and a browser session has no business
/// renaming the ladder it is being measured against.
struct LabelCommand: AsyncCommand {
struct Signature: CommandSignature {
@Option(name: "classification", help: "Classification ordinal to name.")
var classification: Int?
@Option(name: "compartment", help: "Compartment bit (0-63) to name.")
var compartment: Int?
@Option(name: "name", help: "The name to give it.")
var name: String?
@Flag(name: "list", help: "Show the current vocabulary.")
var list: Bool
}
var help: String { "Name a classification level or compartment, or list the vocabulary." }
func run(using context: CommandContext, signature: Signature) async throws {
let db = context.application.db
if signature.list {
let levels = try await ClassificationLevelModel.query(on: db).sort(\.$id, .ascending).all()
let compartments = try await CompartmentNameModel.query(on: db).sort(\.$id, .ascending).all()
context.console.print("classifications:")
for level in levels { context.console.print(" \(level.id ?? 0) \(level.name)") }
context.console.print("compartments:")
if compartments.isEmpty { context.console.print(" (none named)") }
for compartment in compartments {
context.console.print(" \(compartment.id ?? 0) \(compartment.name)")
}
return
}
guard let name = signature.name?.trimmingCharacters(in: .whitespaces), !name.isEmpty else {
throw Abort(.badRequest, reason: "--name is required")
}
if let ordinal = signature.classification {
guard (0...255).contains(ordinal) else {
throw Abort(.badRequest, reason: "--classification must be 0...255")
}
let key = Int16(ordinal)
if let existing = try await ClassificationLevelModel.find(key, on: db) {
existing.name = name
try await existing.update(on: db)
} else {
try await ClassificationLevelModel(ordinal: key, name: name).create(on: db)
}
context.console.print("classification \(ordinal) is now '\(name)'")
} else if let bit = signature.compartment {
guard (0...63).contains(bit) else {
throw Abort(.badRequest, reason: "--compartment must be 0...63")
}
let key = Int16(bit)
if let existing = try await CompartmentNameModel.find(key, on: db) {
existing.name = name
try await existing.update(on: db)
} else {
try await CompartmentNameModel(bit: key, name: name).create(on: db)
}
context.console.print("compartment \(bit) is now '\(name)'")
} else {
throw Abort(.badRequest, reason: "one of --classification or --compartment is required")
}
}
}
@@ -1,108 +0,0 @@
import Foundation
import JWT
import Vapor
import EnclaveLattice
import EnclaveAuth
import EnclaveAccess
/// Everything a request is allowed to do, resolved once at the edge.
struct SessionContext: Sendable {
let principalID: UUID
let clearance: Clearance
/// Which device this session belongs to, when the token carries one.
///
/// ⚠️ Optional on purpose and for a long time yet: tokens minted before the
/// claim existed have no device, and so does any client that has not been
/// updated to send one. Code that needs a device must handle its absence
/// rather than assume every session has one.
let device: String?
/// Every device on this account, from the token. Empty when the client
/// predates the claim.
let devices: [String]
/// Already validated against `clearance`. Downstream code may use it freely.
let label: Label
}
private struct SessionContextKey: StorageKey {
typealias Value = SessionContext
}
extension Request {
var session: SessionContext {
get throws {
guard let context = storage[SessionContextKey.self] else {
throw Abort(.unauthorized, reason: "no session label established")
}
return context
}
}
fileprivate func setSession(_ context: SessionContext) {
storage[SessionContextKey.self] = context
}
}
/// Verifies the token, resolves the requested session label, and refuses
/// anything the principal's clearance does not permit.
struct EnclaveSessionMiddleware: AsyncMiddleware {
static let classificationHeader = "X-Enclave-Classification"
static let compartmentsHeader = "X-Enclave-Compartments"
let policy: Policy
func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
let token = try await request.jwt.verify(as: EnclaveToken.self)
let clearance = token.clearance
let requested = try Self.requestedLabel(in: request, defaultingTo: clearance.minimum)
// A label outside the clearance is refused here, once, so that no
// downstream code has to re-derive what the principal may assert.
guard policy.session(at: requested, for: clearance) == .allow else {
throw Abort(.forbidden, reason: "session label exceeds clearance")
}
request.setSession(
SessionContext(
principalID: try token.principalID,
clearance: clearance,
device: token.device,
devices: token.devices ?? [],
label: requested
)
)
return try await next.respond(to: request)
}
/// Absent headers default to the clearance *minimum*, never the maximum.
/// A client that forgets to declare a label gets the least sensitive
/// session it could have asked for rather than the most.
static func requestedLabel(in request: Request, defaultingTo fallback: Label) throws -> Label {
guard let raw = request.headers.first(name: classificationHeader) else {
return fallback
}
guard let classification = Int16(raw) else {
throw Abort(.badRequest, reason: "\(classificationHeader) must be an integer ordinal")
}
let bits = (request.headers.first(name: compartmentsHeader) ?? "")
.split(separator: ",")
.map(String.init)
.compactMap { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
var positions: [Int] = []
for bit in bits {
guard let position = Int(bit), (0...63).contains(position) else {
throw Abort(.badRequest, reason: "compartment bit '\(bit)' is not in 0...63")
}
positions.append(position)
}
return Label(
classification: Classification(classification),
compartments: Compartments(bits: positions)
)
}
}
@@ -1,78 +0,0 @@
import Foundation
import JWT
import Vapor
import EnclaveLattice
import EnclaveAuth
/// Mint a clearance token, for development only.
///
/// In production the control plane authenticates the user, reads their
/// clearance from its own store, and signs this token. That service does not
/// exist yet, and without some way to produce a token nothing can be exercised
/// end to end -- so this command exists, and refuses to run in production.
struct TokenCommand: AsyncCommand {
struct Signature: CommandSignature {
@Option(name: "principal", help: "Principal UUID. A random one is generated if omitted.")
var principal: String?
@Option(name: "tenant", help: "Tenant slug. Defaults to ENCLAVE_TENANT or 'default'.")
var tenant: String?
@Option(name: "max-class", help: "Maximum classification ordinal. Default 3.")
var maxClass: Int?
@Option(name: "max-comp", help: "Comma-separated compartment bits, e.g. 0,1. Default none.")
var maxComp: String?
@Option(name: "hours", help: "Token lifetime in hours. Default 12.")
var hours: Int?
}
var help: String { "Mint a development clearance token. Refuses to run in production." }
func run(using context: CommandContext, signature: Signature) async throws {
let app = context.application
guard app.environment != .production else {
throw Abort(.forbidden, reason: """
Refusing to mint tokens in production. Clearance decisions belong to the \
control plane, which signs tokens with ENCLAVE_JWT_SECRET.
""")
}
let principal = try signature.principal.map {
guard let id = UUID(uuidString: $0) else {
throw Abort(.badRequest, reason: "--principal must be a uuid")
}
return id
} ?? UUID()
let bits = (signature.maxComp ?? "")
.split(separator: ",")
.compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
for bit in bits where !(0...63).contains(bit) {
throw Abort(.badRequest, reason: "compartment bit \(bit) is not in 0...63")
}
let maximum = Label(
classification: Classification(Int16(signature.maxClass ?? 3)),
compartments: Compartments(bits: bits)
)
let lifetime = Double(signature.hours ?? 12) * 3600
let token = EnclaveToken(
subject: .init(value: principal.uuidString),
expiration: .init(value: Date().addingTimeInterval(lifetime)),
tenant: signature.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default",
maxClassification: maximum.classification.rawValue,
maxCompartments: maximum.compartments.postgresBitPattern,
minClassification: 0,
minCompartments: 0
)
let signed = try await app.jwt.keys.sign(token)
context.console.print("principal: \(principal.uuidString)")
context.console.print("clearance: classification \(maximum.classification.rawValue), compartments \(bits)")
context.console.print("")
context.console.print(signed)
}
}
-17
View File
@@ -1,17 +0,0 @@
import Vapor
extension Environment {
/// A configuration value, where blank means absent.
///
/// `Environment.get` answers `""` for a variable that is set to nothing,
/// and Compose sets every `VAR: ${VAR:-}` to exactly that rather than
/// leaving it out. So a plain `!= nil` check reads an unconfigured
/// deployment as a configured one — which is how a page offering payment
/// renders with no payment processor behind it, and how a server announces
/// a bucket it has no credentials for.
static func value(_ name: String) -> String? {
guard let raw = Environment.get(name) else { return nil }
let trimmed = raw.trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty ? nil : trimmed
}
}
@@ -1,167 +0,0 @@
import Fluent
import SQLKit
import Vapor
import Foundation
import EnclaveLattice
/// Ciphertext upload and download.
///
/// The server never sees plaintext and never holds a key, so there is nothing
/// to validate about the bytes. What it does enforce is the label: the row is
/// created at the session label by the RLS insert policy, and a download only
/// succeeds if the session dominates it.
struct BlobController: RouteCollection {
/// The largest ciphertext this server will accept, in bytes.
///
/// One number, in one place, and advertised at `/api/config` so a client can
/// refuse an oversized file *before* reading it rather than after. Without
/// that, a phone reads the whole file into memory, encrypts it into a second
/// copy, uploads it, and only then learns the server was never going to take
/// it — which on a phone is not a wasted round trip, it is a crash.
///
/// Raising it is a real decision, not a knob: the upload path buffers whole
/// blobs on both sides, so this number is also the memory a single request
/// can cost. Streaming is the fix for wanting it much larger.
static var maxUploadBytes: Int {
Environment.get("ENCLAVE_MAX_UPLOAD_BYTES").flatMap(Int.init) ?? 64 * 1024 * 1024
}
func boot(routes: any RoutesBuilder) throws {
let blobs = routes.grouped("api", "blobs")
blobs.on(.POST, body: .collect(maxSize: .init(value: Self.maxUploadBytes)), use: upload)
blobs.get(":blobID", use: download)
blobs.post(":blobID", "collected", use: collected)
}
static let modeHeader = "X-Enclave-Blob-Mode"
struct UploadResponse: Content {
let id: UUID
let sizeBytes: Int64
/// Echoed back so a client never has to assume which it got.
let mode: String
/// How many devices this transfer is waiting for. Zero on a courier
/// upload means nothing else is signed in to receive it — worth the
/// client saying so, because the file will expire rather than arrive.
let waitingFor: Int
}
func upload(request: Request) async throws -> UploadResponse {
let session = try request.session
guard let buffer = request.body.data, buffer.readableBytes > 0 else {
throw Abort(.badRequest, reason: "empty body")
}
let bytes = Data(buffer.readableBytesView)
// 🔴 Courier is opt-in per upload, and the default is what Files has
// always done. A header that silently changed an upload into something
// the server will delete would be the wrong default in the one
// direction that cannot be undone.
let courier = request.headers.first(name: Self.modeHeader)
.map { $0.lowercased() == "courier" } ?? false
// Written before the row exists, so a crash leaves an orphaned file
// rather than a row pointing at nothing. Orphans are collectable;
// dangling rows are data loss.
let objectKey = try request.application.blobs.write(bytes)
let blob = BlobModel(
label: session.label,
sizeBytes: Int64(bytes.count),
objectKey: objectKey
)
// Everything except the device that just uploaded it: that one has the
// file already, and waiting for it to collect its own upload would mean
// no transfer ever completes.
let waitingFor = courier
? session.devices.filter { $0 != session.device }
: []
return try await request.labeled { db in
try await blob.create(on: db)
let id = try blob.requireID()
if courier {
guard let sql = db as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "courier needs a SQL database")
}
try await sql.raw("""
UPDATE blobs SET mode = 'courier' WHERE id = \(bind: id)
""").run()
// ⚠️ Written in the same transaction as the mode. A blob that
// is courier with no delivery rows is one the sweep reads as
// "addressed to nobody" and holds to the backstop — safe, but
// it would sit there for thirty days having reached nothing.
for device in waitingFor {
try await sql.raw("""
INSERT INTO blob_deliveries (blob_id, device_id)
VALUES (\(bind: id), \(bind: device))
ON CONFLICT DO NOTHING
""").run()
}
}
return UploadResponse(id: id, sizeBytes: blob.sizeBytes,
mode: courier ? "courier" : "stored",
waitingFor: waitingFor.count)
}
}
/// A device saying it has the file and the server may stop holding it.
///
/// 🔴 Separate from the download, deliberately. A download that has started
/// is not a file that has arrived: the response can fail halfway, the disk
/// can be full, the app can be killed. Marking collection on the GET would
/// drop the server's copy while the only complete copy was still in flight,
/// which is precisely the moment it is most needed. The client says so once
/// the bytes are written down.
///
/// Idempotent: a device that acknowledges twice has still collected once.
func collected(request: Request) async throws -> HTTPStatus {
let session = try request.session
guard let blobID = request.parameters.get("blobID", as: UUID.self) else {
throw Abort(.badRequest, reason: "blobID must be a uuid")
}
guard let device = session.device else {
// Without a device there is nothing to mark, and silently
// succeeding would let a client believe it had acknowledged.
throw Abort(.badRequest, reason:
"this session has no device, so it cannot collect a transfer")
}
return try await request.labeled { db in
guard let sql = db as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "collection needs a SQL database")
}
// ⚠️ Only sets the time if it is not already set. A second
// acknowledgement must not move the clock forward, or a device
// pinging in a loop would hold the grace window open for ever.
try await sql.raw("""
UPDATE blob_deliveries SET collected_at = now()
WHERE blob_id = \(bind: blobID)
AND device_id = \(bind: device)
AND collected_at IS NULL
""").run()
return .noContent
}
}
func download(request: Request) async throws -> Response {
guard let blobID = request.parameters.get("blobID", as: UUID.self) else {
throw Abort(.badRequest, reason: "blobID must be a uuid")
}
// Row-level security decides this. An undominated blob is simply not
// found, which is the same answer as one that does not exist.
let objectKey = try await request.labeled { db -> String in
guard let blob = try await BlobModel.find(blobID, on: db) else { throw Abort(.notFound) }
return blob.objectKey
}
let response = Response(status: .ok)
response.headers.contentType = HTTPMediaType(type: "application", subType: "octet-stream")
response.body = .init(data: try request.application.blobs.read(objectKey))
return response
}
}
@@ -1,47 +0,0 @@
import Vapor
/// What a client needs to know before it can sign in anywhere.
///
/// The browser gets this from a `<meta>` tag, because it was served the page by
/// the very server it is about to talk to. A native app was not: it is handed a
/// server address by a person typing one, and it has no other way to learn
/// which account service that server trusts.
///
/// So the server names its own. Point the app at `files.flamenet.io` and it is
/// told to authenticate against `accounts.flamenet.io`; point it at a
/// self-hosted box and it is told to use the account service bundled alongside
/// it. One field for the user, no build flags, and no client-side list of which
/// hostnames are "ours" — which would be wrong the moment somebody forks this.
///
/// Deliberately unauthenticated and deliberately empty of anything sensitive:
/// it says where to go, never who is there.
struct ConfigController: RouteCollection {
struct ConfigResponse: Content {
/// Absolute. The app posts credentials here, not to the file server.
let accountsURL: String
/// Which tenant this deployment serves. Clearance is scoped to it.
let tenant: String
/// So an app can show where it is connected, and link to the source of
/// the thing it is talking to rather than of itself.
let siteURL: String
let sourceURL: String
/// The largest ciphertext this deployment accepts. Advertised so a
/// client can refuse a file before reading it into memory, instead of
/// discovering the limit after paying for the read and the encryption.
let maxUploadBytes: Int
/// Bumped when the wire format changes in a way an old app cannot read.
let protocolVersion = 1
}
func boot(routes: any RoutesBuilder) throws {
routes.get("api", "config") { _ async -> ConfigResponse in
ConfigResponse(
accountsURL: SiteController.accountsURL,
tenant: Environment.get("ENCLAVE_TENANT") ?? "default",
siteURL: SiteController.siteURL,
sourceURL: SiteController.sourceURL,
maxUploadBytes: BlobController.maxUploadBytes
)
}
}
}
@@ -1,253 +0,0 @@
import Foundation
import Vapor
/// Donations, via Stripe Checkout.
///
/// The same environment variables the Messenger relay reads — `FN_DONATE_PROVIDER`
/// and `FN_DONATE_SECRET` — so one Stripe account backs both without either
/// holding a copy of the other's configuration.
///
/// ⚠️ The secret is read from the environment and is never committed. A payment
/// credential in a public repository is unrecoverable: it is cloned, cached and
/// indexed before it can be rotated.
///
/// Deliberately no Stripe SDK. One form-encoded POST is the whole integration,
/// and a dependency that ships its own HTTP stack is not worth the surface.
///
/// The payment form is *embedded*: the session is created with `ui_mode=embedded`
/// and mounted on `/donate`, so nobody is sent to a different site to pay and
/// then bounced back. Card details still never reach this server — they are
/// typed into a Stripe-hosted frame, which is what keeps this out of PCI scope.
/// `js.stripe.com` is therefore a script this page loads, and the one part of
/// the flow that cannot be served from here: Stripe does not permit that file to
/// be self-hosted, and collecting raw card numbers ourselves to avoid it would
/// trade a third-party script for full card-data liability.
struct DonateController: RouteCollection {
static let minAmount = 1
static let maxAmount = 5_000
static var provider: String? { Environment.value("FN_DONATE_PROVIDER") }
static var secret: String? { Environment.value("FN_DONATE_SECRET") }
/// Safe to put in the page — that is what it is for. Still configuration
/// rather than a constant, because it differs per deployment and a
/// self-hoster donating to themselves is not a case worth hard-coding.
static var publishableKey: String? { Environment.value("FN_DONATE_PUBLISHABLE_KEY") }
/// The Stripe **connected account** donations are taken on, or nil to take
/// them on whichever account the secret key itself authenticates as.
///
/// Set to an `acct_…` id and the session is created under that account — a
/// *direct* charge, so the money, the fees, the receipt and the statement
/// descriptor are its own rather than the platform's. Unset is not an
/// error: a self-hoster with their own key wants exactly that. But with a
/// platform key and no account, Stripe still answers 200 and the donation
/// lands on the platform, which is the one failure here that never shows up
/// on the page.
///
/// The publishable key stays the **platform's**: a direct charge is
/// confirmed by the platform key scoped with `stripeAccount`, and the
/// connected account's own key would be the wrong half of that pair.
static var account: String? { Environment.value("FN_DONATE_ACCOUNT") }
/// Embedded checkout needs the publishable key as well: without it the form
/// cannot render, and offering a button that fails on click is worse than
/// saying donations are not configured.
static var isEnabled: Bool { provider != nil && secret != nil && configurationProblem == nil }
enum Mode: String {
case test, live
}
/// Which Stripe account a key belongs to, read off its prefix.
///
/// Stripe encodes this in the key itself, which is the only reason it can
/// be checked here at all — nothing is asked of the network.
static func mode(of key: String) -> Mode? {
if key.hasPrefix("sk_test_") || key.hasPrefix("pk_test_") { return .test }
if key.hasPrefix("sk_live_") || key.hasPrefix("pk_live_") { return .live }
return nil
}
/// The mode donations are actually running in, or nil if it cannot be told.
static var mode: Mode? { secret.flatMap(mode(of:)) }
/// Why donations are switched off, in a sentence, or nil if they are fine.
///
/// Every one of these is a configuration that *looks* like it works. A
/// missing publishable key renders a form that cannot mount; a test secret
/// on a live site takes payment details and collects nothing. Both are
/// silent, and both are only ever noticed by the money not arriving — so
/// they are turned into a refusal and a log line instead.
static var configurationProblem: String? {
guard provider != nil, let secret else { return nil }
guard let publishableKey else {
return "FN_DONATE_SECRET is set but FN_DONATE_PUBLISHABLE_KEY is not. "
+ "The embedded payment form cannot render without it."
}
let secretMode = mode(of: secret)
let publishableMode = mode(of: publishableKey)
if secretMode != nil, publishableMode != nil, secretMode != publishableMode {
return "FN_DONATE_SECRET is a \(secretMode!.rawValue) key and "
+ "FN_DONATE_PUBLISHABLE_KEY is a \(publishableMode!.rawValue) key. "
+ "They must be from the same Stripe account and mode."
}
if let account, !account.hasPrefix("acct_") {
return "FN_DONATE_ACCOUNT is not a Stripe account id. "
+ "It is the connected account donations are charged on and starts with acct_."
}
if publishableKey.hasPrefix("sk_") {
return "FN_DONATE_PUBLISHABLE_KEY looks like a secret key. "
+ "The publishable key starts with pk_ and is the one safe to put in a page."
}
return nil
}
struct Form: Content {
let amount: String?
let custom_amount: String?
let frequency: String?
}
func boot(routes: any RoutesBuilder) throws {
routes.get("donate") { request async throws -> View in
try await request.view.render("donate", DonateContext(
thanks: request.query[String.self, at: "thanks"] != nil,
error: request.query[String.self, at: "error"]
))
}
routes.post("donate", "session", use: session)
}
struct DonateContext: Encodable {
let title = "Donate — Flamenet Files"
let description = "Fund an independent security audit of Flamenet Files."
let path = "/donate"
let siteURL = SiteController.siteURL
let appURL = SiteController.appURL
let sourceURL = SiteController.sourceURL
let enabled = DonateController.isEnabled
let publishableKey = DonateController.publishableKey
/// Empty rather than nil, so the page can test it as a string. Leaf
/// renders an absent optional as nothing useful.
let stripeAccount = DonateController.account ?? ""
let minAmount = DonateController.minAmount
let maxAmount = DonateController.maxAmount
let thanks: Bool
let error: String?
}
struct SessionResponse: Content {
let clientSecret: String
}
/// Opens a payment session and hands its client secret back to the page.
///
/// Answers JSON rather than redirecting, because the form it serves is
/// mounted in place: a redirect here would be the exact thing this flow
/// exists to avoid. Errors come back as a status and a sentence the page
/// shows next to the form.
func session(request: Request) async throws -> SessionResponse {
guard let provider = Self.provider, let secret = Self.secret, Self.publishableKey != nil else {
throw Abort(.serviceUnavailable, reason: "Donations aren't available right now. Nothing was charged.")
}
guard provider.lowercased() == "stripe" else {
request.logger.error("unknown donate provider", metadata: ["provider": .string(provider)])
throw Abort(.serviceUnavailable, reason: "Donations aren't available right now. Nothing was charged.")
}
let form = try request.content.decode(Form.self)
// Resolved before anyone is contacted: an invalid amount should fail
// here, against the form the person is still looking at.
let raw = (form.amount == "custom" ? form.custom_amount : form.amount) ?? ""
guard let dollars = Int(raw.trimmingCharacters(in: .whitespaces)),
dollars >= Self.minAmount, dollars <= Self.maxAmount
else {
throw Abort(.badRequest, reason: "Please enter an amount between $\(Self.minAmount) and $\(Self.maxAmount).")
}
let clientSecret = try await stripeSession(
dollars: dollars,
recurring: (form.frequency ?? "once") == "monthly",
secret: secret,
request: request
)
return SessionResponse(clientSecret: clientSecret)
}
private func stripeSession(
dollars: Int, recurring: Bool, secret: String, request: Request
) async throws -> String {
// The deployment's own declared address, in preference to guessing one
// from the request. Reconstructing it from the Host header meant
// defaulting the scheme to https whenever no proxy set
// `X-Forwarded-Proto`, which sends a donor on a plain-http server to an
// https URL that does not answer — after they have paid, which is the
// worst moment to hand somebody a dead page.
let base = SiteController.siteURL.hasSuffix("/")
? String(SiteController.siteURL.dropLast())
: SiteController.siteURL
var fields: [String: String] = [
"mode": recurring ? "subscription" : "payment",
// ⚠️ `embedded`, the value this was written against, is REJECTED by
// the current API version: "The ui_mode value `embedded` is no
// longer supported. Use `embedded_page` instead." Nothing pins a
// Stripe-Version here, so the account's default decides, and the
// rename arrived as a 400 on a live donate page rather than at
// build time.
"ui_mode": "embedded_page",
// Stripe sends the browser here itself once the payment completes,
// and it is this site. There is no cancel_url in embedded mode:
// there is nowhere to come back *from*.
"return_url": "\(base)/donate?thanks=1",
"line_items[0][quantity]": "1",
"line_items[0][price_data][currency]": "usd",
"line_items[0][price_data][unit_amount]": String(dollars * 100),
"line_items[0][price_data][product_data][name]":
recurring ? "Flamenet Files — monthly support" : "Flamenet Files — donation",
]
if recurring { fields["line_items[0][price_data][recurring][interval]"] = "month" }
// Types spelled out: SQLKit is in scope in this target, and its
// string-interpolation conformance otherwise captures these literals.
func escape(_ value: String) -> String {
value.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? value
}
let encoded: String = fields
.map { (key: String, value: String) -> String in escape(key) + "=" + escape(value) }
.joined(separator: "&")
var headers = HTTPHeaders()
headers.add(name: .authorization, value: "Bearer \(secret)")
headers.add(name: .contentType, value: "application/x-www-form-urlencoded")
// Open the session *on the connected account*, not on the platform the
// key authenticates as. One header is the whole of it. Omitting it is
// not an error Stripe reports — it succeeds, against the wrong account.
if let account = Self.account {
headers.add(name: "Stripe-Account", value: account)
}
// Spelled as a URI rather than a bare literal: SQLKit is in scope in
// this target and its string-literal conformance otherwise wins.
let endpoint = URI(string: "https://api.stripe.com/v1/checkout/sessions")
let response = try await request.client.post(endpoint, headers: headers) {
(outbound: inout ClientRequest) in
outbound.body = ByteBuffer(string: encoded)
}
guard response.status == .ok,
let data = response.body.flatMap({ Data(buffer: $0) }),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let clientSecret = json["client_secret"] as? String
else {
// The processor's own error text is written for a developer and may
// name the account, so it is logged and not shown.
request.logger.error("stripe checkout session failed",
metadata: ["status": .string(response.status.description)])
throw Abort(.badGateway, reason: "Could not start a payment session. Please try again later.")
}
return clientSecret
}
}
@@ -1,231 +0,0 @@
import Fluent
import SQLKit
import Vapor
import Foundation
import EnclaveLattice
/// Key distribution.
///
/// Everything here is wrapped ciphertext. The server hands out blobs it cannot
/// open, and the client unwraps them with an identity key derived from a
/// passphrase that never leaves the device.
struct KeyController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let keys = routes.grouped("api", "keys")
keys.get("labels", use: labelGrants)
keys.post("labels", use: storeGrant)
keys.post("labels", "delegate", use: delegateGrant)
keys.get("nodes", ":nodeID", use: nodeKey)
}
struct GrantResponse: Content {
let classification: Int16
let compartments: [Int]
let generation: Int
let wrappedKey: Data
}
/// The label keys wrapped to the calling principal.
///
/// Filtered by principal rather than by dominance: which *other* people hold
/// a compartment is itself sensitive, so this is not a lattice query.
func labelGrants(request: Request) async throws -> [GrantResponse] {
let session = try request.session
return try await request.labeled { db in
try await LabelKeyGrantModel.query(on: db)
.filter(\.$principalID == session.principalID)
.all()
.map {
GrantResponse(
classification: $0.classification,
compartments: $0.label.compartments.bits,
generation: $0.generation,
wrappedKey: $0.wrappedKey
)
}
}
}
/// One node's wrapped key. RLS hides keys above the session label, so an
/// undominated node's key is a 404 exactly like the node itself.
func nodeKey(request: Request) async throws -> GrantResponse {
guard let nodeID = request.parameters.get("nodeID", as: UUID.self) else {
throw Abort(.badRequest, reason: "nodeID must be a uuid")
}
return try await request.labeled { db in
guard let key = try await NodeKeyModel.find(nodeID, on: db) else {
throw Abort(.notFound)
}
return GrantResponse(
classification: key.classification,
compartments: key.label.compartments.bits,
generation: key.generation,
wrappedKey: key.wrappedKey
)
}
}
}
extension KeyController {
struct StoreGrantRequest: Content {
let classification: Int16
let compartments: [Int]
let wrappedKey: Data
let generation: Int?
}
struct DelegateGrantRequest: Content {
/// What a person types. The server resolves it rather than trusting the
/// client's idea of who the recipient is.
let handle: String
/// Who the client believes that handle resolves to, and therefore who
/// it wrapped the key for. Checked against the account service's answer:
/// a mismatch means the client wrapped for the wrong person, and the
/// grant would be a key nobody can open.
let principalID: UUID
let wrappedKey: Data
}
/// Hand the caller's label key to another principal at the session label.
///
/// Two checks, in the two places that can each see half of it.
///
/// The database enforces the half it can see: the row's label must equal the
/// session label, and the granter must already hold a key at that label. So
/// nobody mints a key for a label they cannot themselves assert.
///
/// The account service enforces the half only the control plane knows: that
/// the recipient is cleared. A tenant role has no grant on the account
/// schema, so this process genuinely cannot answer that and does not try —
/// it asks, with the caller's own token, and refuses on anything but a
/// clean answer.
///
/// Worth stating what the second check is worth, because it is the weaker
/// one. A label key alone opens nothing: every row at that label stays
/// hidden by row-level security from a session whose token lacks the
/// clearance. A grant that somehow slipped past would hand somebody
/// ciphertext they can unwrap and a server that will never serve it to them.
func delegateGrant(request: Request) async throws -> HTTPStatus {
let session = try request.session
let input = try request.content.decode(DelegateGrantRequest.self)
guard input.principalID != session.principalID else {
throw Abort(.badRequest, reason: "use the ordinary grant route for yourself")
}
let resolved = try await AccountsLookup.clearanceCheck(
handle: input.handle, label: session.label, on: request)
guard resolved.pseudonym == input.principalID else {
// The client wrapped the key for somebody else. Storing it would
// create a grant that its recipient cannot open, which is worse
// than refusing: it looks like access and is not.
throw Abort(.conflict, reason: "that handle does not resolve to the named principal")
}
let grant = LabelKeyGrantModel()
grant.classification = session.label.classification.rawValue
grant.compartments = session.label.columns.compartments
grant.principalID = input.principalID
grant.generation = 1
grant.wrappedKey = input.wrappedKey
// Hoisted: the closure below is @Sendable and `Request` is not, so
// reaching for `request` inside it is a concurrency error rather than a
// convenience — and one that only shows up on Linux.
let logger = request.logger
let audit = GrantAuditModel()
audit.grantedBy = session.principalID
audit.grantedTo = input.principalID
audit.classification = session.label.classification.rawValue
audit.compartments = session.label.columns.compartments
return try await request.labeled { db in
// Checked here rather than left to the policy, because the policy's
// refusal arrives as an opaque row-level-security error and the two
// failures need different words. Not a security check — the policy
// is still the one that decides — just a legible one.
let holds = try await LabelKeyGrantModel.query(on: db)
.filter(\.$principalID == session.principalID)
.filter(\.$classification == grant.classification)
.filter(\.$compartments == grant.compartments)
.first()
guard holds != nil else {
throw Abort(.forbidden,
reason: "You don't hold a key for this area yourself.")
}
// Whether the recipient already holds one cannot be checked by
// querying: the read policy on this table restricts SELECT to your
// own rows, so a lookup by their id returns nothing whether or not
// the grant exists. That restriction is deliberate — who holds a
// compartment is not disclosable — so the uniqueness constraint is
// the only thing that can tell us, and it tells us by failing.
// Raw, and deliberately without RETURNING.
//
// ⚠️ Fluent's `create` appends `RETURNING "id"`, and RETURNING reads
// the new row back — through the SELECT policy, which restricts this
// table to your *own* rows. Inserting on somebody else's behalf
// therefore fails at the read rather than the write, and reports
// something that reads exactly like a constraint violation. The
// policy is right and the read is unnecessary: the id is generated
// here, and `grant_audit` is what records that this happened.
guard let sql = db as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "labeled access needs a SQL database")
}
let newID = UUID()
let classification = grant.classification
let compartments = grant.compartments
let recipient = grant.principalID
let generation = grant.generation
let wrappedKey = grant.wrappedKey
do {
try await sql.raw("""
INSERT INTO label_key_grants
(id, classification, compartments, principal_id, generation, wrapped_key)
VALUES (\(bind: newID), \(bind: classification), \(bind: compartments), \
\(bind: recipient), \(bind: generation), \(bind: wrappedKey))
""").run()
} catch {
// With the precheck above passed, the realistic cause is the
// unique constraint and nothing else. Saying so plainly is safe:
// the caller is cleared for the label and named the recipient
// themselves, so this discloses nothing they did not supply.
logger.notice("delegated grant rejected",
metadata: ["error": .string(String(describing: error))])
throw Abort(.conflict, reason:
"They already have their own key for this area, so giving them yours "
+ "would orphan whatever they filed under it. They need to start from "
+ "an area they have not written to.")
}
try await audit.create(on: db)
return .created
}
}
/// Store a label key grant for the calling principal.
///
/// The RLS insert policy permits self-grant at exactly the session label
/// and nothing else, so this cannot be used to widen anyone's clearance --
/// it only records a key for a label the caller was already able to assert.
func storeGrant(request: Request) async throws -> HTTPStatus {
let session = try request.session
let input = try request.content.decode(StoreGrantRequest.self)
let grant = LabelKeyGrantModel()
grant.classification = input.classification
grant.compartments = Label(
classification: Classification(input.classification),
compartments: Compartments(bits: input.compartments)
).columns.compartments
grant.principalID = session.principalID
grant.generation = input.generation ?? 1
grant.wrappedKey = input.wrappedKey
return try await request.labeled { db in
try await grant.create(on: db)
return .created
}
}
}
@@ -1,150 +0,0 @@
import Fluent
import Vapor
import Foundation
import EnclaveLattice
import EnclaveAccess
import EnclaveCrypto
/// File-tree routes.
///
/// Note how little access-control code appears here. Row-level security filters
/// below the ORM, so an undominated node simply is not returned, and the
/// ordinary `guard let ... else { throw Abort(.notFound) }` is already the
/// correct inference-controlled answer. Handlers that reach for `Policy`
/// directly are the exception, not the rule.
struct NodeController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let nodes = routes.grouped("api", "nodes")
nodes.get("roots", use: roots)
nodes.get(":folderID", "children", use: children)
nodes.post(use: create)
}
// MARK: responses
struct NodeResponse: Content {
let id: UUID
let isFolder: Bool
let classification: Int16
let compartments: [Int]
let nameCiphertext: Data
let nameDigest: Data
let blobID: UUID?
let contentKey: Data?
let sizeBytes: Int64
let updatedAt: Date?
}
struct CreateNodeRequest: Content {
let parentID: UUID?
let nameDigest: Data
let nameCiphertext: Data
let isFolder: Bool
/// The node key, already wrapped client-side to the session label's key.
let wrappedKey: Data
/// Set for files whose ciphertext was already uploaded to /api/blobs.
let blobID: UUID?
/// The content key for this revision, wrapped to the node key.
let contentKey: Data?
let sizeBytes: Int64?
}
static func describe(_ node: NodeModel) -> NodeResponse {
NodeResponse(
id: node.id!,
isFolder: node.isFolder,
classification: node.classification,
compartments: node.label.compartments.bits,
nameCiphertext: node.nameCiphertext,
nameDigest: node.nameDigest,
blobID: node.blobID,
contentKey: node.contentKey,
sizeBytes: node.sizeBytes,
updatedAt: node.updatedAt ?? node.createdAt
)
}
// MARK: handlers
/// List a folder's visible children.
func children(request: Request) async throws -> [NodeResponse] {
guard let folderID = request.parameters.get("folderID", as: UUID.self) else {
throw Abort(.badRequest, reason: "folderID must be a uuid")
}
return try await request.labeled { db in
// The folder itself must be visible, or the listing would confirm
// the existence of a folder the caller cannot see.
guard try await NodeModel.find(folderID, on: db) != nil else {
throw Abort(.notFound)
}
let visible = try await NodeModel.query(on: db)
.filter(\.$parentID == folderID)
.all()
return visible.map(Self.describe)
}
}
/// Top-level nodes. Same RLS filtering as any other listing.
func roots(request: Request) async throws -> [NodeResponse] {
try await request.labeled { db in
try await NodeModel.query(on: db)
.filter(\.$parentID == nil)
.all()
.map(Self.describe)
}
}
/// Create a file or folder, with its wrapped key, atomically.
func create(request: Request) async throws -> Response {
let session = try request.session
let input = try request.content.decode(CreateNodeRequest.self)
let node = NodeModel(
parentID: input.parentID,
nameDigest: input.nameDigest,
nameCiphertext: input.nameCiphertext,
isFolder: input.isFolder,
label: session.label,
createdBy: session.principalID,
sizeBytes: input.sizeBytes ?? 0
)
node.blobID = input.blobID
node.contentKey = input.contentKey
// Checked here as well as by the database trigger. The trigger is the
// real guarantee; this exists so the failure arrives as a typed Swift
// error with a usable message rather than a raw constraint violation.
try KeyHierarchy.validate(
nodeID: node.id ?? UUID(),
nodeLabel: session.label,
key: WrappedKey(ciphertext: input.wrappedKey, wrappedTo: .label(session.label))
)
return try await request.labeled { db in
// One transaction: a node without its key is unopenable, and a key
// without its node is a dangling secret.
try await node.create(on: db)
let key = NodeKeyModel(
nodeID: try node.requireID(),
label: session.label,
wrappedKey: input.wrappedKey
)
try await key.create(on: db)
try await AuditEntry(
actorID: session.principalID,
sessionLabel: session.label,
action: "node.create",
nodeID: try node.requireID(),
label: session.label
).write(on: db)
let response = Response(status: .created)
try response.content.encode(Self.describe(node))
return response
}
}
}
@@ -1,178 +0,0 @@
import Fluent
import Vapor
import Foundation
import EnclaveLattice
/// Link shares.
///
/// Everything the server holds here is wrapped under a key it does not have:
/// the client derives it from the label key and a secret carried in the link's
/// fragment, which browsers never transmit. The server's job is to serve that
/// material only to a session that dominates the share's label, and to stop
/// serving it when the share expires.
struct ShareController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let shares = routes.grouped("api", "shares")
shares.post(use: create)
shares.get(":shareID", use: fetch)
shares.get("for", ":nodeID", use: forNode)
shares.delete(":shareID", use: revoke)
}
struct CreateRequest: Content {
let nodeID: UUID
let wrappedContentKey: Data
let wrappedName: Data
/// Public salt for an out-of-band password, when one was set.
let passwordSalt: Data?
let passwordIterations: Int?
/// Hours until it stops working. Omit for no expiry.
let expiresInHours: Int?
}
struct ShareResponse: Content {
let id: UUID
let nodeID: UUID
let classification: Int16
let compartments: [Int]
let wrappedContentKey: Data
let wrappedName: Data
let passwordSalt: Data?
let passwordIterations: Int?
/// So the interface can ask for the password before doing any work.
let needsPassword: Bool
let blobID: UUID?
let sizeBytes: Int64
let expiresAt: Date?
let createdAt: Date?
}
func create(request: Request) async throws -> ShareResponse {
let session = try request.session
let input = try request.content.decode(CreateRequest.self)
return try await request.labeled { db in
// The node must be visible, and RLS decides that. A share for
// something you cannot see would be a way to launder access.
guard let node = try await NodeModel.find(input.nodeID, on: db) else {
throw Abort(.notFound)
}
guard !node.isFolder else {
throw Abort(.badRequest, reason: "Folders cannot be shared by link yet.")
}
// Sharing something below your session label would seal it under
// the wrong label key and produce a link nobody can open.
guard node.label == session.label else {
throw Abort(.conflict, reason:
"Switch to that file's own label before sharing it.")
}
let share = ShareModel()
share.nodeID = input.nodeID
(share.classification, share.compartments) = session.label.columns
share.wrappedContentKey = input.wrappedContentKey
share.wrappedName = input.wrappedName
share.passwordSalt = input.passwordSalt
share.passwordIterations = input.passwordIterations
share.createdBy = session.principalID
share.expiresAt = input.expiresInHours.map {
Date().addingTimeInterval(Double($0) * 3600)
}
try await share.create(on: db)
try await AuditEntry(
actorID: session.principalID, sessionLabel: session.label,
action: "share.create", nodeID: input.nodeID, label: session.label
).write(on: db)
return try Self.describe(share, node: node)
}
}
/// Fetch a share's wrapped material.
///
/// An undominated or expired share is simply not found — the same answer as
/// a link that never existed, so the endpoint says nothing about which.
func fetch(request: Request) async throws -> ShareResponse {
guard let shareID = request.parameters.get("shareID", as: UUID.self) else {
throw Abort(.badRequest, reason: "shareID must be a uuid")
}
return try await request.labeled { db in
guard let share = try await ShareModel.find(shareID, on: db),
let node = try await NodeModel.find(share.nodeID, on: db)
else { throw Abort(.notFound) }
return try Self.describe(share, node: node)
}
}
/// Existing links for a node, so the interface can show and revoke them.
func forNode(request: Request) async throws -> [ShareResponse] {
guard let nodeID = request.parameters.get("nodeID", as: UUID.self) else {
throw Abort(.badRequest, reason: "nodeID must be a uuid")
}
return try await request.labeled { db in
guard let node = try await NodeModel.find(nodeID, on: db) else { throw Abort(.notFound) }
return try await ShareModel.query(on: db)
.filter(\.$nodeID == nodeID).all()
.map { try Self.describe($0, node: node) }
}
}
func revoke(request: Request) async throws -> HTTPStatus {
guard let shareID = request.parameters.get("shareID", as: UUID.self) else {
throw Abort(.badRequest, reason: "shareID must be a uuid")
}
let session = try request.session
return try await request.labeled { db in
guard let share = try await ShareModel.find(shareID, on: db) else { throw Abort(.notFound) }
// The delete policy enforces ownership; this makes the refusal say so.
guard share.createdBy == session.principalID else {
throw Abort(.forbidden, reason: "Only the person who created a link can revoke it.")
}
try await share.delete(on: db)
try await AuditEntry(
actorID: session.principalID, sessionLabel: session.label,
action: "share.revoke", nodeID: share.nodeID, label: share.label
).write(on: db)
return .noContent
}
}
static func describe(_ share: ShareModel, node: NodeModel) throws -> ShareResponse {
ShareResponse(
id: try share.requireID(),
nodeID: share.nodeID,
classification: share.classification,
compartments: share.label.compartments.bits,
wrappedContentKey: share.wrappedContentKey,
wrappedName: share.wrappedName,
passwordSalt: share.passwordSalt,
passwordIterations: share.passwordIterations,
needsPassword: share.passwordSalt != nil,
blobID: node.blobID,
sizeBytes: node.sizeBytes,
expiresAt: share.expiresAt,
createdAt: share.createdAt
)
}
}
final class ShareModel: Model, @unchecked Sendable {
static let schema = "shares"
@ID(key: .id) var id: UUID?
@Field(key: "node_id") var nodeID: UUID
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "wrapped_content_key") var wrappedContentKey: Data
@Field(key: "wrapped_name") var wrappedName: Data
@Field(key: "created_by") var createdBy: UUID
@OptionalField(key: "password_salt") var passwordSalt: Data?
@OptionalField(key: "password_iterations") var passwordIterations: Int?
@OptionalField(key: "expires_at") var expiresAt: Date?
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
init() {}
var label: Label { Label(classification: classification, compartments: compartments) }
}
@@ -1,128 +0,0 @@
import Vapor
/// The public marketing pages.
///
/// Two hostnames, matching how Messenger is deployed: the public site lives on
/// its own domain, and the application on a Flamenet subdomain. Both are
/// configurable, because a self-hoster serves both from wherever they like and
/// a canonical URL pointing at our domain would be wrong on their box.
struct SiteController: RouteCollection {
static var siteURL: String {
Environment.get("ENCLAVE_SITE_URL") ?? "https://flamenetfiles.com"
}
/// Absolute in production so the marketing site can link across hostnames;
/// relative in development, where one process serves both.
static var appURL: String {
Environment.get("ENCLAVE_APP_URL") ?? "/app"
}
/// Where the browser reaches the shared account service. A different origin
/// in production, which is why that service lists allowed origins
/// explicitly rather than reflecting whatever asks.
/// Where the code actually lives. Configurable because a self-hoster
/// running a fork should point "read the code" at their fork, not at ours.
static var sourceURL: String {
Environment.get("ENCLAVE_SOURCE_URL") ?? "https://gitlab.com/paulhitt/flamenet-files"
}
static var accountsURL: String {
Environment.get("ENCLAVE_ACCOUNTS_URL") ?? "http://127.0.0.1:8100"
}
/// Where *this process* reaches the account service, which is not the same
/// address the browser uses and must not be assumed to be.
///
/// `ENCLAVE_ACCOUNTS_URL` is a public address: it goes into a meta tag and
/// into `/api/config`, and it is what a phone or a tab dials. From inside a
/// container the same string is wrong in the most confusing way possible —
/// `http://127.0.0.1:8100` resolves to the container itself and the call
/// fails as "could not reach the account service" while the service is
/// plainly running.
///
/// Defaults to the public one, because for a single-host deployment they
/// genuinely are the same and demanding both would be noise.
static var accountsInternalURL: String {
Environment.get("ENCLAVE_ACCOUNTS_INTERNAL_URL") ?? accountsURL
}
struct PageContext: Encodable {
let title: String
let description: String
let path: String
let siteURL: String
let appURL: String
let accountsURL: String
let sourceURL: String
init(title: String, description: String, path: String) {
self.title = title
self.description = description
self.path = path
self.siteURL = SiteController.siteURL
self.appURL = SiteController.appURL
self.accountsURL = SiteController.accountsURL
self.sourceURL = SiteController.sourceURL
}
}
/// Pages that are pure content: one template each, no handler logic.
static let pages: [String: (title: String, description: String)] = [
"security": (
"Security — Flamenet Files",
"What Flamenet Files protects, what it does not, and where the limits are."
),
"self-hosting": (
"Self-hosting — Flamenet Files",
"Run Flamenet Files on your own server with Docker and Postgres."
),
"compare": (
"Compared with Proton Drive, Google Drive and iCloud — Flamenet Files",
"How Flamenet Files differs from Proton Drive, Google Drive and iCloud Drive, including where it comes off worse."
),
"source": (
"Source — Flamenet Files",
"Flamenet Files is MIT licensed and open to read."
),
]
func boot(routes: any RoutesBuilder) throws {
routes.get { request async throws -> View in
try await request.view.render("landing", PageContext(
title: "Flamenet Files — private, labelled file storage",
description: """
Encrypted in your browser before upload, and every file carries a \
level so people only see what they are cleared for. Free, open \
source, and yours to host.
""",
path: "/"
))
}
for (slug, meta) in Self.pages {
routes.get(.constant(slug)) { request async throws -> View in
try await request.view.render(slug, PageContext(
title: meta.title, description: meta.description, path: "/\(slug)"
))
}
}
// A share link. Only the id reaches the server; the secret lives in the
// fragment, which browsers do not transmit.
routes.get("s", ":shareID") { request async throws -> View in
try await request.view.render("app", PageContext(
title: "Shared file — Flamenet Files",
description: "A file shared with you.",
path: "/s"
))
}
routes.get("app") { request async throws -> View in
try await request.view.render("app", PageContext(
title: "Flamenet Files",
description: "Your files.",
path: "/app"
))
}
}
}
@@ -1,255 +0,0 @@
import Fluent
import Vapor
import Foundation
import EnclaveLattice
/// What this tenant calls its levels and compartments.
///
/// Without this the interface can only show ordinals and bit positions, which
/// is fine for a database and useless to a person deciding where to file
/// something.
struct VocabularyController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let vocab = routes.grouped("api", "vocabulary")
vocab.get(use: vocabulary)
vocab.post("levels", use: nameLevel)
vocab.delete("levels", ":ordinal", use: removeLevel)
vocab.post("compartments", use: nameCompartment)
vocab.delete("compartments", ":bit", use: removeCompartment)
}
// MARK: authorisation
//
// There is no administrator role in this product yet, so this is a proxy
// for one: you may edit the vocabulary if your clearance already reaches
// everything in this tenant. Someone who can see every label is not
// learning anything by renaming one.
//
// It is a stand-in, not a model. The real answer is an administrator role
// with an audit of who changed what, and until that exists this is
// deliberately conservative rather than convenient.
static func requireVocabularyAdmin(_ request: Request, on db: any Database) async throws {
let session = try request.session
let levels = try await ClassificationLevelModel.query(on: db).all()
let compartments = try await CompartmentNameModel.query(on: db).all()
let highest = levels.compactMap(\.id).max() ?? 0
let allBits = Set(compartments.compactMap { $0.id.map(Int.init) })
let clearance = session.clearance.maximum
guard clearance.classification.rawValue >= highest,
Set(clearance.compartments.bits).isSuperset(of: allBits)
else {
throw Abort(.forbidden, reason:
"Editing labels needs a clearance that reaches everything in this tenant.")
}
}
struct Level: Content {
let ordinal: Int16
let name: String
}
struct CompartmentName: Content {
let bit: Int
let name: String
}
struct VocabularyResponse: Content {
let levels: [Level]
let compartments: [CompartmentName]
/// The caller's own bounds, so the interface can offer exactly the
/// labels they may assert and no others.
let maxClassification: Int16
let maxCompartments: [Int]
let minClassification: Int16
/// Whether this caller may edit the vocabulary, so the interface can
/// offer the controls rather than let someone discover a 403.
let canEdit: Bool
}
struct NameLevelRequest: Content {
let ordinal: Int16
let name: String
}
struct NameCompartmentRequest: Content {
let bit: Int
let name: String
}
func vocabulary(request: Request) async throws -> VocabularyResponse {
let session = try request.session
let cleared = Set(session.clearance.maximum.compartments.bits)
return try await request.labeled { db in
let levels = try await ClassificationLevelModel.query(on: db)
.sort(\.$id, .ascending).all()
.map { Level(ordinal: $0.id ?? 0, name: $0.name) }
// Filtered to the caller's clearance. Naming a compartment they are
// not in would advertise that it exists.
let compartments = try await CompartmentNameModel.query(on: db).all()
.compactMap { row -> CompartmentName? in
guard let bit = row.id.map(Int.init), cleared.contains(bit) else { return nil }
return CompartmentName(bit: bit, name: row.name)
}
.sorted { $0.bit < $1.bit }
let canEdit = (try? await Self.requireVocabularyAdmin(request, on: db)) != nil
return VocabularyResponse(
levels: levels,
compartments: compartments,
maxClassification: session.clearance.maximum.classification.rawValue,
maxCompartments: session.clearance.maximum.compartments.bits,
minClassification: session.clearance.minimum.classification.rawValue,
canEdit: canEdit
)
}
}
}
extension VocabularyController {
/// Name or rename a classification level.
func nameLevel(request: Request) async throws -> HTTPStatus {
let input = try request.content.decode(NameLevelRequest.self)
let name = try Self.validate(name: input.name)
guard input.ordinal >= 0 else {
throw Abort(.badRequest, reason: "A level's ordinal cannot be negative.")
}
try Self.requireWithinClearance(request, classification: input.ordinal, compartment: nil)
return try await request.labeled { db in
try await Self.requireVocabularyAdmin(request, on: db)
if let existing = try await ClassificationLevelModel.find(input.ordinal, on: db) {
existing.name = name
try await existing.update(on: db)
return .ok
}
try await ClassificationLevelModel(ordinal: input.ordinal, name: name).create(on: db)
return .created
}
}
/// Remove a level's name.
///
/// Refused while anything is filed at it. Deleting the name would not
/// delete the files — it would leave them showing a bare ordinal, which is
/// how a label stops meaning anything.
func removeLevel(request: Request) async throws -> HTTPStatus {
guard let ordinal = request.parameters.get("ordinal", as: Int16.self) else {
throw Abort(.badRequest, reason: "ordinal must be a number")
}
return try await request.labeled { db in
try await Self.requireVocabularyAdmin(request, on: db)
let inUse = try await NodeModel.query(on: db)
.filter(\.$classification == ordinal).count()
guard inUse == 0 else {
throw Abort(.conflict, reason:
"\(inUse) item\(inUse == 1 ? " is" : "s are") filed at this level. "
+ "Move or delete them first.")
}
guard let level = try await ClassificationLevelModel.find(ordinal, on: db) else {
throw Abort(.notFound)
}
try await level.delete(on: db)
return .noContent
}
}
func nameCompartment(request: Request) async throws -> HTTPStatus {
let input = try request.content.decode(NameCompartmentRequest.self)
let name = try Self.validate(name: input.name)
guard (0...63).contains(input.bit) else {
throw Abort(.badRequest, reason: "An area's number must be between 0 and 63.")
}
try Self.requireWithinClearance(request, classification: nil, compartment: input.bit)
return try await request.labeled { db in
try await Self.requireVocabularyAdmin(request, on: db)
let bit = Int16(input.bit)
if let existing = try await CompartmentNameModel.find(bit, on: db) {
existing.name = name
try await existing.update(on: db)
return .ok
}
try await CompartmentNameModel(bit: bit, name: name).create(on: db)
return .created
}
}
func removeCompartment(request: Request) async throws -> HTTPStatus {
guard let bit = request.parameters.get("bit", as: Int.self), (0...63).contains(bit) else {
throw Abort(.badRequest, reason: "area number must be between 0 and 63")
}
return try await request.labeled { db in
try await Self.requireVocabularyAdmin(request, on: db)
// A bitmask test, because a file carries the whole set at once.
let mask = Compartments(bits: [bit]).postgresBitPattern
let inUse = try await NodeModel.query(on: db).all()
.filter { $0.compartments & mask != 0 }.count
guard inUse == 0 else {
throw Abort(.conflict, reason:
"\(inUse) item\(inUse == 1 ? " is" : "s are") in this area. Move or delete them first.")
}
guard let compartment = try await CompartmentNameModel.find(Int16(bit), on: db) else {
throw Abort(.notFound)
}
try await compartment.delete(on: db)
return .noContent
}
}
/// Refuse to create a label the caller could not then see.
///
/// Naming a level above your clearance, or an area you are not in, makes it
/// invisible to you the moment it exists — and because editing requires
/// reaching everything in the tenant, it also revokes your own ability to
/// edit. You would be locked out by your own change, with the offending
/// label hidden from you and no way to undo it in the interface.
///
/// So the rule is simply: you may only name what you can already reach.
static func requireWithinClearance(_ request: Request, classification: Int16?, compartment: Int?) throws {
let clearance = try request.session.clearance.maximum
if let classification, classification > clearance.classification.rawValue {
throw Abort(.forbidden, reason:
"You can't name a level above your own clearance — it would be invisible to you.")
}
if let compartment, !clearance.compartments.bits.contains(compartment) {
throw Abort(.forbidden, reason:
"You can't name an area you're not in — it would be invisible to you.")
}
}
static func validate(name: String) throws -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard (1...48).contains(trimmed.count) else {
throw Abort(.badRequest, reason: "A name must be 1 to 48 characters.")
}
// Names are rendered as text, never as markup, but a control character
// in a label is a mistake either way.
guard !trimmed.contains(where: { $0.isNewline || $0.unicodeScalars.contains { s in s.value < 0x20 } }) else {
throw Abort(.badRequest, reason: "A name cannot contain control characters.")
}
return trimmed
}
}
final class ClassificationLevelModel: Model, @unchecked Sendable {
static let schema = "classification_levels"
@ID(custom: "ordinal", generatedBy: .user) var id: Int16?
@Field(key: "name") var name: String
init() {}
init(ordinal: Int16, name: String) { self.id = ordinal; self.name = name }
}
final class CompartmentNameModel: Model, @unchecked Sendable {
static let schema = "compartment_names"
@ID(custom: "bit", generatedBy: .user) var id: Int16?
@Field(key: "name") var name: String
init() {}
init(bit: Int16, name: String) { self.id = bit; self.name = name }
}
@@ -1,74 +0,0 @@
import Foundation
import Vapor
import EnclaveLattice
/// The one thing this process asks the account service.
///
/// A tenant role has no grant on the account schema, deliberately, so the file
/// server cannot see clearances at all. When it needs to know whether somebody
/// is cleared — which is only when a label key is being handed to them — it asks.
///
/// The caller's own bearer token is forwarded rather than a service credential.
/// That keeps the answer bounded by what the caller could already learn: the
/// account service refuses to answer about a label the caller does not hold, and
/// gives one indistinguishable 404 for an unknown handle, an uncleared account
/// and an unenrolled one.
enum AccountsLookup {
struct Resolved: Content {
let pseudonym: UUID
let publicKey: Data
}
private struct CheckBody: Content {
let handle: String
let classification: Int16
let compartments: [Int]
}
static func clearanceCheck(handle: String, label: Label, on request: Request) async throws
-> Resolved {
guard let bearer = request.headers.bearerAuthorization?.token else {
throw Abort(.unauthorized)
}
// The internal address, not the one handed to browsers. See
// `SiteController.accountsInternalURL`.
let configured = SiteController.accountsInternalURL
let base = configured.hasSuffix("/") ? String(configured.dropLast()) : configured
var headers = HTTPHeaders()
headers.bearerAuthorization = .init(token: bearer)
let response: ClientResponse
do {
response = try await request.client.post(
URI(string: base + "/clearance/check"), headers: headers
) { outbound in
try outbound.content.encode(CheckBody(
handle: handle,
classification: label.classification.rawValue,
compartments: label.compartments.bits
))
}
} catch {
request.logger.error("account service unreachable",
metadata: ["error": .string(String(describing: error))])
throw Abort(.badGateway, reason: "Could not reach the account service.")
}
switch response.status {
case .ok:
return try response.content.decode(Resolved.self)
case .notFound:
// Deliberately the same message the account service uses. Repeating
// its ambiguity here rather than inventing a more specific one is
// the whole point of that endpoint's shape.
throw Abort(.notFound, reason: "No such account, or they are not cleared for this area.")
case .forbidden:
throw Abort(.forbidden, reason: "That area exceeds your clearance.")
default:
request.logger.error("clearance check failed",
metadata: ["status": .string(response.status.description)])
throw Abort(.badGateway, reason: "The account service could not answer.")
}
}
}
@@ -1,34 +0,0 @@
import Fluent
import SQLKit
import Foundation
import EnclaveLattice
/// An append-only audit record.
///
/// Written through raw SQL rather than a Fluent model on purpose: the table has
/// no UPDATE or DELETE grant, and modelling it as a mutable entity would invite
/// code that assumes otherwise. Audit rows carry the label of the thing they
/// describe, so the log cannot become the leak.
struct AuditEntry {
let actorID: UUID
let sessionLabel: Label
let action: String
let nodeID: UUID?
let label: Label
var detail: String = "{}"
func write(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
let session = sessionLabel.columns
let object = label.columns
try await sql.raw("""
INSERT INTO audit_log
(actor_id, session_class, session_comp, action,
node_id, classification, compartments, detail)
VALUES
(\(bind: actorID), \(bind: session.classification), \(bind: session.compartments),
\(bind: action), \(bind: nodeID), \(bind: object.classification),
\(bind: object.compartments), \(bind: detail)::jsonb)
""").run()
}
}
@@ -1,87 +0,0 @@
import Foundation
import Vapor
/// Ciphertext blobs on local disk.
///
/// Deliberately dumb: the bytes are already encrypted client-side and the
/// `blobs` row carries the label, so access control happens in Postgres and
/// this layer only needs to not lose files. An object-store backend (S3, B2)
/// would slot in behind the same two methods.
struct BlobStore {
let root: URL
/// Keys are generated here, never accepted from a client, and validated on
/// the way back out anyway -- a traversal sequence reaching this from a
/// corrupted row must not escape the blob directory.
private static let allowed = Set("0123456789abcdef/")
static let hexBytes = 32
/// Structure, not a magic length: three lowercase-hex components of 2, 2
/// and 60 characters. Nothing that satisfies this can traverse a directory.
static func validate(objectKey: String) throws {
let parts = objectKey.split(separator: "/", omittingEmptySubsequences: false)
guard parts.count == 3,
parts[0].count == 2, parts[1].count == 2, parts[2].count == 60,
objectKey.allSatisfy(allowed.contains)
else {
throw Abort(.internalServerError, reason: "malformed blob object key")
}
}
func write(_ data: Data) throws -> String {
var hex = ""
for byte in (0..<32).map({ _ in UInt8.random(in: 0...255) }) {
hex += String(format: "%02x", byte)
}
// Two levels of fan-out so no directory grows past a few thousand files.
let objectKey = "\(hex.prefix(2))/\(hex.dropFirst(2).prefix(2))/\(hex.dropFirst(4))"
try Self.validate(objectKey: objectKey)
let url = root.appendingPathComponent(objectKey)
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true
)
try data.write(to: url, options: .atomic)
return objectKey
}
func read(_ objectKey: String) throws -> Data {
try Self.validate(objectKey: objectKey)
return try Data(contentsOf: root.appendingPathComponent(objectKey))
}
/// Remove one object.
///
/// ⚠️ Validated exactly as `read` and `write` are, and for the sharper
/// reason: this one deletes. A malformed key reaching here from a corrupted
/// row must not be able to escape the blob directory and take something
/// else with it.
///
/// A key that is already gone is not an error. The sweep deletes the row
/// first and the object second, so a retry after a crash between the two
/// finds no file and should carry on rather than fail for ever on a blob
/// nobody can reference any more.
func remove(_ objectKey: String) throws {
try Self.validate(objectKey: objectKey)
let url = root.appendingPathComponent(objectKey)
guard FileManager.default.fileExists(atPath: url.path) else { return }
try FileManager.default.removeItem(at: url)
}
}
struct BlobStoreKey: StorageKey {
typealias Value = BlobStore
}
extension Application {
var blobs: BlobStore {
get {
guard let store = storage[BlobStoreKey.self] else {
fatalError("blob store not configured")
}
return store
}
set { storage[BlobStoreKey.self] = newValue }
}
}
@@ -1,107 +0,0 @@
import EnclaveAccess
import Fluent
import Foundation
import Logging
import SQLKit
/// Drops couriered transfers once they have landed, and says so at a level
/// somebody can alert on.
///
/// 🔴 **`.notice`, not `.info`.** The relay learned this the expensive way: its
/// sweep logged at `.info` while production ran at `error`, so the line meant
/// for alerting never appeared and the only way to know the sweeper was alive
/// was to query the database and find nothing past a window. A component whose
/// whole job is deleting things has to be able to say what it deleted.
///
/// ⚠️ The decision of WHAT to drop is not here — it is `CourierSweep`, which
/// has no database behind it and is tested on its own. This file is the part
/// that talks to Postgres and the blob store, and it deliberately holds no
/// policy of its own beyond the order of operations below.
struct CourierRetention: Sendable {
let db: any Database
let blobs: BlobStore
let logger: Logger
let retention: CourierSweep.Retention
static let interval: Duration = .seconds(3600)
func run() async {
while !Task.isCancelled {
do {
let dropped = try await sweepOnce(now: Date())
if dropped > 0 {
logger.notice("courier sweep", metadata: [
"dropped": .stringConvertible(dropped),
])
}
} catch {
// Logged, never swallowed: a sweep that quietly stops turns
// courier mode back into permanent storage without anyone
// being told the promise changed.
logger.error("courier sweep failed", metadata: [
"error": .string("\(error)"),
])
}
try? await Task.sleep(for: Self.interval)
}
}
/// One pass. Returns how many transfers were dropped.
@discardableResult
func sweepOnce(now: Date) async throws -> Int {
guard let sql = db as? any SQLDatabase else { return 0 }
// Only courier rows are even fetched. `CourierSweep.verdict` refuses to
// drop a `stored` blob anyway, but not selecting them means a mistake
// in this file cannot reach one either.
struct Row: Decodable {
let id: UUID
let object_key: String
let created_at: Date
let intended: Int
let collected: Int
let completed_at: Date?
}
let rows = try await sql.raw("""
SELECT b.id, b.object_key, s.created_at,
s.intended::int AS intended,
s.collected::int AS collected,
s.completed_at
FROM blob_transfer_state s
JOIN blobs b ON b.id = s.id
WHERE s.mode = 'courier'
""").all(decoding: Row.self)
var dropped = 0
for row in rows {
let transfer = CourierSweep.Transfer(
mode: .courier,
createdAt: row.created_at,
intended: row.intended,
collected: row.collected,
completedAt: row.completed_at)
guard case .drop(let why) = CourierSweep.verdict(
transfer, retention: retention, now: now) else { continue }
// 🔴 Row first, then the file — the same order the upload path
// uses in reverse, and for the same reason it gives: a crash
// between the two leaves an orphaned object, which is collectable,
// rather than a row pointing at a file that is gone, which reads
// to every caller as data loss.
try await sql.raw("DELETE FROM blobs WHERE id = \(bind: row.id)").run()
do {
try blobs.remove(row.object_key)
} catch {
logger.notice("courier blob row dropped, object left behind", metadata: [
"object": .string(row.object_key),
"reason": .string(why.rawValue),
"error": .string("\(error)"),
])
}
dropped += 1
}
return dropped
}
}
@@ -1,52 +0,0 @@
import Fluent
import SQLKit
import Vapor
import EnclaveLattice
/// The only sanctioned path to the database.
///
/// Every query must run inside a transaction that has pinned the session label
/// into transaction-local settings, because that is what the RLS policies read.
/// Three things make this correct:
///
/// 1. `SET LOCAL` semantics are transaction-scoped, so a pooled connection
/// cannot carry one user's label into another user's request.
/// 2. `set_config(name, value, true)` is the parameterisable form. `SET LOCAL`
/// itself takes no bind parameters, so building it by interpolation would be
/// an injection site; this avoids that entirely.
/// 3. Forgetting the label fails closed -- unset settings read as NULL, every
/// dominance test evaluates to NULL, and RLS treats NULL as false. But the
/// symptom is an empty result set rather than an error, which is a miserable
/// thing to debug, so `session` throws if the middleware never ran.
extension Request {
func labeled<T>(_ body: @escaping @Sendable (any Database) async throws -> T) async throws -> T
where T: Sendable {
let session = try self.session
return try await self.db.transaction { database in
guard let sql = database as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "labeled access requires a SQL database")
}
try await sql.raw("""
SELECT set_config('enclave.classification', \(bind: String(session.label.classification.rawValue)), true),
set_config('enclave.compartments', \(bind: String(session.label.compartments.postgresBitPattern)), true),
set_config('enclave.principal', \(bind: session.principalID.uuidString), true)
""").run()
return try await body(database)
}
}
}
extension Label {
/// Split form for storage. Kept next to the wrapper so the two encodings of
/// a label -- GUC and column -- never drift apart.
var columns: (classification: Int16, compartments: Int64) {
(classification.rawValue, compartments.postgresBitPattern)
}
init(classification: Int16, compartments: Int64) {
self.init(
classification: Classification(classification),
compartments: Compartments(postgresBitPattern: compartments)
)
}
}
@@ -1,52 +0,0 @@
import Fluent
import SQLKit
import Vapor
/// Refuse to serve traffic on a connection that can ignore row-level security.
///
/// This is the single most dangerous misconfiguration available to a
/// self-hoster. Postgres superusers bypass RLS unconditionally, and so does any
/// role holding BYPASSRLS -- FORCE ROW LEVEL SECURITY does not save you. The
/// failure is silent and looks exactly like everything working: queries return
/// rows, the app is fast, and every label is being ignored.
///
/// Pointing DATABASE_URL at the postgres superuser is the obvious way to get
/// here, and it is what most quick-start compose files do. So the server checks
/// its own role at boot and refuses rather than serving unlabelled data.
enum RLSGuard {
private struct RoleFacts: Decodable {
let is_superuser: Bool
let bypasses_rls: Bool
let role_name: String
}
static func assertRowLevelSecurityApplies(_ app: Application) async throws {
guard let sql = app.db as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "expected a SQL database")
}
let facts = try await sql.raw("""
SELECT current_user::text AS role_name,
current_setting('is_superuser') = 'on' AS is_superuser,
COALESCE((SELECT rolbypassrls FROM pg_roles
WHERE rolname = current_user), false) AS bypasses_rls
""").first(decoding: RoleFacts.self)
guard let facts else {
throw Abort(.internalServerError, reason: "could not determine database role")
}
if facts.is_superuser || facts.bypasses_rls {
let why = facts.is_superuser ? "is a superuser" : "holds BYPASSRLS"
app.logger.critical("""
Refusing to start: database role '\(facts.role_name)' \(why), so every \
row-level security policy is ignored and labels are not enforced. Point \
DATABASE_URL at the per-tenant role (tenant_<slug>) instead of the owner \
or superuser. See SELF-HOSTING.md.
""")
throw Abort(.internalServerError, reason: "database role can bypass row-level security")
}
app.logger.info("row-level security applies to role '\(facts.role_name)'")
}
}
@@ -1,166 +0,0 @@
import Fluent
import SQLKit
import Foundation
import Vapor
import EnclaveSQL
/// Schema installation.
///
/// Fluent's schema builder cannot express row-level security policies, FORCE
/// ROW LEVEL SECURITY, triggers, or grants -- which is most of what protects
/// this system. So the DDL lives in .sql files and these migrations execute it
/// verbatim. Wrapping it in Fluent migrations rather than shelling out to psql
/// keeps `_fluent_migrations` as the version record, and because each tenant
/// has its own search_path that record lands per-tenant automatically.
enum TenantSchema {
/// Slugs become schema and role identifiers, which cannot be parameterised
/// in DDL. Validate rather than escape: anything outside this alphabet is
/// rejected instead of quoted.
static func validate(slug: String) throws {
let allowed = Set("abcdefghijklmnopqrstuvwxyz0123456789_")
guard (2...39).contains(slug.count),
let first = slug.first, first.isLowercase, first.isLetter,
slug.allSatisfy(allowed.contains)
else {
throw Abort(.badRequest, reason: "tenant slug '\(slug)' is not a safe identifier")
}
}
/// Execute a schema file one statement at a time.
///
/// Postgres's extended query protocol refuses more than one command per
/// statement, so a schema file cannot be sent whole. `SQLScript` does the
/// splitting, respecting the dollar-quoted function bodies this schema is
/// full of.
static func execute(_ script: String, on sql: any SQLDatabase) async throws {
for statement in SQLScript.statements(script) {
try await sql.raw(.init(statement)).run()
}
}
static func sql(named name: String) throws -> String {
guard let url = Bundle.module.url(forResource: "SQL/\(name)", withExtension: "sql") else {
throw Abort(.internalServerError, reason: "missing bundled SQL resource \(name).sql")
}
return try String(contentsOf: url, encoding: .utf8)
}
}
/// Installs the shared `enclave` helpers and the control-plane registry.
struct InstallSharedSchema: AsyncMigration {
var name: String { "InstallSharedSchema" }
func prepare(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await TenantSchema.execute(try TenantSchema.sql(named: "001_shared"), on: sql)
}
func revert(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw("DROP SCHEMA IF EXISTS enclave CASCADE").run()
try await sql.raw("DROP SCHEMA IF EXISTS enclave_control CASCADE").run()
}
}
/// Applies one incremental script to one tenant's schema.
///
/// The template in `002_tenant_template.sql` runs exactly once per tenant and
/// never again, so a feature that adds a table or a policy reached new
/// deployments and no existing one. Share links shipped that way; a database
/// created before them simply had no `shares` table, and the failure surfaced
/// as a 500 with nothing to say about migrations.
///
/// Each bundled script under `SQL/tenant/` becomes its own migration, named for
/// the tenant and the script, so Fluent's own ledger decides what has run. There
/// is no second bookkeeping table to drift.
///
/// The template stays frozen as the original baseline and incremental changes
/// live only here, so there is one place to change and nothing to keep in sync.
/// A fresh tenant runs the template and then every script, which reaches the
/// same state an upgraded one does — by the same route, which is the point.
///
/// ⚠️ **Scripts must still be idempotent**, because a script may be re-run
/// against a schema that a later template revision already covers. `DROP POLICY
/// IF EXISTS` before `CREATE POLICY`, `CREATE TABLE IF NOT EXISTS`, and so on.
struct ApplyTenantScript: AsyncMigration {
let slug: String
/// Bare filename without extension, e.g. `003_delegated_grants`.
let script: String
var name: String { "TenantScript.\(slug).\(script)" }
func prepare(on database: any Database) async throws {
try TenantSchema.validate(slug: slug)
guard let sql = database as? any SQLDatabase else { return }
let body = try TenantSchema.sql(named: "tenant/\(script)")
.replacingOccurrences(of: ":schema", with: "\"t_\(slug)\"")
.replacingOccurrences(of: ":role", with: "\"tenant_\(slug)\"")
try await TenantSchema.execute(body, on: sql)
}
/// Deliberately not reversible. These scripts add policies and tables that
/// later ones depend on, and a generic "undo" would be a guess. Roll back by
/// restoring a backup, which is the only honest answer for DDL.
func revert(on database: any Database) async throws {}
/// Every tenant script, in the order they must run.
///
/// Listed here rather than discovered from the bundle. Enumerating
/// resources is not portable — the plural `Bundle.urls(...)` does not exist
/// on Linux's Foundation, which is where this actually runs — and an
/// explicit list is better regardless: the set and the order are reviewable
/// in a diff instead of depending on how a directory happens to sort.
///
/// ⚠️ Append only, and never reorder or rename. Each entry becomes a
/// migration name that Fluent records; renaming one makes it run again.
static let all: [String] = [
"003_delegated_grants",
"004_revocation",
"005_courier_transfer",
]
}
/// Installs one tenant's schema, policies, and grants.
struct InstallTenantSchema: AsyncMigration {
let slug: String
var name: String { "InstallTenantSchema.\(slug)" }
private var schemaName: String { "t_\(slug)" }
private var roleName: String { "tenant_\(slug)" }
func prepare(on database: any Database) async throws {
try TenantSchema.validate(slug: slug)
guard let sql = database as? any SQLDatabase else { return }
// The role must exist before the template's GRANTs run.
try await sql.raw("SELECT enclave.ensure_role(\(bind: roleName))").run()
let template = try TenantSchema.sql(named: "002_tenant_template")
.replacingOccurrences(of: ":schema", with: "\"\(schemaName)\"")
.replacingOccurrences(of: ":role", with: "\"\(roleName)\"")
try await TenantSchema.execute(template, on: sql)
// With this set, the worker process never names its own schema: Fluent
// models declare plain table names and resolve into the right one.
try await sql.raw("""
ALTER ROLE \(unsafeRaw: "\"\(roleName)\"")
SET search_path = \(unsafeRaw: "\"\(schemaName)\""), enclave
""").run()
// The worker connects as this role, so it needs LOGIN. Deliberately not
// a superuser and never granted BYPASSRLS: both would make every policy
// installed above inert. `assertRowLevelSecurityApplies` checks at boot.
if let password = Environment.get("ENCLAVE_TENANT_PASSWORD"), !password.isEmpty {
try await sql.raw(
"SELECT enclave.set_role_login(\(bind: roleName), \(bind: password))"
).run()
}
}
func revert(on database: any Database) async throws {
try TenantSchema.validate(slug: slug)
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw("DROP SCHEMA IF EXISTS \(unsafeRaw: "\"\(schemaName)\"") CASCADE").run()
}
}
@@ -1,129 +0,0 @@
import Fluent
import Foundation
import EnclaveLattice
/// A file or folder.
///
/// Table names are unqualified: the tenant role's search_path resolves them
/// into that tenant's schema, so nothing here is tenant-aware.
final class NodeModel: Model, @unchecked Sendable {
static let schema = "nodes"
@ID(key: .id) var id: UUID?
@OptionalField(key: "parent_id") var parentID: UUID?
/// HMAC(folder_key, normalise(name)), computed client-side. The server
/// never sees a filename in the clear.
@Field(key: "name_digest") var nameDigest: Data
@Field(key: "name_ciphertext") var nameCiphertext: Data
@Field(key: "is_folder") var isFolder: Bool
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@OptionalField(key: "blob_id") var blobID: UUID?
@OptionalField(key: "content_key") var contentKey: Data?
@Field(key: "size_bytes") var sizeBytes: Int64
@Field(key: "created_by") var createdBy: UUID
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
@Timestamp(key: "updated_at", on: .update) var updatedAt: Date?
@Timestamp(key: "deleted_at", on: .delete) var deletedAt: Date?
init() {}
init(parentID: UUID?, nameDigest: Data, nameCiphertext: Data,
isFolder: Bool, label: Label, createdBy: UUID, sizeBytes: Int64 = 0) {
self.parentID = parentID
self.nameDigest = nameDigest
self.nameCiphertext = nameCiphertext
self.isFolder = isFolder
(self.classification, self.compartments) = label.columns
self.createdBy = createdBy
self.sizeBytes = sizeBytes
}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
/// A node's content key, wrapped to its LABEL key.
final class NodeKeyModel: Model, @unchecked Sendable {
static let schema = "node_keys"
@ID(custom: "node_id", generatedBy: .user) var id: UUID?
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "generation") var generation: Int
@Field(key: "wrapped_key") var wrappedKey: Data
init() {}
init(nodeID: UUID, label: Label, wrappedKey: Data, generation: Int = 1) {
self.id = nodeID
(self.classification, self.compartments) = label.columns
self.wrappedKey = wrappedKey
self.generation = generation
}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
/// A label key wrapped to one principal's identity key.
final class LabelKeyGrantModel: Model, @unchecked Sendable {
static let schema = "label_key_grants"
@ID(key: .id) var id: UUID?
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "principal_id") var principalID: UUID
@Field(key: "generation") var generation: Int
@Field(key: "wrapped_key") var wrappedKey: Data
@Timestamp(key: "granted_at", on: .create) var grantedAt: Date?
init() {}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
/// A stored ciphertext blob. The row carries the label; the bytes live on disk.
final class BlobModel: Model, @unchecked Sendable {
static let schema = "blobs"
@ID(key: .id) var id: UUID?
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "size_bytes") var sizeBytes: Int64
@Field(key: "object_key") var objectKey: String
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
init() {}
init(label: Label, sizeBytes: Int64, objectKey: String) {
(self.classification, self.compartments) = label.columns
self.sizeBytes = sizeBytes
self.objectKey = objectKey
}
}
/// Who granted a label key to whom.
///
/// Not for the granter's benefit. This is the record that answers how somebody
/// came to hold a key, which is the first question asked after anything goes
/// wrong — and without it the answer is a shrug.
final class GrantAuditModel: Model, @unchecked Sendable {
static let schema = "grant_audit"
@ID(key: .id) var id: UUID?
@Field(key: "granted_by") var grantedBy: UUID
@Field(key: "granted_to") var grantedTo: UUID
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Timestamp(key: "granted_at", on: .create) var grantedAt: Date?
init() {}
}
-103
View File
@@ -1,103 +0,0 @@
-- Shared objects. Installed once per database, owned by enclave_owner.
-- Tenant workers get EXECUTE on the helpers and nothing else here.
CREATE SCHEMA IF NOT EXISTS enclave;
CREATE SCHEMA IF NOT EXISTS enclave_control;
-- Session label, read from transaction-local GUCs.
--
-- The `true` second argument makes a missing setting return NULL rather than
-- raise. NULL then makes every dominance test NULL, which RLS treats as false:
-- a worker that forgets to set its session label sees zero rows. Fail-closed by
-- construction, but it does mean "empty result set" is the symptom of a wiring
-- bug -- the Vapor middleware asserts the GUCs are present for that reason.
CREATE OR REPLACE FUNCTION enclave.session_classification() RETURNS smallint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.classification', true), '')::smallint $$;
CREATE OR REPLACE FUNCTION enclave.session_compartments() RETURNS bigint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.compartments', true), '')::bigint $$;
-- A ⊒ B: at least as high on the ladder AND a superset of compartments.
-- Compartments are a signed bigint here; bit 63 makes the value negative, which
-- is harmless because `&` is a pure bit operation. The Swift side must convert
-- with Int64(bitPattern:) rather than a checked cast.
CREATE OR REPLACE FUNCTION enclave.dominates(
subject_class smallint, subject_comp bigint,
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$$ SELECT subject_class >= object_class AND (subject_comp & object_comp) = object_comp $$;
-- Convenience wrapper used by every read policy.
CREATE OR REPLACE FUNCTION enclave.session_dominates(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.dominates(
enclave.session_classification(), enclave.session_compartments(),
object_class, object_comp) $$;
CREATE OR REPLACE FUNCTION enclave.session_label_is(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.session_classification() = object_class
AND enclave.session_compartments() = object_comp $$;
-- Control plane. Lives outside every tenant schema; tenant roles cannot read it.
CREATE TABLE IF NOT EXISTS enclave_control.tenants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug text UNIQUE NOT NULL CHECK (slug ~ '^[a-z][a-z0-9-]{1,38}$'),
schema_name text UNIQUE NOT NULL,
db_role text UNIQUE NOT NULL,
status text NOT NULL DEFAULT 'provisioning',
created_at timestamptz NOT NULL DEFAULT now()
);
-- Tenants name their own ladder; the lattice code only sees ordinals.
CREATE TABLE IF NOT EXISTS enclave_control.classification_levels (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
ordinal smallint NOT NULL CHECK (ordinal >= 0),
name text NOT NULL,
PRIMARY KEY (tenant_id, ordinal),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.compartments (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
bit smallint NOT NULL CHECK (bit BETWEEN 0 AND 63),
name text NOT NULL,
PRIMARY KEY (tenant_id, bit),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.principals (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
email text NOT NULL,
max_class smallint NOT NULL,
max_comp bigint NOT NULL DEFAULT 0,
min_class smallint NOT NULL DEFAULT 0,
min_comp bigint NOT NULL DEFAULT 0,
UNIQUE (tenant_id, email)
);
-- Role management. DDL cannot take bind parameters, so these wrap format()'s
-- %I/%L quoting -- the identifier and the password are escaped by Postgres
-- rather than by string-building in the application.
CREATE OR REPLACE FUNCTION enclave.ensure_role(role_name text) RETURNS void
LANGUAGE plpgsql AS
$fn$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = role_name) THEN
EXECUTE format('CREATE ROLE %I NOLOGIN', role_name);
END IF;
END
$fn$;
CREATE OR REPLACE FUNCTION enclave.set_role_login(role_name text, role_password text)
RETURNS void LANGUAGE plpgsql AS
$fn$
BEGIN
EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', role_name, role_password);
END
$fn$;
@@ -1,401 +0,0 @@
-- Per-tenant schema. The control plane runs this once per tenant with :schema
-- and :role substituted, then runs Fluent's migrations against it.
--
-- The key move: the tenant's role gets a fixed search_path, so the per-tenant
-- worker process never names its own schema. Fluent models declare plain table
-- names ("nodes", "blobs") and resolve into the right schema automatically --
-- the tenant axis is completely invisible to application code.
--
-- ALTER ROLE :role SET search_path = :schema, enclave;
--
-- Tables are owned by enclave_owner, not by the tenant role, so RLS applies
-- normally. FORCE ROW LEVEL SECURITY is set anyway: an ownership change during
-- some future migration would otherwise silently disable every policy.
CREATE SCHEMA :schema;
REVOKE ALL ON SCHEMA :schema FROM PUBLIC;
GRANT USAGE ON SCHEMA :schema TO :role;
GRANT USAGE ON SCHEMA enclave TO :role;
-- ---------------------------------------------------------------- nodes
-- Files and folders in one adjacency-list tree.
CREATE TABLE :schema.nodes (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
parent_id uuid REFERENCES :schema.nodes(id) ON DELETE RESTRICT,
-- Names are ciphertext. name_digest = HMAC(folder_key, normalise(name)),
-- computed client-side: deterministic enough to constrain and index, but
-- keyed per folder so the server can neither invert it nor correlate names
-- across folders.
name_digest bytea NOT NULL,
name_ciphertext bytea NOT NULL,
is_folder boolean NOT NULL,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
blob_id uuid,
-- The content key for this revision, wrapped to this node's key. Stored
-- beside the node because it is useless without the node key, which is
-- itself wrapped to the label key.
content_key bytea,
size_bytes bigint NOT NULL DEFAULT 0,
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
-- Polyinstantiation: the same name may exist once per label under a parent, so
-- a low-cleared user creating "Q3 Forecast" never collides with -- and never
-- learns about -- a higher-labeled file of the same name. A plain UNIQUE(name)
-- here would turn the constraint violation into an existence oracle.
CREATE UNIQUE INDEX nodes_polyinstantiated_name
ON :schema.nodes (parent_id, name_digest, classification, compartments)
WHERE deleted_at IS NULL;
-- Every RLS predicate filters on the label pair; keep it leading.
CREATE INDEX nodes_label ON :schema.nodes (classification, compartments);
CREATE INDEX nodes_parent ON :schema.nodes (parent_id) WHERE deleted_at IS NULL;
ALTER TABLE :schema.nodes ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.nodes FORCE ROW LEVEL SECURITY;
CREATE POLICY nodes_read ON :schema.nodes FOR SELECT
USING (enclave.session_dominates(classification, compartments));
-- Strong tranquility: you may only create at exactly your session label.
CREATE POLICY nodes_insert ON :schema.nodes FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
-- USING gates which rows you may touch; WITH CHECK forbids relabelling by
-- UPDATE. Moving a node between labels is a regrade, never a plain write.
CREATE POLICY nodes_update ON :schema.nodes FOR UPDATE
USING (enclave.session_label_is(classification, compartments))
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT, UPDATE ON :schema.nodes TO :role;
-- Tree invariant: a child must dominate its parent, or nobody cleared for the
-- child could traverse to it. The parent lookup runs under the caller's RLS, so
-- an invisible parent is indistinguishable from a missing one -- also correct.
CREATE FUNCTION :schema.enforce_tree_invariant() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE p_class smallint; p_comp bigint;
BEGIN
IF NEW.parent_id IS NULL THEN RETURN NEW; END IF;
SELECT classification, compartments INTO p_class, p_comp
FROM nodes WHERE id = NEW.parent_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'parent not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NOT enclave.dominates(NEW.classification, NEW.compartments, p_class, p_comp) THEN
RAISE EXCEPTION 'child label must dominate parent label'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER nodes_tree_invariant
BEFORE INSERT OR UPDATE OF parent_id, classification, compartments
ON :schema.nodes FOR EACH ROW EXECUTE FUNCTION :schema.enforce_tree_invariant();
-- ---------------------------------------------------------------- blobs
-- Ciphertext blobs. NOT content-addressed, and deliberately not deduplicated.
--
-- Dedup would need convergent encryption (key derived from plaintext), which
-- gives the server a confirmation-of-file oracle: encrypt a candidate, see
-- whether the ciphertext already exists, and learn that some user holds it.
-- That is a leak in any zero-knowledge system, and across labels it is also the
-- covert channel that lets a low-cleared user probe for high-labeled content.
-- Every upload is a distinct blob under a distinct key. Deliberate cost.
CREATE TABLE :schema.blobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
size_bytes bigint NOT NULL,
object_key text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE :schema.blobs ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.blobs FORCE ROW LEVEL SECURITY;
CREATE POLICY blobs_read ON :schema.blobs FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY blobs_insert ON :schema.blobs FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.blobs TO :role;
-- Per-label quota, for the same reason. A single tenant-wide counter would let
-- a low user infer high-label activity from the remaining-space figure.
CREATE TABLE :schema.quotas (
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
limit_bytes bigint NOT NULL,
used_bytes bigint NOT NULL DEFAULT 0,
PRIMARY KEY (classification, compartments)
);
ALTER TABLE :schema.quotas ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.quotas FORCE ROW LEVEL SECURITY;
CREATE POLICY quotas_read ON :schema.quotas FOR SELECT
USING (enclave.session_label_is(classification, compartments));
GRANT SELECT ON :schema.quotas TO :role;
-- ---------------------------------------------------------------- regrade
-- Moving a node down the lattice is the one privileged operation. Two distinct
-- reviewers, an immutable record, and no path that mutates nodes directly.
CREATE TABLE :schema.regrade_requests (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
node_id uuid NOT NULL REFERENCES :schema.nodes(id),
from_class smallint NOT NULL,
from_comp bigint NOT NULL,
to_class smallint NOT NULL,
to_comp bigint NOT NULL,
justification text NOT NULL CHECK (length(justification) >= 20),
requested_by uuid NOT NULL,
reviewer_a uuid,
reviewer_b uuid,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','approved','rejected','applied')),
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (reviewer_a IS DISTINCT FROM reviewer_b),
CHECK (reviewer_a IS DISTINCT FROM requested_by),
CHECK (reviewer_b IS DISTINCT FROM requested_by)
);
ALTER TABLE :schema.regrade_requests ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.regrade_requests FORCE ROW LEVEL SECURITY;
CREATE POLICY regrade_read ON :schema.regrade_requests FOR SELECT
USING (enclave.session_dominates(from_class, from_comp));
GRANT SELECT, INSERT, UPDATE ON :schema.regrade_requests TO :role;
-- ---------------------------------------------------------------- audit
-- Append-only. Audit rows carry the label of what they describe, so the log
-- itself cannot become the leak.
CREATE TABLE :schema.audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id uuid NOT NULL,
session_class smallint NOT NULL,
session_comp bigint NOT NULL,
action text NOT NULL,
node_id uuid,
classification smallint NOT NULL,
compartments bigint NOT NULL,
detail jsonb NOT NULL DEFAULT '{}'::jsonb
);
ALTER TABLE :schema.audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.audit_log FORCE ROW LEVEL SECURITY;
CREATE POLICY audit_read ON :schema.audit_log FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY audit_insert ON :schema.audit_log FOR INSERT WITH CHECK (true);
-- No UPDATE or DELETE grant, ever. Retention is a partition drop by the owner.
GRANT SELECT, INSERT ON :schema.audit_log TO :role;
-- ---------------------------------------------------------------- keys
-- Label keys, wrapped to each principal whose clearance permits the label.
-- The server stores only wrapped blobs; it holds no key that opens any of them.
CREATE TABLE :schema.label_key_grants (
-- Surrogate key so the ORM can address a row; the tuple below is the real
-- identity and is kept unique.
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
principal_id uuid NOT NULL,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL,
granted_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (classification, compartments, principal_id, generation)
);
ALTER TABLE :schema.label_key_grants ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.label_key_grants FORCE ROW LEVEL SECURITY;
-- A principal may read only their own grants. Seeing who else is cleared for a
-- compartment is itself sensitive, so this is not a dominance test.
CREATE POLICY label_key_grants_read ON :schema.label_key_grants FOR SELECT
USING (principal_id = NULLIF(current_setting('enclave.principal', true), '')::uuid);
-- Self-grant only, at exactly the session label. This is enough to bootstrap a
-- new principal, which is what the browser does on first unlock. Granting a
-- label key to *another* principal is a clearance decision and belongs to the
-- control plane, not to any authenticated session.
CREATE POLICY label_key_grants_insert ON :schema.label_key_grants FOR INSERT
WITH CHECK (
enclave.session_label_is(classification, compartments)
AND principal_id = NULLIF(current_setting('enclave.principal', true), '')::uuid
);
GRANT SELECT, INSERT ON :schema.label_key_grants TO :role;
-- Node keys, wrapped to the node's LABEL key -- never to the parent's node key.
-- The CHECK is the database's copy of KeyHierarchy.validate: it makes the
-- misalignment that would silently undo the lattice unrepresentable.
CREATE TABLE :schema.node_keys (
node_id uuid PRIMARY KEY REFERENCES :schema.nodes(id) ON DELETE CASCADE,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL
);
CREATE FUNCTION :schema.enforce_key_label_alignment() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE n_class smallint; n_comp bigint;
BEGIN
SELECT classification, compartments INTO n_class, n_comp
FROM nodes WHERE id = NEW.node_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'node not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NEW.classification <> n_class OR NEW.compartments <> n_comp THEN
RAISE EXCEPTION 'node key must be wrapped to its own label key'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER node_keys_label_alignment
BEFORE INSERT OR UPDATE ON :schema.node_keys
FOR EACH ROW EXECUTE FUNCTION :schema.enforce_key_label_alignment();
ALTER TABLE :schema.node_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.node_keys FORCE ROW LEVEL SECURITY;
CREATE POLICY node_keys_read ON :schema.node_keys FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY node_keys_insert ON :schema.node_keys FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.node_keys TO :role;
-- A downgrade cannot be executed by the server: it must decrypt under the old
-- label key and re-encrypt under the new one, and the server holds neither.
-- So 'approved' is a request awaiting a cleared client to perform the rewrap,
-- and only that client can move it to 'applied'.
ALTER TABLE :schema.regrade_requests
ADD COLUMN applied_by uuid,
ADD COLUMN applied_at timestamptz,
ADD CONSTRAINT regrade_applied_requires_client
CHECK ((status <> 'applied') OR (applied_by IS NOT NULL AND applied_at IS NOT NULL));
-- ---------------------------------------------------------------- identities
-- Not here. Identities moved to the account service, which owns them for
-- every product rather than once per tenant per product.
--
-- They were never really file state: a keypair belongs to the account, and
-- keeping the two apart meant registration was two writes across two
-- services with a window in between where a client could die and strand an
-- account nobody could enrol into. They are now written in the same
-- transaction as the account itself.
--
-- Self-hosters lose nothing: the bundled compose runs its own account
-- service against its own schema, so the identity store is still local and
-- still yours.
-- ---------------------------------------------------------------- vocabulary
-- What this tenant calls its levels and compartments.
--
-- Names live in the tenant schema rather than the control plane because the
-- worker has no grant there, and because the vocabulary is the tenant's own:
-- one customer's "Restricted" is another's "Level 4".
--
-- Nothing here is sensitive on its own -- these are labels on a ladder, not
-- data -- so reads are not lattice-gated. The API still filters compartment
-- names down to the caller's clearance, so the existence of a compartment you
-- are not in is not advertised.
CREATE TABLE :schema.classification_levels (
ordinal smallint PRIMARY KEY CHECK (ordinal >= 0),
name text NOT NULL
);
CREATE TABLE :schema.compartment_names (
bit smallint PRIMARY KEY CHECK (bit BETWEEN 0 AND 63),
name text NOT NULL
);
ALTER TABLE :schema.classification_levels ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.classification_levels FORCE ROW LEVEL SECURITY;
CREATE POLICY classification_levels_read ON :schema.classification_levels FOR SELECT USING (true);
CREATE POLICY classification_levels_write ON :schema.classification_levels FOR ALL USING (true) WITH CHECK (true);
ALTER TABLE :schema.compartment_names ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.compartment_names FORCE ROW LEVEL SECURITY;
CREATE POLICY compartment_names_read ON :schema.compartment_names FOR SELECT USING (true);
CREATE POLICY compartment_names_write ON :schema.compartment_names FOR ALL USING (true) WITH CHECK (true);
GRANT SELECT, INSERT, UPDATE, DELETE ON :schema.classification_levels TO :role;
GRANT SELECT, INSERT, UPDATE, DELETE ON :schema.compartment_names TO :role;
-- A ladder that reads sensibly out of the box. Renaming these is a CLI action.
INSERT INTO :schema.classification_levels (ordinal, name) VALUES
(0, 'Public'), (1, 'Internal'), (2, 'Confidential'), (3, 'Restricted')
ON CONFLICT (ordinal) DO NOTHING;
-- ---------------------------------------------------------------- shares
-- Link shares that still respect the lattice.
--
-- The row holds a content key and a filename wrapped under a key derived from
-- the label key *and* a secret that lives only in the link's fragment. The
-- server stores neither half in the clear and cannot open either: fragments are
-- never sent, and the label key never leaves a cleared client.
--
-- Row-level security is the second wall. An uncleared session cannot even fetch
-- the wrapped material, so a forwarded link fails before the mathematics gets a
-- chance to. Expiry is enforced in the same predicate, which means an expired
-- share stops being visible rather than relying on a handler to remember to
-- check.
CREATE TABLE :schema.shares (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
node_id uuid NOT NULL REFERENCES :schema.nodes(id) ON DELETE CASCADE,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
wrapped_content_key bytea NOT NULL,
wrapped_name bytea NOT NULL,
created_by uuid NOT NULL,
-- An optional third factor, sent out of band. The salt is public; the
-- password itself never reaches the server, and no verifier is stored, so
-- there is nothing here for anyone to attack offline. A wrong password
-- simply derives a key that does not decrypt.
password_salt bytea,
password_iterations integer,
expires_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX shares_node ON :schema.shares (node_id);
CREATE INDEX shares_label ON :schema.shares (classification, compartments);
ALTER TABLE :schema.shares ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.shares FORCE ROW LEVEL SECURITY;
CREATE POLICY shares_read ON :schema.shares FOR SELECT
USING (
enclave.session_dominates(classification, compartments)
AND (expires_at IS NULL OR expires_at > now())
);
-- A share is created at the session label, like anything else. Sharing a file
-- to a lower label is not a share, it is a downgrade, and downgrades go through
-- the regrade workflow.
CREATE POLICY shares_insert ON :schema.shares FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
-- Only the person who made a link may revoke it.
CREATE POLICY shares_delete ON :schema.shares FOR DELETE
USING (created_by = NULLIF(current_setting('enclave.principal', true), '')::uuid);
GRANT SELECT, INSERT, DELETE ON :schema.shares TO :role;
@@ -1,76 +0,0 @@
-- Let a cleared principal hand their label key to another principal.
--
-- Until now the only insert policy was self-grant, with the comment that
-- granting to someone else "is a clearance decision and belongs to the control
-- plane". That is still true, and this does not move the decision into the
-- session — it splits the check across the two places that can each see half
-- of it:
--
-- * The database enforces what it can see: the granter must already hold a
-- key at exactly this label, and the row's label must equal the session
-- label. Nobody can mint a key for a label they cannot themselves assert.
--
-- * The application enforces what only the control plane knows: that the
-- recipient is cleared for the label. The tenant role has no grant on
-- enclave_control and never will, so the file server asks the account
-- service and refuses if the answer is no.
--
-- Worth being precise about what the second check is worth, because it is the
-- weaker one. A label key alone opens nothing: every row at that label is still
-- hidden by row-level security from a session whose token does not carry the
-- clearance. So a grant that slipped past the application check would hand
-- somebody ciphertext they can unwrap and a server that will never serve them
-- the ciphertext. It is defence in depth, not the load-bearing control.
--
-- Idempotent, because this script runs against tenant schemas that already
-- exist as well as being folded into the template for new ones.
DROP POLICY IF EXISTS label_key_grants_delegate ON :schema.label_key_grants;
CREATE POLICY label_key_grants_delegate ON :schema.label_key_grants FOR INSERT
WITH CHECK (
enclave.session_label_is(classification, compartments)
AND EXISTS (
SELECT 1
FROM :schema.label_key_grants AS held
WHERE held.principal_id
= NULLIF(current_setting('enclave.principal', true), '')::uuid
AND held.classification = label_key_grants.classification
AND held.compartments = label_key_grants.compartments
)
);
-- Who granted what to whom, and when.
--
-- Not for the granter's benefit: this is the record that says how someone came
-- to hold a key, which is the first question asked after anything goes wrong.
-- Append-only to the tenant role — it may write its own actions and read them
-- back, and it may not rewrite history.
CREATE TABLE IF NOT EXISTS :schema.grant_audit (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
granted_by uuid NOT NULL,
granted_to uuid NOT NULL,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
granted_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE :schema.grant_audit ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.grant_audit FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS grant_audit_read ON :schema.grant_audit;
DROP POLICY IF EXISTS grant_audit_insert ON :schema.grant_audit;
-- Readable by either party to the grant. Not by everyone at the label: who else
-- holds a compartment is exactly the thing the read policy on label_key_grants
-- refuses to disclose, and this table must not become the way around it.
CREATE POLICY grant_audit_read ON :schema.grant_audit FOR SELECT
USING (
granted_by = NULLIF(current_setting('enclave.principal', true), '')::uuid
OR granted_to = NULLIF(current_setting('enclave.principal', true), '')::uuid
);
CREATE POLICY grant_audit_insert ON :schema.grant_audit FOR INSERT
WITH CHECK (granted_by = NULLIF(current_setting('enclave.principal', true), '')::uuid);
GRANT SELECT, INSERT ON :schema.grant_audit TO :role;
@@ -1,130 +0,0 @@
-- Revoking a clearance has to rotate the label key, or it revokes nothing.
--
-- Today a grant can be handed out and never taken back: `label_key_grants`
-- carries SELECT and INSERT to the tenant role and nothing else. That gap is
-- not an oversight about DELETE. Deleting the row would be the dangerous
-- version of this feature, because the key is already on the revoked person's
-- device. Removing their copy of a grant removes a record, not an ability —
-- and every node key at that label stays wrapped to the key they still hold.
--
-- So revocation is two things that must not be confused:
--
-- 1. Withdrawing the grant. Cheap, immediate, and on its own worth nothing
-- against anyone who kept the key.
-- 2. Rotating the label key and re-wrapping every node key under the new
-- generation. This is what actually ends their access to content filed
-- from that moment, and it CANNOT be done here: the server holds no key
-- that opens anything. Only a cleared client can perform it.
--
-- The regrade workflow already models exactly this shape — the server records
-- an intent, and a cleared client moves it to `applied` once it has done the
-- cryptography. This follows it deliberately rather than inventing a second
-- vocabulary for the same idea.
--
-- 🔴 **The status vocabulary refuses to lie.** There is no `revoked` state that
-- can be reached by withdrawing a grant alone, because "revoked" is the claim
-- somebody will read on a screen and act on. The states are what is true:
-- `requested` (the grant is gone, the key is not), `rotating` (a client is
-- re-wrapping), and `rotated` (the new generation is live). An interface
-- showing "access removed" before `rotated` would be stating something the
-- system has not done.
CREATE TABLE IF NOT EXISTS :schema.clearance_revocations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
-- The label whose key must rotate.
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
-- Whose access is being withdrawn.
principal_id uuid NOT NULL,
requested_by uuid NOT NULL,
requested_at timestamptz NOT NULL DEFAULT now(),
-- The generation in force when this was requested, and the one that ends
-- it. Recorded rather than derived: a second revocation raised while the
-- first is still rotating must not silently retarget the first one's work.
from_generation integer NOT NULL,
to_generation integer NOT NULL,
CHECK (to_generation = from_generation + 1),
status text NOT NULL DEFAULT 'requested'
CHECK (status IN ('requested','rotating','rotated','abandoned')),
-- Set only by the client that performed the rewrap, exactly as
-- `regrade_requests.applied_by` is. The server cannot fill these in
-- because it cannot do the work they attest to.
rotated_by uuid,
rotated_at timestamptz,
-- ⚠️ A row cannot claim the rotation happened without naming who did it.
-- The same constraint regrade uses, for the same reason: a status column
-- that can be moved without evidence is a status column that will be.
CONSTRAINT revocation_rotated_requires_client CHECK (
status <> 'rotated' OR (rotated_by IS NOT NULL AND rotated_at IS NOT NULL)
),
-- Revoking your own clearance is not a thing anyone means to do, and doing
-- it by accident locks you out of your own compartment.
CHECK (principal_id IS DISTINCT FROM requested_by)
);
-- One rotation in flight per label. Two concurrent rotations would each mint a
-- generation and re-wrap a subset of the node keys, leaving the label split
-- across two keys with no record of which opens what.
CREATE UNIQUE INDEX IF NOT EXISTS clearance_revocations_one_in_flight
ON :schema.clearance_revocations (classification, compartments)
WHERE status IN ('requested','rotating');
ALTER TABLE :schema.clearance_revocations ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.clearance_revocations FORCE ROW LEVEL SECURITY;
-- Readable by anyone cleared for the label. Unlike `label_key_grants` — where
-- who else holds a compartment is deliberately not disclosable — a rotation in
-- flight is something every holder needs to see, because every holder has to
-- re-fetch their key when it lands.
DROP POLICY IF EXISTS clearance_revocations_read ON :schema.clearance_revocations;
CREATE POLICY clearance_revocations_read ON :schema.clearance_revocations FOR SELECT
USING (enclave.session_dominates(classification, compartments));
-- Requesting one requires holding the label yourself, at exactly that label.
DROP POLICY IF EXISTS clearance_revocations_insert ON :schema.clearance_revocations;
CREATE POLICY clearance_revocations_insert ON :schema.clearance_revocations FOR INSERT
WITH CHECK (
enclave.session_label_is(classification, compartments)
AND requested_by = NULLIF(current_setting('enclave.principal', true), '')::uuid
);
-- Only forward, and only by a session at the label. The CHECK constraint above
-- is what stops 'rotated' being claimed without evidence; this stops somebody
-- at a different label moving it at all.
DROP POLICY IF EXISTS clearance_revocations_update ON :schema.clearance_revocations;
CREATE POLICY clearance_revocations_update ON :schema.clearance_revocations FOR UPDATE
USING (enclave.session_label_is(classification, compartments))
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT, UPDATE ON :schema.clearance_revocations TO :role;
-- Withdrawing the grant itself. DELETE was never granted on this table; it is
-- granted here and nowhere else, so the only way a grant disappears is through
-- a revocation that has been recorded.
--
-- ⚠️ Deliberately NOT restricted to rows whose revocation is `rotated`. The
-- grant should go the moment the decision is made — leaving it in place while
-- rotation is pending would mean a person who has just been revoked can still
-- fetch a fresh copy of the key from the server. Withdrawing early is weaker
-- than rotation and stronger than nothing.
DROP POLICY IF EXISTS label_key_grants_delete ON :schema.label_key_grants;
CREATE POLICY label_key_grants_delete ON :schema.label_key_grants FOR DELETE
USING (
enclave.session_label_is(classification, compartments)
AND EXISTS (
SELECT 1 FROM :schema.clearance_revocations r
WHERE r.classification = label_key_grants.classification
AND r.compartments = label_key_grants.compartments
AND r.principal_id = label_key_grants.principal_id
AND r.status IN ('requested','rotating','rotated')
)
);
GRANT DELETE ON :schema.label_key_grants TO :role;
@@ -1,99 +0,0 @@
-- The server as a courier: hold ciphertext until it reaches the other device,
-- then let it go.
--
-- 🔴 **This changes what a promise means, so it does not change existing data.**
-- Every blob written before this migration was stored under "we keep this for
-- you". Sweeping those on a delivery rule would delete files people believe
-- they still have, and no amount of correct new behaviour makes that anything
-- other than data loss. So `mode` defaults to 'stored', every existing row
-- takes that default, and courier behaviour applies only to blobs uploaded
-- after somebody chose it.
--
-- The two modes are genuinely different products and the column says which:
--
-- stored the server keeps it until the owner deletes it. What Files has
-- always done. The server cannot read it, but it does hold it.
-- courier the server holds it only until every intended device has it,
-- then drops it. Nothing durable in the middle.
--
-- ⚠️ **Courier mode is not a backup, and the interface must not imply it is.**
-- If every device holding a file loses it, the file is gone — the server has
-- no copy to restore from, by design. That is the trade being made for "you
-- store nothing permanently", and it is the kind of thing a person should be
-- told once in plain words rather than discover.
--
-- The retention shape is deliberately the relay's, not a new one. Messenger has
-- run this for envelopes since it shipped: a delivered flag, a short grace
-- after delivery, and a longer backstop for a recipient who never appears.
-- Same vocabulary, same proven behaviour, one thing to reason about.
ALTER TABLE :schema.blobs
ADD COLUMN IF NOT EXISTS mode text NOT NULL DEFAULT 'stored'
CHECK (mode IN ('stored','courier'));
-- Which devices this transfer is for, and which have collected it.
--
-- Per device rather than per person: a file that reached the phone but not the
-- laptop has not arrived, and dropping it then would lose it for the laptop
-- for ever. "Delivered" means every intended device, not the first one.
CREATE TABLE IF NOT EXISTS :schema.blob_deliveries (
blob_id uuid NOT NULL REFERENCES :schema.blobs(id) ON DELETE CASCADE,
device_id text NOT NULL,
collected_at timestamptz,
PRIMARY KEY (blob_id, device_id)
);
ALTER TABLE :schema.blob_deliveries ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.blob_deliveries FORCE ROW LEVEL SECURITY;
-- Readable and writable only by a session that can already see the blob. The
-- label check rides on the blob row rather than being duplicated here, so the
-- two cannot disagree about who may see a transfer.
DROP POLICY IF EXISTS blob_deliveries_read ON :schema.blob_deliveries;
CREATE POLICY blob_deliveries_read ON :schema.blob_deliveries FOR SELECT
USING (EXISTS (
SELECT 1 FROM :schema.blobs b
WHERE b.id = blob_deliveries.blob_id
AND enclave.session_dominates(b.classification, b.compartments)));
DROP POLICY IF EXISTS blob_deliveries_insert ON :schema.blob_deliveries;
CREATE POLICY blob_deliveries_insert ON :schema.blob_deliveries FOR INSERT
WITH CHECK (EXISTS (
SELECT 1 FROM :schema.blobs b
WHERE b.id = blob_deliveries.blob_id
AND enclave.session_label_is(b.classification, b.compartments)));
-- A device marks its own collection and nothing else. Deliberately not
-- restricted to the calling device's id, because the id is asserted by the
-- session and a device lying about having collected a file only hurts itself:
-- it drops its own copy sooner. Nobody else's delivery is affected.
DROP POLICY IF EXISTS blob_deliveries_update ON :schema.blob_deliveries;
CREATE POLICY blob_deliveries_update ON :schema.blob_deliveries FOR UPDATE
USING (EXISTS (
SELECT 1 FROM :schema.blobs b
WHERE b.id = blob_deliveries.blob_id
AND enclave.session_dominates(b.classification, b.compartments)));
GRANT SELECT, INSERT, UPDATE ON :schema.blob_deliveries TO :role;
-- Fully collected transfers, for the sweep. A courier blob with no delivery
-- rows at all is NOT complete — it is a transfer nobody was named for, and
-- treating "no rows" as "everyone has it" would delete it immediately.
CREATE OR REPLACE VIEW :schema.blob_transfer_state AS
SELECT b.id,
b.mode,
b.created_at,
count(d.*) AS intended,
count(d.*) FILTER (WHERE d.collected_at IS NOT NULL) AS collected,
(count(d.*) > 0
AND count(d.*) = count(d.*) FILTER (WHERE d.collected_at IS NOT NULL))
AS complete,
max(d.collected_at) AS completed_at
FROM :schema.blobs b
LEFT JOIN :schema.blob_deliveries d ON d.blob_id = b.id
GROUP BY b.id, b.mode, b.created_at;
GRANT SELECT ON :schema.blob_transfer_state TO :role;
CREATE INDEX IF NOT EXISTS blobs_courier_created
ON :schema.blobs (created_at) WHERE mode = 'courier';
-120
View File
@@ -1,120 +0,0 @@
import Foundation
import Fluent
import FluentPostgresDriver
import JWT
import Leaf
import Vapor
import EnclaveAccess
func configure(_ app: Application) async throws {
// MARK: database
//
// A worker connects as its own tenant role, whose search_path points at that
// tenant's schema. The role has USAGE on nothing else, so a bug in this
// process cannot address another tenant's tables -- there is no grant to.
guard let databaseURL = Environment.get("DATABASE_URL") else {
throw Abort(.internalServerError, reason: "DATABASE_URL is required")
}
app.databases.use(.postgres(configuration: try .init(url: databaseURL)), as: .psql)
// MARK: token verification
//
// Clearance arrives in a token minted by the control plane. This secret
// verifies signatures; it never mints anything here.
guard let jwtSecret = Environment.get("ENCLAVE_JWT_SECRET"), jwtSecret.count >= 32 else {
throw Abort(.internalServerError,
reason: "ENCLAVE_JWT_SECRET is required and must be at least 32 characters")
}
await app.jwt.keys.add(hmac: .init(from: jwtSecret), digestAlgorithm: .sha256)
// MARK: views and static files
app.views.use(.leaf)
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
// MARK: blob storage
let blobPath = Environment.get("ENCLAVE_BLOB_PATH")
?? app.directory.workingDirectory + "blobs"
try FileManager.default.createDirectory(
atPath: blobPath, withIntermediateDirectories: true
)
app.blobs = BlobStore(root: URL(fileURLWithPath: blobPath, isDirectory: true))
// MARK: commands
app.asyncCommands.use(TokenCommand(), as: "token")
app.asyncCommands.use(LabelCommand(), as: "label")
// MARK: schema
app.migrations.add(InstallSharedSchema())
if let tenant = Environment.get("ENCLAVE_TENANT") {
app.migrations.add(InstallTenantSchema(slug: tenant))
// Incremental scripts, one migration each, so an existing tenant picks
// up what the template alone would only have given a new one.
for script in ApplyTenantScript.all {
app.migrations.add(ApplyTenantScript(slug: tenant, script: script))
}
}
// Opt-in, so a self-hoster upgrading a running deployment chooses when DDL
// executes rather than having it happen on restart.
if Environment.get("ENCLAVE_AUTO_MIGRATE") == "true" {
try await app.autoMigrate()
}
// MARK: safety
//
// Skipped for the migrate command, which legitimately runs as the schema
// owner. Serving traffic as that role is what must never happen.
let isServing = !CommandLine.arguments.contains("migrate")
&& !CommandLine.arguments.contains("token")
&& !CommandLine.arguments.contains("label")
if isServing {
try await RLSGuard.assertRowLevelSecurityApplies(app)
}
// MARK: courier sweep
//
// 🔴 **Off unless switched on, and it deletes things, which is why.**
// Nothing is courier mode today — `blobs.mode` defaults to 'stored' and
// only an upload that asks becomes a transfer — so this would find zero
// rows either way. That is exactly the right time to make it deliberate:
// a sweeper is easy to enable when the feature it serves arrives, and
// impossible to un-delete if it runs before anyone expected it to.
//
// ⚠️ Also still waiting on device identity. `blob_deliveries.device_id`
// has nothing behind it yet: a session carries a principal, a clearance
// and a label, and no notion of WHICH device is asking. Until that
// exists, `intended` is zero for every transfer, which this reads as
// "awaiting collection" and holds to the backstop rather than dropping.
// Safe, and not yet the feature.
if isServing, Environment.get("ENCLAVE_COURIER_SWEEP") == "true" {
let sweep = CourierRetention(
db: app.db,
blobs: app.blobs,
logger: app.logger,
retention: .default)
Task.detached { await sweep.run() }
app.logger.notice("courier sweep enabled")
}
// MARK: donations
//
// Which Stripe account the money lands on, said out loud. A platform key
// without a connected account takes real payments onto the wrong account
// and reports nothing — the only symptom is the balance.
if DonateController.secret != nil {
switch DonateController.account {
case .some(let account) where account.hasPrefix("acct_"):
app.logger.notice("donations are taken on connected account \(account)")
case .some(let account):
app.logger.critical("FN_DONATE_ACCOUNT is not a Stripe account id (\(account)) — every donation will fail at the processor.")
case .none:
app.logger.warning("FN_DONATE_ACCOUNT is unset — donations land on whichever account FN_DONATE_SECRET belongs to, which on a platform key is the platform itself.")
}
}
// MARK: uploads
// Ciphertext only, but still worth a ceiling.
app.routes.defaultMaxBodySize = "64mb"
try routes(app)
}
-21
View File
@@ -1,21 +0,0 @@
import Vapor
import Logging
@main
enum Entrypoint {
static func main() async throws {
var environment = try Environment.detect()
try LoggingSystem.bootstrap(from: &environment)
let app = try await Application.make(environment)
do {
try await configure(app)
} catch {
app.logger.report(error: error)
try? await app.asyncShutdown()
throw error
}
try await app.execute()
try await app.asyncShutdown()
}
}
-28
View File
@@ -1,28 +0,0 @@
import Fluent
import Vapor
import EnclaveAccess
func routes(_ app: Application) throws {
app.get("healthz") { _ async -> String in "ok" }
// Public pages and the application shell. Everything the file browser
// displays is decrypted in the browser, so Leaf renders the frame and the
// client fills it in.
try app.register(collection: SiteController())
try app.register(collection: DonateController())
// Unauthenticated on purpose: a native app has to be told where to
// authenticate before it can authenticate.
try app.register(collection: ConfigController())
// Strong tranquility: writes happen at exactly the session label. See
// WriteRule for why the *-property alternative is not the default.
let session = EnclaveSessionMiddleware(policy: Policy(writeRule: .equal))
let authenticated = app.grouped(session)
try authenticated.register(collection: NodeController())
try authenticated.register(collection: KeyController())
try authenticated.register(collection: BlobController())
try authenticated.register(collection: VocabularyController())
try authenticated.register(collection: ShareController())
}
+7 -119
View File
@@ -15,18 +15,7 @@ Every bug found in sharing and in recovery was found by the bottom row.
## The fast ones
```bash
swift test # server: lattice, SQL scripts, accounts kit
node --test client/test/*.mjs # web client: content, identity, lattice, shares
```
⚠️ `node --test client/test/` — the directory rather than the glob — reports a
single opaque failure on Node 25 and runs nothing.
In the app repositories:
```bash
swift test # flamenet-files-ios: FilesEngine
./gradlew :engine:test # flamenet-files-android: engine
swift test # lattice, SQL scripts, accounts kit
```
## Against a throwaway stack
@@ -46,111 +35,10 @@ Messenger delete that took the whole account would take the `identities` row
that wraps somebody's file key, and nothing else holds a copy. B is what fails
if that reading ever comes back.
## Against a running stack
## The rate limits, when you run the throwaway stack
```bash
docker compose up -d
node scripts/integration/account-functions.mjs # registration, sign-in, passphrase, recovery
node scripts/integration/area-sharing.mjs # handing a label key to somebody else
```
These use the same modules the browser runs, so they exercise the client rather
than a second implementation of it. `area-sharing.mjs` also shells out to
`docker compose exec` to assign clearances, which is an administrative act with
no endpoint by design.
⚠️ `docker-compose.yml` raises two rate limits that a deployment should leave
alone: registrations and sign-in attempts *per address*, because every test run
on a development machine arrives from one address. The per-*handle* sign-in
limit is deliberately left at its default — it is the one that actually stops a
password guess, and `account-functions.mjs` asserts that it engages.
## The app suites
Both drive the real app against the local stack, and both register real
accounts, so point them at a development stack and never at production.
Reset first:
```bash
scripts/reset-local.sh # ⚠️ destroys the local database and blobs
node scripts/seed-ui-account.mjs
```
⚠️ Not housekeeping. The open area is shared by everyone cleared for it, so
every account a test run creates leaves its rows there permanently — after a
few hundred runs the list a new account arrives at is not empty, a freshly
created folder is no longer on screen, and neither lazy list builds a row it
has not shown. The suites then fail for reasons that have nothing to do with
the app. The tests scroll to find their rows anyway, but starting from an empty
server is what makes a run reproducible.
The seeded account exists because one thing the apps do cannot be tested by an
account that registers itself: choosing *where* a file is filed. That needs a
clearance above the bottom of the lattice, clearance is assigned by command
with no endpoint by design, and a test running inside a simulator cannot run
commands on this machine. So it is seeded first and signed into. The tests that
need it skip rather than fail when it is missing — a red test for a missing
fixture teaches people to ignore red tests.
### iOS
```bash
xcodebuild build-for-testing -project FlamenetFiles.xcodeproj -scheme FlamenetFiles \
-destination 'platform=iOS Simulator,id=<udid>'
xcodebuild test-without-building -project FlamenetFiles.xcodeproj -scheme FlamenetFiles \
-destination 'platform=iOS Simulator,id=<udid>'
```
⚠️ **Use a simulator nothing else is using**, and address it by udid rather than
by name. Two XCUITest runners on one device produce failures that look like
product bugs and are not: taps landing in another app, element frames a
twentieth of their real size, `kAXErrorIPCTimeout`. Creating a dedicated one is
a second:
```bash
xcrun simctl create files-test "iPhone 17 Pro" "com.apple.CoreSimulator.SimRuntime.iOS-26-5"
xcrun simctl bootstatus <udid> -b # waits for a *finished* boot, unlike `boot`
```
A cold device fails the first run on accessibility timeouts, so wait for the
boot rather than racing it.
### Android
```bash
adb -s $SERIAL reverse tcp:8081 tcp:8081 && adb -s $SERIAL reverse tcp:8100 tcp:8100
ANDROID_SERIAL=$SERIAL ./gradlew connectedDebugAndroidTest
```
⚠️ **Name the device, both times.** `connectedAndroidTest` runs on *every*
attached device, so another project's emulator — or one left running from
yesterday — silently joins the run, and `adb` without `-s` refuses outright
once a second device appears. `ANDROID_SERIAL` pins the run to one; find it
with `adb devices` and confirm which AVD it is with
`adb -s <serial> emu avd name`.
A dedicated AVD, phone-shaped and with room to work:
```bash
avdmanager create avd -n files-android-iso \
-k "system-images;android-35;google_apis;arm64-v8a"
# then in ~/.android/avd/files-android-iso.avd/config.ini:
# hw.ramSize=4096 vm.heapSize=512
# hw.lcd.density=420 hw.lcd.width=1080 hw.lcd.height=2400
emulator -avd files-android-iso -no-snapshot -no-boot-anim -wipe-data
```
⚠️ The forwards are not optional. The server tells clients where its account
service lives, and that answer is *one string for every client* — so an
emulator reaching the server on `10.0.2.2` is still handed `127.0.0.1:8100` for
accounts and fails with "Failed to connect to /127.0.0.1:8100" against a stack
that is plainly running. Forwarding the ports makes loopback mean the same
thing in the emulator as in a browser and on the iOS simulator, so one server
configuration serves all three. `scripts/local-for.sh android` flips the
advertised address instead, which is what a physical device on the same network
needs.
⚠️ The screen size is not cosmetic. A default AVD at 320×640 hides every
layout failure that only happens at real phone widths, and runs out of heap
partway through a suite.
`docker-compose.yml` raises two limits a deployment should leave alone:
registrations and sign-in attempts *per address*, because every test run on a
development machine arrives from one address. The per-*handle* sign-in limit is
deliberately left at its default. It is the one that actually stops a password
guess, and `scripts/test-throttle-restart.sh` asserts that it engages.
@@ -231,48 +231,3 @@ final class RateLimiterTests: XCTestCase {
"a live window must survive the sweep that clears dead ones")
}
}
/// One handle backs every product, so what "delete my account" removes is not
/// obvious and getting it wrong destroys files. These pin the reading.
final class AccountRemovalTests: XCTestCase {
/// The case that was broken: Messenger writes no identity, so somebody who
/// only ever used Messenger has nothing enrolled and the account goes.
func testAMessengerOnlyAccountIsRemovedEntirely() {
XCTAssertEqual(
AccountRemoval.decide(deleting: "messenger", enrolled: []),
.removeAccount)
}
/// The case that would have been a silent data loss. The `files` identity
/// row wraps the key those files are encrypted under; taking it because
/// somebody left Messenger would be unrecoverable.
func testLeavingMessengerKeepsAnAccountThatStillHasFiles() {
XCTAssertEqual(
AccountRemoval.decide(deleting: "messenger", enrolled: ["files"]),
.detachProduct)
}
/// Symmetric: the rule is about what remains, not about which product is
/// privileged.
func testLeavingFilesKeepsAnAccountThatStillHasMessenger() {
XCTAssertEqual(
AccountRemoval.decide(deleting: "files", enrolled: ["messenger"]),
.detachProduct)
}
/// A product's own enrolment is never what keeps its account alive.
func testTheDepartingProductDoesNotCountAsAReasonToStay() {
XCTAssertEqual(
AccountRemoval.decide(deleting: "files", enrolled: ["files"]),
.removeAccount)
}
func testTheLastProductLeavingTakesTheAccount() {
XCTAssertEqual(
AccountRemoval.decide(deleting: "files", enrolled: ["files", "messenger"]),
.detachProduct)
XCTAssertEqual(
AccountRemoval.decide(deleting: "messenger", enrolled: ["messenger"]),
.removeAccount)
}
}
@@ -1,145 +0,0 @@
import XCTest
@testable import EnclaveAccess
/// The sweep decides whether somebody's file is deleted, so every branch is
/// pinned — including the ones that exist only to stop a deletion.
final class CourierSweepTests: XCTestCase {
private let now = Date(timeIntervalSince1970: 1_800_000_000)
private func ago(_ seconds: TimeInterval) -> Date { now.addingTimeInterval(-seconds) }
private func transfer(mode: CourierSweep.Mode = .courier,
age: TimeInterval = 0,
intended: Int = 2,
collected: Int = 0,
completed: TimeInterval? = nil) -> CourierSweep.Transfer {
CourierSweep.Transfer(mode: mode, createdAt: ago(age),
intended: intended, collected: collected,
completedAt: completed.map(ago))
}
// MARK: - Stored blobs are never touched
/// 🔴 The case that protects everything uploaded before courier existed.
func testAStoredBlobIsNeverDroppedHoweverOld() {
let ancient = transfer(mode: .stored, age: 365 * 24 * 60 * 60,
intended: 0, collected: 0)
XCTAssertFalse(CourierSweep.shouldDrop(ancient, now: now))
XCTAssertEqual(CourierSweep.verdict(ancient, now: now), .keep(.stored))
}
/// A stored blob nobody ever collected is still not a courier transfer.
func testAStoredBlobWithNoDeliveriesIsStillKept() {
let t = transfer(mode: .stored, age: 90 * 24 * 60 * 60, intended: 0)
XCTAssertEqual(CourierSweep.verdict(t, now: now), .keep(.stored))
}
// MARK: - The empty-set trap
/// 🔴 Zero intended devices must not read as "everybody has it".
///
/// Between an upload and its delivery rows being written there is a moment
/// with no recipients recorded. If that counted as complete, the sweep
/// would delete a file whose only copy may still be in flight.
func testATransferAddressedToNobodyIsNotComplete() {
let justUploaded = transfer(age: 5, intended: 0, collected: 0)
XCTAssertFalse(justUploaded.isComplete)
XCTAssertEqual(CourierSweep.verdict(justUploaded, now: now),
.keep(.awaitingCollection))
}
/// And it stays kept right up to the backstop, rather than being swept
/// early for having no recipients.
func testATransferAddressedToNobodyIsKeptUntilTheBackstop() {
let old = transfer(age: 29 * 24 * 60 * 60, intended: 0)
XCTAssertEqual(CourierSweep.verdict(old, now: now), .keep(.awaitingCollection))
let past = transfer(age: 31 * 24 * 60 * 60, intended: 0)
XCTAssertEqual(CourierSweep.verdict(past, now: now), .drop(.expired))
}
// MARK: - Partial delivery
/// A file that reached the phone and not the laptop has not arrived.
/// Dropping it here loses it for the laptop for ever.
func testPartialDeliveryIsNotDelivered() {
let half = transfer(age: 60 * 60, intended: 3, collected: 2)
XCTAssertFalse(half.isComplete)
XCTAssertEqual(CourierSweep.verdict(half, now: now), .keep(.awaitingCollection))
}
/// The last device arriving is what completes it.
func testTheLastDeviceCompletesIt() {
let all = transfer(age: 60 * 60, intended: 3, collected: 3, completed: 60)
XCTAssertTrue(all.isComplete)
XCTAssertEqual(CourierSweep.verdict(all, now: now), .keep(.withinGrace))
}
// MARK: - Grace after delivery
func testDeliveredIsKeptInsideTheGraceWindow() {
let fresh = transfer(age: 2 * 60 * 60, intended: 2, collected: 2,
completed: 60 * 60)
XCTAssertEqual(CourierSweep.verdict(fresh, now: now), .keep(.withinGrace))
}
func testDeliveredIsDroppedOnceTheGraceHasPassed() {
let done = transfer(age: 48 * 60 * 60, intended: 2, collected: 2,
completed: 25 * 60 * 60)
XCTAssertEqual(CourierSweep.verdict(done, now: now), .drop(.delivered))
}
/// ⚠️ Complete but with no recorded completion time. The server knows it
/// landed and not when; keeping it costs a day of storage, dropping it
/// costs the file.
func testCompleteWithNoTimestampIsKept() {
let odd = transfer(age: 40 * 24 * 60 * 60, intended: 2, collected: 2,
completed: nil)
XCTAssertEqual(CourierSweep.verdict(odd, now: now), .keep(.withinGrace))
}
// MARK: - The backstop
func testNeverCollectedIsKeptUntilTheBackstop() {
let waiting = transfer(age: 29 * 24 * 60 * 60, intended: 2, collected: 0)
XCTAssertEqual(CourierSweep.verdict(waiting, now: now),
.keep(.awaitingCollection))
}
func testNeverCollectedIsDroppedAfterTheBackstop() {
let abandoned = transfer(age: 31 * 24 * 60 * 60, intended: 2, collected: 0)
XCTAssertEqual(CourierSweep.verdict(abandoned, now: now), .drop(.expired))
}
/// Over-collection — more acknowledgements than devices — is still
/// complete rather than an error. A device that acknowledges twice should
/// not wedge a transfer open for ever.
func testMoreCollectionsThanDevicesIsComplete() {
let t = transfer(intended: 2, collected: 3, completed: 25 * 60 * 60)
XCTAssertTrue(t.isComplete)
XCTAssertEqual(CourierSweep.verdict(t, now: now), .drop(.delivered))
}
// MARK: - Boundaries
/// Exactly at the boundary drops, so the window is closed at its end and a
/// transfer cannot sit one second short of the cutoff for ever.
func testTheGraceBoundaryIsInclusive() {
let exact = transfer(intended: 1, collected: 1, completed: 24 * 60 * 60)
XCTAssertEqual(CourierSweep.verdict(exact, now: now), .drop(.delivered))
}
func testTheBackstopBoundaryIsInclusive() {
let exact = transfer(age: 30 * 24 * 60 * 60, intended: 1, collected: 0)
XCTAssertEqual(CourierSweep.verdict(exact, now: now), .drop(.expired))
}
/// A shorter retention is honoured, so a self-hoster can choose to hold
/// less without editing code.
func testRetentionIsConfigurable() {
let brief = CourierSweep.Retention(afterDelivery: 60, undelivered: 300)
let t = transfer(intended: 1, collected: 1, completed: 120)
XCTAssertEqual(CourierSweep.verdict(t, retention: brief, now: now),
.drop(.delivered))
XCTAssertEqual(CourierSweep.verdict(t, now: now), .keep(.withinGrace))
}
}
@@ -1,8 +1,6 @@
import XCTest
import Foundation
@testable import EnclaveLattice
@testable import EnclaveAccess
@testable import EnclaveCrypto
// Tenant-agnostic fixtures: ordinals and bit positions only.
private let PUBLIC = Classification(0)
@@ -87,97 +85,6 @@ final class LatticeTests: XCTestCase {
}
}
final class PolicyTests: XCTestCase {
private let policy = Policy(writeRule: .equal)
/// The core inference-control requirement: failing to dominate an object is
/// reported as absence, never as refusal.
func testUndominatedReadIsReportedAsNotFound() {
let decision = policy.decide(
subject: L(INTERNAL),
object: L(RESTRICTED, FINANCE),
mode: .read
)
XCTAssertEqual(decision, .denyNotVisible)
XCTAssertEqual(decision.httpStatus, 404)
}
func testVisibleButLowerObjectIsReadOnly() {
let decision = policy.decide(
subject: L(RESTRICTED, BOTH),
object: L(INTERNAL),
mode: .write
)
XCTAssertEqual(decision, .denyReadOnly)
XCTAssertEqual(decision.httpStatus, 403)
}
func testWriteAtSessionLabelIsAllowed() {
let label = L(CONFIDENTIAL, FINANCE)
XCTAssertEqual(policy.decide(subject: label, object: label, mode: .write), .allow)
}
func testSessionOutsideClearanceIsRejected() {
let clearance = Clearance(maximum: L(CONFIDENTIAL, FINANCE))
XCTAssertEqual(policy.session(at: L(RESTRICTED, FINANCE), for: clearance), .denyOutsideClearance)
}
}
final class TreeTests: XCTestCase {
func testChildMustDominateParent() {
XCTAssertNoThrow(try Tree.validate(child: L(RESTRICTED, FINANCE), parent: L(INTERNAL)))
XCTAssertThrowsError(try Tree.validate(child: L(INTERNAL), parent: L(RESTRICTED, FINANCE)))
}
/// Creating at the session label can never break the tree invariant, because
/// traversal into the parent already required dominating it.
func testNewNodeLabelPreservesInvariant() throws {
let parent = L(INTERNAL)
let session = L(CONFIDENTIAL, FINANCE)
let assigned = Tree.labelForNewNode(session: session, parent: parent)
XCTAssertEqual(assigned, session)
XCTAssertNoThrow(try Tree.validate(child: assigned, parent: parent))
}
func testPolyinstantiatedNamesResolvePerSession() {
let lowID = UUID(), highID = UUID()
let children = [
Node(id: lowID, parentID: nil, name: NameDigest(plaintext: "Q3 Forecast"), label: L(INTERNAL), isFolder: false),
Node(id: highID, parentID: nil, name: NameDigest(plaintext: "Q3 Forecast"), label: L(RESTRICTED, FINANCE), isFolder: false),
]
// The low session sees exactly one file, and does not learn of the other.
XCTAssertEqual(Tree.visibleChildren(of: children, at: L(INTERNAL)).count, 1)
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "Q3 Forecast"), among: children, at: L(INTERNAL)), .found(lowID))
// The cleared session sees both, and its exact-label instance wins.
XCTAssertEqual(Tree.visibleChildren(of: children, at: L(RESTRICTED, FINANCE)).count, 2)
XCTAssertEqual(
Tree.resolve(name: NameDigest(plaintext: "Q3 Forecast"), among: children, at: L(RESTRICTED, FINANCE)),
.found(highID)
)
}
func testMissingAndHiddenNamesAreIndistinguishable() {
let hidden = [Node(id: UUID(), parentID: nil, name: NameDigest(plaintext: "Payroll"), label: L(RESTRICTED, FINANCE), isFolder: false)]
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "Payroll"), among: hidden, at: L(INTERNAL)), .notVisible)
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "No Such File"), among: hidden, at: L(INTERNAL)), .notVisible)
}
func testIncomparableSiblingsWithSameNameAreAmbiguous() {
let a = UUID(), b = UUID()
let children = [
Node(id: a, parentID: nil, name: NameDigest(plaintext: "Notes"), label: L(CONFIDENTIAL, FINANCE), isFolder: false),
Node(id: b, parentID: nil, name: NameDigest(plaintext: "Notes"), label: L(CONFIDENTIAL, LEGAL), isFolder: false),
]
guard case .ambiguous(let ids) = Tree.resolve(name: NameDigest(plaintext: "Notes"), among: children, at: L(RESTRICTED, BOTH)) else {
return XCTFail("expected ambiguity between incomparable instances")
}
XCTAssertEqual(Set(ids), Set([a, b]))
}
}
final class PostgresEncodingTests: XCTestCase {
/// The bit-63 case: a naive UInt64 -> Int64 conversion traps here.
func testHighBitSurvivesSignedRoundTrip() {
@@ -195,56 +102,3 @@ final class PostgresEncodingTests: XCTestCase {
object.postgresBitPattern)
}
}
final class KeyHierarchyTests: XCTestCase {
private let node = UUID()
private let principal = UUID()
private func key(_ ref: KeyRef) -> WrappedKey {
WrappedKey(ciphertext: Data([0xAB]), wrappedTo: ref)
}
func testNodeKeyWrappedToItsOwnLabelIsAccepted() {
let label = L(CONFIDENTIAL, FINANCE)
XCTAssertNoThrow(try KeyHierarchy.validate(nodeID: node, nodeLabel: label, key: key(.label(label))))
}
/// The mistake this module exists to catch: deriving a node key from its
/// parent folder's key. The tree invariant allows a RESTRICTED file inside a
/// CONFIDENTIAL folder, so parent-wrapping would hand the folder key holder
/// content above their clearance regardless of what RLS serves.
func testNodeKeyWrappedToParentFolderIsRejected() {
let parentNode = UUID()
XCTAssertThrowsError(
try KeyHierarchy.validate(
nodeID: node,
nodeLabel: L(RESTRICTED, FINANCE),
key: key(.node(parentNode))
)
) { error in
guard case KeyHierarchyError.nodeKeyNotWrappedToItsLabel = error else {
return XCTFail("expected label-misalignment error, got \(error)")
}
}
}
func testNodeKeyWrappedToADifferentLabelIsRejected() {
XCTAssertThrowsError(
try KeyHierarchy.validate(
nodeID: node,
nodeLabel: L(RESTRICTED, FINANCE),
key: key(.label(L(CONFIDENTIAL, FINANCE)))
)
)
}
func testGrantBeyondClearanceIsRejected() {
let grant = LabelKeyGrant(
label: L(RESTRICTED, BOTH),
principalID: principal,
wrapped: key(.identity(principalID: principal)),
generation: 1
)
let clearance = Clearance(maximum: L(RESTRICTED, FINANCE))
XCTAssertThrowsError(try KeyHierarchy.validate(grant: grant, clearance: clearance))
}
}
+15 -81
View File
@@ -84,87 +84,16 @@ final class SQLScriptTests: XCTestCase {
XCTAssertEqual(statements.count, 2)
}
/// The real schema files are the thing that has to work.
/// 🔴 The tenant scripts exist twice — once at `sql/tenant/` and once at
/// `Sources/EnclaveServer/SQL/tenant/`, which is the copy that gets bundled
/// and therefore the copy that actually runs. They are kept in step by
/// hand, so nothing stops an edit landing in one and not the other, and the
/// symptom would be a migration that behaves differently from the file
/// somebody just read. Cheap to check, and impossible to notice otherwise.
func testTheBundledTenantScriptsMatchTheirSources() throws {
let root = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent()
for name in ["003_delegated_grants.sql", "004_revocation.sql",
"005_courier_transfer.sql"] {
let source = root.appendingPathComponent("sql/tenant/\(name)")
let bundled = root.appendingPathComponent(
"Sources/EnclaveServer/SQL/tenant/\(name)")
let a = try String(contentsOf: source, encoding: .utf8)
let b = try String(contentsOf: bundled, encoding: .utf8)
XCTAssertEqual(a, b, "sql/tenant/\(name) and its bundled copy have drifted")
}
}
/// 🔴 Every table a tenant script names must be schema-qualified.
///
/// A policy body is parsed when the policy is CREATED, with whatever
/// search_path the migration happens to run under — and the migrator's does
/// not include the tenant schema. So `SELECT 1 FROM clearance_revocations`
/// inside a policy is a migration that parses perfectly, passes every test
/// this file had, and fails against a real database with
/// `relation "clearance_revocations" does not exist`.
///
/// That is not hypothetical: it broke the files deployment on 2026-09-03,
/// after the table had already been created, leaving a schema with the
/// table present and the migration unrecorded.
func testTenantScriptsQualifyEveryTableTheyName() throws {
let root = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent()
// `enclave.` is the shared schema and is on the search_path by design;
// information_schema and pg_ are the catalogue.
let allowedPrefixes = [":schema.", "enclave.", "information_schema.", "pg_"]
for name in ["003_delegated_grants", "004_revocation", "005_courier_transfer"] {
let url = root.appendingPathComponent("sql/tenant/\(name).sql")
let body = try String(contentsOf: url, encoding: .utf8)
for (number, line) in body.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
let text = line.trimmingCharacters(in: .whitespaces)
guard !text.hasPrefix("--") else { continue }
for keyword in ["FROM ", "JOIN "] {
guard let range = text.range(of: keyword) else { continue }
// ⚠️ `IS DISTINCT FROM x` and `EXTRACT(y FROM z)` are not
// table references. Matching "FROM " alone reads the column
// after them as a table and reports a constraint as a bug.
let before = text[..<range.lowerBound].uppercased()
if before.hasSuffix("DISTINCT ") || before.contains("EXTRACT(") { continue }
let rest = text[range.upperBound...].trimmingCharacters(in: .whitespaces)
guard let first = rest.split(separator: " ").first.map(String.init),
first.first?.isLetter == true || first.hasPrefix(":")
else { continue }
XCTAssertTrue(
allowedPrefixes.contains(where: { first.hasPrefix($0) }),
"\(name).sql:\(number + 1) names `\(first)` unqualified — "
+ "a policy body is parsed without the tenant schema on the "
+ "search_path, so this fails only against a real database")
}
}
}
}
func testSplitsTheShippedSchemaFiles() throws {
// 🔴 The tenant scripts are in this list too, and were not before.
// They are the ones that run against databases that already exist —
// the template runs once per tenant and never again — so an unparseable
// incremental script breaks upgrades for every deployment while a fresh
// install stays perfectly healthy. That is the failure mode this file
// exists to catch, and it was aimed only at the baseline.
for name in ["sql/001_shared.sql", "sql/002_tenant_template.sql",
"sql/tenant/003_delegated_grants.sql",
"sql/tenant/004_revocation.sql",
"sql/tenant/005_courier_transfer.sql",
"Sources/EnclaveAccounts/SQL/010_accounts.sql"] {
// 🔴 Every script, not just the baseline. The later ones run against
// databases that already exist, so an unparseable incremental script
// breaks upgrades for every deployment while a fresh install stays
// perfectly healthy. That is the failure mode this file exists to
// catch, and it was once aimed only at the baseline.
for name in ["Sources/EnclaveAccounts/SQL/010_accounts.sql",
"Sources/EnclaveAccounts/SQL/020_identities.sql",
"Sources/EnclaveAccounts/SQL/030_rate_limits.sql",
"Sources/EnclaveAccounts/SQL/040_account_devices.sql"] {
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent().appendingPathComponent(name)
@@ -173,7 +102,12 @@ final class SQLScriptTests: XCTestCase {
.replacingOccurrences(of: ":role", with: "\"tenant_test\"")
let statements = SQLScript.statements(script)
XCTAssertGreaterThan(statements.count, 2, name)
// One, not three. The floor is here to catch a script that parsed
// to nothing, and it used to be sized for the file server's tenant
// scripts; two of the four left are legitimately two statements
// long, and a floor tuned to files that no longer exist would only
// have taught somebody to shorten the list.
XCTAssertGreaterThanOrEqual(statements.count, 1, name)
for statement in statements {
XCTAssertFalse(statement.isEmpty, name)
// Every dollar tag opened must be closed within its statement.
-12
View File
@@ -1,12 +0,0 @@
{
"name": "enclave-client-crypto",
"version": "0.1.0",
"description": "Client-side key hierarchy and content encryption for Enclave. Dependency-free, WebCrypto only.",
"type": "module",
"license": "MIT",
"main": "src/index.js",
"scripts": {
"test": "node --test test/*.test.mjs"
},
"engines": { "node": ">=20" }
}
-223
View File
@@ -1,223 +0,0 @@
import { b64, unb64, random, utf8 } from "./bytes.js";
import { KDF_PBKDF2_V1, deriveAuthSecret } from "./kdf.js";
import { kdfSecret } from "./recovery.js";
/**
* The account-side half of a recovery code.
*
* The code already carries 128 bits of its own entropy, so this needs no
* passphrase stretching and no salt round-trip — HKDF over the code is enough,
* and the server keeps only a salted hash of the result.
*/
async function recoveryAuthSecret(entropy) {
const base = await crypto.subtle.importKey(
"raw", utf8(kdfSecret(entropy)), "HKDF", false, ["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0),
info: utf8("flamenet/files/auth-recovery/v1"),
},
base, 256
);
return new Uint8Array(bits);
}
/**
* Client for the shared FlameNet account service.
*
* One credential across products, with no shared key material: the secret this
* sends is derived under an authentication context, while the key that opens
* files is derived under an encryption context from the same passphrase. A
* compromised account service can impersonate you to itself and decrypt
* nothing.
*
* The passphrase never leaves the browser in either case.
*/
export class AccountsAPI {
constructor(baseURL = "") {
this.baseURL = baseURL.replace(/\/$/, "");
}
async #json(method, path, body, { token = null } = {}) {
const headers = {};
if (body) headers["Content-Type"] = "application/json";
// Only the identity routes need one. Registration and sign-in are
// necessarily unauthenticated, and sending a stale token on them would
// be noise at best.
if (token) headers.Authorization = `Bearer ${token}`;
const response = await fetch(`${this.baseURL}${path}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
let reason = `${response.status}`;
try { reason = (await response.json()).reason ?? reason; } catch { /* non-JSON body */ }
throw new Error(reason);
}
// A 201 with no body is a perfectly ordinary answer here, and calling
// .json() on one throws. Read the text first and decide.
const text = await response.text();
return text ? JSON.parse(text) : null;
}
/**
* Stretch parameters for a handle.
*
* An unknown handle returns a deterministic fake, so this cannot be used to
* discover who has an account — and the client cannot tell the difference,
* which is the point.
*/
params(handle) {
return this.#json("GET", `/accounts/${encodeURIComponent(handle.toLowerCase())}/params`);
}
/**
* Register, binding the recovery code to the account as well as to the
* files. A code that restored file access but left you unable to sign in
* would not be a recovery mechanism.
*
* One account service backs every FlameNet product, so there is no handle
* to carry over from anywhere: a username registered here is the username
* everywhere.
*/
async register({ handle, passphrase, recoveryEntropy, identity = null }) {
const kdfSalt = random(KDF_PBKDF2_V1.saltBytes);
const authSecret = await deriveAuthSecret(passphrase, kdfSalt, { params: KDF_PBKDF2_V1 });
await this.#json("POST", "/accounts", {
handle: handle.toLowerCase(),
authSecret: b64(authSecret),
kdfSalt: b64(kdfSalt),
kdfIterations: KDF_PBKDF2_V1.iterations,
recoveryAuthSecret: recoveryEntropy ? b64(await recoveryAuthSecret(recoveryEntropy)) : null,
// Sent with the registration, not after it. The account and its
// first identity land in one transaction, so a tab that closes
// mid-signup leaves nothing behind rather than a handle that is
// taken, unusable, and impossible to enrol into.
identity,
});
}
/**
* Change a passphrase while you still know it.
*
* Two writes, both to this service: the account credential and then the
* identity record. Still not one transaction, because the second needs a
* token minted from the *new* credential. `Session` keeps the private key
* in memory, so a failure between them can be retried without knowing
* either passphrase.
*
* The recovery code is deliberately untouched. It wraps the identity key,
* not the passphrase, so a routine change should not force you to write
* down a new one.
*/
async changePassphrase({ handle, currentPassphrase, newPassphrase }) {
const params = await this.params(handle);
const currentAuthSecret = await deriveAuthSecret(
currentPassphrase, unb64(params.kdfSalt),
{ params: { ...KDF_PBKDF2_V1, iterations: params.kdfIterations } }
);
const kdfSalt = random(KDF_PBKDF2_V1.saltBytes);
const newAuthSecret = await deriveAuthSecret(newPassphrase, kdfSalt, { params: KDF_PBKDF2_V1 });
await this.#json("POST", "/accounts/passphrase", {
handle: handle.toLowerCase(),
currentAuthSecret: b64(currentAuthSecret),
newAuthSecret: b64(newAuthSecret),
newKdfSalt: b64(kdfSalt),
newKdfIterations: KDF_PBKDF2_V1.iterations,
});
}
/**
* Prove the recovery code and set a new passphrase.
*
* `nextEntropy` is the freshly issued code: the old one is retired here as
* well as on the file side, so a code that has already been used somewhere
* does not stay live.
*/
async rotate({ handle, entropy, newPassphrase, nextEntropy }) {
const kdfSalt = random(KDF_PBKDF2_V1.saltBytes);
const newAuthSecret = await deriveAuthSecret(newPassphrase, kdfSalt, { params: KDF_PBKDF2_V1 });
await this.#json("POST", "/accounts/rotate", {
handle: handle.toLowerCase(),
recoveryAuthSecret: b64(await recoveryAuthSecret(entropy)),
newAuthSecret: b64(newAuthSecret),
newKdfSalt: b64(kdfSalt),
newKdfIterations: KDF_PBKDF2_V1.iterations,
newRecoveryAuthSecret: b64(await recoveryAuthSecret(nextEntropy)),
});
}
/** Returns a clearance token for the file server. */
async signIn({ handle, passphrase, product = "files" }) {
const params = await this.params(handle);
const authSecret = await deriveAuthSecret(passphrase, unb64(params.kdfSalt), {
params: { ...KDF_PBKDF2_V1, iterations: params.kdfIterations },
});
return this.#json("POST", "/sessions", {
handle: handle.toLowerCase(),
authSecret: b64(authSecret),
product,
});
}
// ------------------------------------------------------------ identities
//
// These used to live on the file server. They are account state, not file
// state, and holding them here is what lets registration be atomic — see
// `register`. The token decides both who is asking and which product's
// keypair is meant; the client does not get a say in either.
/** The caller's own identity, or null when they have not enrolled. */
identity(token) {
return this.#json("GET", "/identity", null, { token });
}
/**
* Enrol a keypair for a product.
*
* Once per product: overwriting a public key would silently orphan every
* label key already wrapped to the old one, and the server refuses.
*/
enrollIdentity(token, { publicKey, protectedRecord, recoveryRecord = null }) {
return this.#json("POST", "/identity",
{ publicKey, protectedRecord, recoveryRecord }, { token });
}
/**
* Replace the protected records after a passphrase change or a recovery.
* The public key is untouched, so nothing needs re-encrypting.
*/
rekeyIdentity(token, { protectedRecord, recoveryRecord = null }) {
return this.#json("POST", "/identity/rekey",
{ protectedRecord, recoveryRecord }, { token });
}
/**
* Resolve a handle to the principal the file server knows, but only if they
* are cleared for the area you are asking about.
*
* Takes a handle rather than an id on purpose. An "is this person cleared?"
* endpoint keyed by id is a membership oracle, and who else holds a
* compartment is exactly what the file server's read policy refuses to
* disclose. Keyed by handle, every kind of no — unknown account, no
* clearance, not enrolled — returns the same answer, so a caller learns
* nothing they could not learn by attempting the grant itself.
*/
resolveRecipient(token, { handle, label }) {
return this.#json("POST", "/clearance/check", {
handle: handle.toLowerCase(),
classification: label.classification,
compartments: label.compartments,
}, { token });
}
/** Another principal's public key, so a label key can be wrapped to them. */
publicKeyFor(token, principalID) {
return this.#json("GET",
`/identity/principals/${encodeURIComponent(principalID)}`, null, { token });
}
}
-75
View File
@@ -1,75 +0,0 @@
import { b64, unb64 } from "./bytes.js";
/**
* Wire client for the Enclave API.
*
* Two headers carry the session label on every request. Omitting them makes the
* server fall back to the clearance *minimum*, never the maximum, so a bug here
* under-privileges rather than over-privileges.
*/
export class EnclaveAPI {
constructor({ baseURL = "", token }) {
this.baseURL = baseURL;
this.token = token;
this.label = null;
}
setLabel(label) { this.label = label; }
get headers() {
const headers = { Authorization: `Bearer ${this.token}` };
if (this.label) {
headers["X-Enclave-Classification"] = String(this.label.classification);
headers["X-Enclave-Compartments"] = this.label.compartments.join(",");
}
return headers;
}
async #request(method, path, { body, raw } = {}) {
const headers = { ...this.headers };
let payload;
if (raw) {
headers["Content-Type"] = "application/octet-stream";
payload = raw;
} else if (body !== undefined) {
headers["Content-Type"] = "application/json";
payload = JSON.stringify(body);
}
const response = await fetch(`${this.baseURL}${path}`, { method, headers, body: payload });
if (!response.ok) {
const detail = await response.text().catch(() => "");
const error = new Error(`${method} ${path} -> ${response.status}${detail ? `: ${detail}` : ""}`);
error.status = response.status;
throw error;
}
return response;
}
async get(path) {
const response = await this.#request("GET", path);
return response.status === 204 ? null : response.json();
}
async post(path, body) {
const response = await this.#request("POST", path, { body });
return response.status === 204 || response.status === 201 && response.headers.get("content-length") === "0"
? null
: response.json().catch(() => null);
}
async delete(path) {
await this.#request("DELETE", path);
}
async putBytes(path, bytes) {
return (await this.#request("POST", path, { raw: bytes })).json();
}
async getBytes(path) {
const response = await this.#request("GET", path);
return new Uint8Array(await response.arrayBuffer());
}
}
export { b64, unb64 };
-139
View File
@@ -1,139 +0,0 @@
/** Local rather than imported: `kdf.js` exposes the account KDF, and a wallet
* seed is deliberately not derived from anything that module knows about. */
const sha256 = async (data) =>
new Uint8Array(await crypto.subtle.digest("SHA-256", data));
const pbkdf2Sha512 = async (password, salt, iterations, length) => {
const base = await crypto.subtle.importKey("raw", password, "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations, hash: "SHA-512" }, base, length * 8);
return new Uint8Array(bits);
};
/**
* BIP-39 mnemonics, for the wallet only.
*
* 🔴 **Not for anything else in this system.** Files and Messenger recover
* through §2's Crockford codes, and the reasoning for rejecting a word list
* there still stands: 2,048 entries that must be byte-exact is a footgun. The
* wallet accepts that footgun for one reason — a phrase has to be understood by
* software nobody here controls — and pays for it with `verifyWordlist` below.
*
* ⚠️ The wordlist is INJECTED, never bundled into this module. That keeps the
* algorithm testable without it and makes vendoring a separate, checkable step
* rather than 2,048 lines nobody reviews.
*/
/** The published SHA-256 of the BIP-39 English wordlist, as ASCII with a
* trailing newline after every word — the canonical `english.txt`.
*
* ⚠️ If this constant is wrong the check fails CLOSED: a correct list would be
* rejected and nothing would derive. That is the safe direction to be wrong
* in, and the reason the digest is asserted rather than computed at runtime. */
export const ENGLISH_SHA256 =
"2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda";
const bytes = (s) => new TextEncoder().encode(s);
/**
* Check a wordlist before anything derives from it.
*
* 🔴 This is the whole mitigation. A silently corrupted list does not error —
* it produces a DIFFERENT wallet from the same phrase, which is discovered when
* somebody restores and finds an empty account. Verified at load, that becomes
* a failure at startup instead.
*/
export async function verifyWordlist(words, expectedDigest = ENGLISH_SHA256) {
if (!Array.isArray(words) || words.length !== 2048) {
throw new Error(`a BIP-39 wordlist has exactly 2048 words, got ${words?.length}`);
}
const canonical = words.join("\n") + "\n";
const digest = await sha256(bytes(canonical));
const hex = [...digest].map(b => b.toString(16).padStart(2, "0")).join("");
if (hex !== expectedDigest) {
throw new Error(
`wordlist digest ${hex} does not match ${expectedDigest} — ` +
"refusing to derive from a list that may be corrupt");
}
return true;
}
/** Entropy sizes BIP-39 allows, and the phrase length each produces. */
const LENGTHS = new Map([[16, 12], [20, 15], [24, 18], [28, 21], [32, 24]]);
/**
* Entropy to phrase.
*
* The checksum is the first `entropy.length / 4` bits of SHA-256(entropy),
* appended before the split into 11-bit groups. It is what makes a mistyped
* word fail to validate rather than silently name another wallet.
*/
export async function toMnemonic(entropy, words) {
if (!LENGTHS.has(entropy.length)) {
throw new Error(`entropy must be 16, 20, 24, 28 or 32 bytes, got ${entropy.length}`);
}
const digest = await sha256(entropy);
const checksumBits = entropy.length / 4;
let bits = "";
for (const b of entropy) bits += b.toString(2).padStart(8, "0");
for (const b of digest) bits += b.toString(2).padStart(8, "0");
bits = bits.slice(0, entropy.length * 8 + checksumBits);
const out = [];
for (let i = 0; i < bits.length; i += 11) {
out.push(words[parseInt(bits.slice(i, i + 11), 2)]);
}
return out.join(" ");
}
/**
* Phrase back to entropy, refusing anything that does not check out.
*
* ⚠️ Every failure here is loud. A phrase that is the wrong length, contains a
* word not on the list, or fails its checksum is rejected — never quietly
* coerced into the nearest valid thing, which would hand somebody a wallet that
* is not theirs.
*/
export async function fromMnemonic(phrase, words) {
const given = phrase.normalize("NFKD").trim().split(/\s+/);
if (![12, 15, 18, 21, 24].includes(given.length)) {
throw new Error(`a phrase is 12, 15, 18, 21 or 24 words, got ${given.length}`);
}
const index = new Map(words.map((w, i) => [w, i]));
let bits = "";
for (const word of given) {
const at = index.get(word);
if (at === undefined) throw new Error(`"${word}" is not in the wordlist`);
bits += at.toString(2).padStart(11, "0");
}
const entropyBits = (given.length * 11 * 32) / 33;
const entropy = new Uint8Array(entropyBits / 8);
for (let i = 0; i < entropy.length; i++) {
entropy[i] = parseInt(bits.slice(i * 8, i * 8 + 8), 2);
}
const digest = await sha256(entropy);
let expected = "";
for (const b of digest) expected += b.toString(2).padStart(8, "0");
if (bits.slice(entropyBits) !== expected.slice(0, entropyBits / 32)) {
throw new Error("checksum failed — check the phrase for a mistyped word");
}
return entropy;
}
/**
* Phrase to the 64-byte seed everything derives from.
*
* ⚠️ The optional passphrase is BIP-39's, not the account's. A different one
* silently yields a DIFFERENT valid wallet, which is the standard's design and
* a sharp edge worth naming wherever it is offered to somebody.
*/
export async function toSeed(phrase, passphrase = "") {
return pbkdf2Sha512(
bytes(phrase.normalize("NFKD")),
bytes(("mnemonic" + passphrase).normalize("NFKD")),
2048, 64);
}
-42
View File
@@ -1,42 +0,0 @@
// Encoding helpers. No dependencies: everything here is stdlib or WebCrypto.
export const utf8 = (s) => new TextEncoder().encode(s);
export const fromUtf8 = (b) => new TextDecoder().decode(b);
/** Base64, the wire format for every `Data` field the Vapor API expects. */
export function b64(bytes) {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}
export function unb64(text) {
const binary = atob(text);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
export function concat(...parts) {
const total = parts.reduce((n, p) => n + p.length, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const part of parts) { out.set(part, offset); offset += part.length; }
return out;
}
export const random = (n) => crypto.getRandomValues(new Uint8Array(n));
/** Constant-time comparison. Length is not secret; contents are. */
export function equal(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}
export function u32be(n) {
const out = new Uint8Array(4);
new DataView(out.buffer).setUint32(0, n, false);
return out;
}
-102
View File
@@ -1,102 +0,0 @@
import { concat, equal, random, u32be, utf8 } from "./bytes.js";
import { labelBytes } from "./lattice.js";
/**
* Chunked content encryption.
*
* A single AES-GCM blob cannot be decrypted incrementally without buffering the
* whole thing before the tag is checked, which is untenable for large files in
* a browser. So content is framed into independently authenticated chunks.
*
* Independent chunks introduce three attacks, all closed by the AAD:
*
* - **Truncation.** Dropping trailing chunks. The final chunk carries a
* `isLast = 1` flag in its AAD, so a chunk promoted to last by truncation
* fails authentication.
* - **Reordering.** The chunk index is in both the nonce and the AAD.
* - **Cross-file splicing.** The label is in the AAD, and the content key is
* per revision, so chunks cannot migrate between files.
*
* ## Wire format (version 1)
*
* offset size field
* 0 4 magic "ENCL"
* 4 1 version = 1
* 5 4 chunk size, uint32be (plaintext bytes per chunk)
* 9 8 base nonce
* 17 .. chunks, each (chunk size + 16) bytes but the last
*
* chunk i nonce = base nonce (8) || uint32be(i)
* chunk i AAD = label (10) || uint32be(i) || uint8(i == last)
*/
export const CONTENT_V1 = 1;
export const DEFAULT_CHUNK_SIZE = 64 * 1024;
const MAGIC = utf8("ENCL");
const TAG_BYTES = 16;
const HEADER_BYTES = 17;
const importContentKey = (bytes, usages) =>
crypto.subtle.importKey("raw", bytes, { name: "AES-GCM", length: 256 }, false, usages);
const chunkNonce = (baseNonce, index) => concat(baseNonce, u32be(index));
const chunkAAD = (label, index, isLast) =>
concat(labelBytes(label), u32be(index), new Uint8Array([isLast ? 1 : 0]));
export async function encryptContent(contentKey, plaintext, label, chunkSize = DEFAULT_CHUNK_SIZE) {
if (!Number.isInteger(chunkSize) || chunkSize <= 0 || chunkSize > 0xffffffff) {
throw new RangeError("chunkSize must be a positive uint32");
}
const key = await importContentKey(contentKey, ["encrypt"]);
const baseNonce = random(8);
// An empty file is still one chunk, so that it too carries an authenticated
// end marker and cannot be confused with a file truncated to nothing.
const count = Math.max(1, Math.ceil(plaintext.length / chunkSize));
const parts = [concat(MAGIC, new Uint8Array([CONTENT_V1]), u32be(chunkSize), baseNonce)];
for (let i = 0; i < count; i++) {
const slice = plaintext.subarray(i * chunkSize, Math.min((i + 1) * chunkSize, plaintext.length));
const ciphertext = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: chunkNonce(baseNonce, i), additionalData: chunkAAD(label, i, i === count - 1) },
key,
slice
);
parts.push(new Uint8Array(ciphertext));
}
return concat(...parts);
}
export async function decryptContent(contentKey, blob, label) {
if (blob.length < HEADER_BYTES) throw new Error("truncated content header");
if (!equal(blob.subarray(0, 4), MAGIC)) throw new Error("not an Enclave content blob");
if (blob[4] !== CONTENT_V1) throw new Error(`unsupported content version ${blob[4]}`);
const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
const chunkSize = view.getUint32(5, false);
if (chunkSize === 0) throw new Error("invalid chunk size");
const baseNonce = blob.subarray(9, 17);
const body = blob.subarray(HEADER_BYTES);
const stored = chunkSize + TAG_BYTES;
const remainder = body.length % stored;
// A remainder of exactly TAG_BYTES is a legitimate empty final chunk.
if (remainder !== 0 && remainder < TAG_BYTES) throw new Error("malformed final chunk");
const count = Math.floor(body.length / stored) + (remainder === 0 ? 0 : 1);
if (count === 0) throw new Error("content blob has no chunks");
const key = await importContentKey(contentKey, ["decrypt"]);
const chunks = [];
for (let i = 0; i < count; i++) {
const slice = body.subarray(i * stored, Math.min((i + 1) * stored, body.length));
// Authentication fails here if the blob was truncated, reordered, or
// relabelled -- there is no separate integrity check to forget to call.
const plaintext = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: chunkNonce(baseNonce, i), additionalData: chunkAAD(label, i, i === count - 1) },
key,
slice
);
chunks.push(new Uint8Array(plaintext));
}
return concat(...chunks);
}
-96
View File
@@ -1,96 +0,0 @@
import { b64, unb64, random, utf8 } from "./bytes.js";
import { CONTEXT, KDF_PBKDF2_V1, deriveIdentityKEK, kdfParams } from "./kdf.js";
import { kdfSecret } from "./recovery.js";
/**
* The identity keypair: an X25519 pair whose private half is encrypted at rest
* under a key derived from the user's passphrase. The server stores the
* protected record and the public key; it never holds anything that opens the
* private half.
*
* Losing the passphrase loses the data. There is no escrow, and adding one
* would end the zero-knowledge property. A recovery phrase -- a second,
* high-entropy secret that wraps the same private key -- is the standard answer
* and is NOT implemented yet.
*/
export async function generateIdentity() {
return crypto.subtle.generateKey("X25519", true, ["deriveBits"]);
}
export const exportPublicKey = async (publicKey) =>
new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
export const importPublicKey = (raw) =>
crypto.subtle.importKey("raw", raw, "X25519", true, []);
/**
* Encrypt the private key for storage.
*
* The context string is the AAD as well as the KDF domain separator, so a
* record produced for one product cannot be unlocked as another's even with the
* correct passphrase.
*/
export async function protectIdentity(privateKey, passphrase, {
params = KDF_PBKDF2_V1,
context = CONTEXT.files,
} = {}) {
const salt = random(params.saltBytes);
const kek = await deriveIdentityKEK(passphrase, salt, { params, context });
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", privateKey));
const nonce = random(12);
const ciphertext = new Uint8Array(
await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: nonce, additionalData: utf8(context) },
kek,
pkcs8
)
);
return {
v: 1,
kdf: params.id,
// Recorded per account, not looked up from the registry. Raising the
// default iteration count must not lock existing accounts out of their
// own data -- the record has to say what actually produced its key.
iterations: params.iterations,
context,
salt: b64(salt),
nonce: b64(nonce),
privateKey: b64(ciphertext),
};
}
export async function unlockIdentity(record, passphrase) {
if (record.v !== 1) throw new Error(`unsupported identity record version ${record.v}`);
const params = { ...kdfParams(record.kdf), iterations: record.iterations };
if (!Number.isInteger(params.iterations) || params.iterations < 1) {
throw new Error("identity record does not record its iteration count");
}
const kek = await deriveIdentityKEK(passphrase, unb64(record.salt), {
params,
context: record.context,
});
const pkcs8 = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: unb64(record.nonce), additionalData: utf8(record.context) },
kek,
unb64(record.privateKey)
);
return crypto.subtle.importKey("pkcs8", pkcs8, "X25519", true, ["deriveBits"]);
}
/**
* Wrap the same private key under a recovery code.
*
* The two records are independent: they use different contexts, so neither
* secret reveals the other, and changing the passphrase does not invalidate the
* recovery code. Both must be replaced to fully rotate an identity.
*/
export async function protectIdentityWithRecovery(privateKey, entropy, { params = KDF_PBKDF2_V1 } = {}) {
return protectIdentity(privateKey, kdfSecret(entropy), {
params,
context: CONTEXT.filesRecovery,
});
}
export async function unlockWithRecovery(record, entropy) {
return unlockIdentity(record, kdfSecret(entropy));
}
-8
View File
@@ -1,8 +0,0 @@
export * from "./bytes.js";
export * from "./lattice.js";
export * from "./kdf.js";
export * from "./identity.js";
export * from "./wrap.js";
export * from "./keys.js";
export * from "./names.js";
export * from "./content.js";
-127
View File
@@ -1,127 +0,0 @@
import { utf8 } from "./bytes.js";
/**
* Passphrase stretching, in two stages.
*
* master = PBKDF2-SHA256(passphrase, salt, iterations)
* productKEK = HKDF-SHA256(master, info = context)
*
* The split exists so that one credential can back several FlameNet products
* without any of them sharing key material. The expensive stretch happens once;
* each product then derives its own key under a distinct context string, so
* compromise of the Messenger identity key yields nothing about the Files
* identity key and vice versa.
*
* ⚠️ Domain separation cannot be retrofitted. Adding a context string later
* changes every derived key and locks every existing account out of its data.
* If shared login is on the roadmap, it has to be here from the first account.
*
* PBKDF2-SHA256 is the stretch because it is available in WebCrypto everywhere
* with no dependency. Argon2id resists GPU attack materially better but needs a
* WASM bundle, which contradicts the dependency-free posture this engine shares
* with flamenet-e2e. Parameters are therefore versioned and recorded per
* account, so Argon2id can arrive as id 2 without stranding anyone.
*
* Iteration count follows OWASP's PBKDF2-SHA256 guidance.
*/
export const KDF_PBKDF2_V1 = Object.freeze({
id: 1,
name: "PBKDF2-SHA256",
iterations: 650_000,
saltBytes: 16,
});
export const KDF_REGISTRY = Object.freeze({ 1: KDF_PBKDF2_V1 });
/** Per-product context strings. Never reuse one across products. */
export const CONTEXT = Object.freeze({
files: "flamenet/files/identity/v1",
messenger: "flamenet/messenger/identity/v1",
// The recovery code wraps the same private key under its own context, so
// the two records are independent: neither secret reveals the other, and a
// passphrase change does not invalidate the recovery code.
filesRecovery: "flamenet/files/recovery/v1",
// 🔴 The wallet seed is NOT derived from the passphrase — see SPEC §8.1.
// This context wraps a seed that already exists, so the account can open
// the wallet without the phrase being typed. Changing the passphrase
// re-wraps this record and leaves the seed, and therefore every address,
// exactly where it was.
walletSeed: "flamenet/wallet/seed/v1",
});
export function kdfParams(id) {
const params = KDF_REGISTRY[id];
if (!params) throw new Error(`unknown KDF id ${id}`);
return params;
}
/**
* Authentication contexts.
*
* The secret sent to the account service is derived from the same passphrase as
* the encryption key, but under a *different* context — so a fully compromised
* account service holds something that can log in as you and nothing that can
* decrypt a single file. The two derivations are cryptographically unrelated.
*/
export const AUTH_CONTEXT = Object.freeze({
files: "flamenet/files/auth/v1",
messenger: "flamenet/messenger/auth/v1",
});
/** Stage one: the expensive stretch. Shared across products, never used directly. */
async function deriveMaster(passphrase, salt, params) {
if (params.id !== 1) throw new Error(`KDF id ${params.id} is not implemented`);
const base = await crypto.subtle.importKey("raw", utf8(passphrase), "PBKDF2", false, ["deriveBits"]);
return crypto.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations: params.iterations, hash: "SHA-256" },
base,
256
);
}
/**
* Stage two: the key-encryption key protecting this product's identity private
* key at rest. Never leaves the device, never stored.
*/
export async function deriveIdentityKEK(passphrase, salt, {
params = KDF_PBKDF2_V1,
context = CONTEXT.files,
} = {}) {
const master = await deriveMaster(passphrase, salt, params);
const base = await crypto.subtle.importKey("raw", master, "HKDF", false, ["deriveKey"]);
return crypto.subtle.deriveKey(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(context) },
base,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
/**
* Raw key bytes for a context, rather than a CryptoKey.
*
* Used for the authentication secret, which is sent to the account service. The
* expensive stretch happens here, on the client, so the server can store a
* plain salted hash: brute-forcing it still costs an attacker the full
* iteration count per guess.
*/
export async function deriveBytes(passphrase, salt, {
params = KDF_PBKDF2_V1,
context,
length = 32,
} = {}) {
if (!context) throw new Error("a context string is required");
const master = await deriveMaster(passphrase, salt, params);
const base = await crypto.subtle.importKey("raw", master, "HKDF", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(context) },
base,
length * 8
);
return new Uint8Array(bits);
}
export const deriveAuthSecret = (passphrase, salt, options = {}) =>
deriveBytes(passphrase, salt, { ...options, context: options.context ?? AUTH_CONTEXT.files });
-44
View File
@@ -1,44 +0,0 @@
import { random } from "./bytes.js";
import { labelBytes } from "./lattice.js";
import { wrapToPublicKey, unwrapWithPrivateKey, wrapWithKey, unwrapWithKey } from "./wrap.js";
/**
* The key hierarchy.
*
* identity key per user, unlocked by passphrase
* | wraps
* label key one per label in use; granted to each cleared principal
* | wraps
* node key one per file or folder
* | wraps
* content key one per revision
*
* Every level is wrapped with the canonical label encoding as AAD. A node key
* is wrapped to its own LABEL key and never to its parent folder's node key --
* the tree invariant allows a RESTRICTED file inside a CONFIDENTIAL folder, so
* parent-derived keys would hand every folder-key holder content above their
* clearance. `KeyHierarchy.validate` in Swift and the `node_keys` trigger in
* Postgres both refuse the misalignment; this module simply never creates it.
*/
export const createLabelKey = () => random(32);
export const createNodeKey = () => random(32);
export const createContentKey = () => random(32);
/** Grant a label key to a principal, by wrapping it to their identity public key. */
export const grantLabelKey = (labelKey, label, recipientPublicKey) =>
wrapToPublicKey(recipientPublicKey, labelKey, labelBytes(label));
export const acceptLabelKey = (blob, label, privateKey, publicKey) =>
unwrapWithPrivateKey(privateKey, publicKey, blob, labelBytes(label));
export const wrapNodeKey = (nodeKey, labelKey, label) =>
wrapWithKey(labelKey, nodeKey, labelBytes(label));
export const unwrapNodeKey = (blob, labelKey, label) =>
unwrapWithKey(labelKey, blob, labelBytes(label));
export const wrapContentKey = (contentKey, nodeKey, label) =>
wrapWithKey(nodeKey, contentKey, labelBytes(label));
export const unwrapContentKey = (blob, nodeKey, label) =>
unwrapWithKey(nodeKey, blob, labelBytes(label));
-68
View File
@@ -1,68 +0,0 @@
// The lattice, mirrored from Sources/EnclaveLattice/Label.swift.
//
// The Swift implementation is the source of truth. This copy exists so the
// client can decide locally which labels a user may work at, and -- more
// importantly -- so it can produce the canonical label encoding that binds
// every ciphertext to its label. Keep the two in step; `test/lattice.test.mjs`
// covers the same cases as the Swift suite.
/** @param {number} classification @param {number[]} compartments bit indices 0..63 */
export function label(classification, compartments = []) {
for (const bit of compartments) {
if (!Number.isInteger(bit) || bit < 0 || bit > 63) {
throw new RangeError(`compartment bit ${bit} out of range 0..63`);
}
}
return {
classification,
compartments: [...new Set(compartments)].sort((a, b) => a - b),
};
}
export function compartmentMask({ compartments }) {
let mask = 0n;
for (const bit of compartments) mask |= 1n << BigInt(bit);
return mask;
}
/** `a ⊒ b` -- at least as high on the ladder AND a superset of compartments. */
export function dominates(a, b) {
if (a.classification < b.classification) return false;
const maskA = compartmentMask(a), maskB = compartmentMask(b);
return (maskA & maskB) === maskB;
}
export function incomparable(a, b) {
return !dominates(a, b) && !dominates(b, a);
}
export function leastUpperBound(a, b) {
return label(
Math.max(a.classification, b.classification),
[...new Set([...a.compartments, ...b.compartments])]
);
}
export function permits(clearance, candidate) {
return dominates(clearance.maximum, candidate) && dominates(candidate, clearance.minimum);
}
/**
* Canonical 10-byte label encoding: int16be classification || uint64be mask.
*
* This is the AAD for every wrap and every content chunk, which is what makes
* a label something the server cannot change. Relabelling a row in the database
* does not reclassify its contents -- it makes them fail to decrypt, loudly.
* A downgrade therefore *must* go through a client that re-encrypts, which is
* exactly the regrade workflow the schema models.
*
* The layout deliberately matches the `classification` and `compartments`
* columns so the two representations cannot drift.
*/
export function labelBytes(l) {
const out = new Uint8Array(10);
const view = new DataView(out.buffer);
view.setInt16(0, l.classification, false);
view.setBigUint64(2, compartmentMask(l), false);
return out;
}
-62
View File
@@ -1,62 +0,0 @@
import { concat, utf8, fromUtf8, random } from "./bytes.js";
import { labelBytes } from "./lattice.js";
/**
* Filenames.
*
* The server must be able to enforce uniqueness and resolve a path component
* without learning any name. Randomised encryption makes two encryptions of
* "Payroll" differ, so uniqueness runs on a deterministic digest instead:
*
* digest = HMAC-SHA256(folder_key, NFC(name))
*
* Keyed with the containing folder's node key, so the server cannot invert a
* name, cannot dictionary-attack it, and cannot tell that two folders hold a
* file of the same name. For root-level entries the label key stands in as the
* folder key.
*
* Comparison is case-sensitive; only Unicode normalisation is applied. Adding
* case folding later would change every digest.
*/
export async function nameDigest(folderKey, name) {
const key = await crypto.subtle.importKey(
"raw", folderKey, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]
);
const mac = await crypto.subtle.sign("HMAC", key, utf8(name.normalize("NFC")));
return new Uint8Array(mac);
}
const NAME_V1 = 1;
/**
* Encrypt a filename. The AAD binds the ciphertext to both its label and its
* digest, so name ciphertexts cannot be swapped between rows by the server.
*/
export async function encryptName(folderKey, name, label) {
const digest = await nameDigest(folderKey, name);
const key = await crypto.subtle.importKey("raw", folderKey, { name: "AES-GCM" }, false, ["encrypt"]);
const nonce = random(12);
const ciphertext = new Uint8Array(
await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: nonce, additionalData: concat(labelBytes(label), digest) },
key,
utf8(name.normalize("NFC"))
)
);
return { digest, ciphertext: concat(new Uint8Array([NAME_V1]), nonce, ciphertext) };
}
export async function decryptName(folderKey, blob, digest, label) {
if (blob[0] !== NAME_V1) throw new Error(`unsupported name version ${blob[0]}`);
const key = await crypto.subtle.importKey("raw", folderKey, { name: "AES-GCM" }, false, ["decrypt"]);
const plaintext = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: blob.subarray(1, 13),
additionalData: concat(labelBytes(label), digest),
},
key,
blob.subarray(13)
);
return fromUtf8(new Uint8Array(plaintext));
}
-119
View File
@@ -1,119 +0,0 @@
import { utf8 } from "./bytes.js";
/**
* Recovery codes.
*
* Losing a passphrase otherwise loses the data outright: the server holds no
* key that opens anything. A recovery code is a second, high-entropy secret
* that wraps the *same* identity private key under a different context, so
* either secret unlocks the account and neither reveals the other.
*
* ## Why a code rather than a word list
*
* A twelve-word phrase is friendlier to transcribe, and BIP-39 is the obvious
* source. Vendoring that list is a deliberate supply-chain decision -- 2048
* words that must be byte-exact, since a single wrong entry silently produces
* codes that cannot be decoded -- so it is not something to improvise. This
* module encodes to Crockford base32 instead, which needs no vendored data and
* is unambiguous by construction: `I`, `L`, `O` and `U` are absent, and `O`/`0`
* and `I`/`L`/`1` are folded on input so a mistranscription still decodes.
*
* `encode`/`decode` are the only places the alphabet appears, so a word-list
* codec can be added beside them without touching anything else.
*
* ## Format
*
* 128 bits entropy || 12 bits checksum = 140 bits = 28 base32 characters
* grouped as XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
*
* The checksum catches a mistyped code in microseconds, before the deliberately
* slow key derivation runs.
*/
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const ENTROPY_BYTES = 16;
const CHECKSUM_BITS = 12;
const CODE_LENGTH = 28;
async function checksum(entropy) {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", entropy));
// Top 12 bits of the digest.
return (digest[0] << 4) | (digest[1] >> 4);
}
function group(code) {
return code.match(/.{1,4}/g).join("-");
}
/**
* Fold the ambiguous glyphs and drop formatting. A code read off paper as
* "O" for zero or "l" for one still decodes.
*/
export function normalize(text) {
return text
.toUpperCase()
// Only O and I/L fold. Q is a *valid* Crockford character -- folding it
// would corrupt every code that contains one.
.replace(/O/g, "0")
.replace(/[IL]/g, "1")
.replace(/[^0-9A-Z]/g, "");
}
export async function generateRecoveryCode() {
const entropy = crypto.getRandomValues(new Uint8Array(ENTROPY_BYTES));
return { entropy, code: await encode(entropy) };
}
export async function encode(entropy) {
if (entropy.length !== ENTROPY_BYTES) {
throw new RangeError(`entropy must be ${ENTROPY_BYTES} bytes`);
}
let value = 0n;
for (const byte of entropy) value = (value << 8n) | BigInt(byte);
value = (value << BigInt(CHECKSUM_BITS)) | BigInt(await checksum(entropy));
let out = "";
for (let i = 0; i < CODE_LENGTH; i++) {
out = ALPHABET[Number(value & 31n)] + out;
value >>= 5n;
}
return group(out);
}
export async function decode(text) {
const normalized = normalize(text);
if (normalized.length !== CODE_LENGTH) {
throw new Error(`recovery code must be ${CODE_LENGTH} characters, got ${normalized.length}`);
}
let value = 0n;
for (const character of normalized) {
const index = ALPHABET.indexOf(character);
if (index < 0) throw new Error(`invalid character '${character}' in recovery code`);
value = (value << 5n) | BigInt(index);
}
const provided = Number(value & ((1n << BigInt(CHECKSUM_BITS)) - 1n));
value >>= BigInt(CHECKSUM_BITS);
const entropy = new Uint8Array(ENTROPY_BYTES);
for (let i = ENTROPY_BYTES - 1; i >= 0; i--) {
entropy[i] = Number(value & 255n);
value >>= 8n;
}
if (await checksum(entropy) !== provided) {
throw new Error("recovery code checksum does not match — check for a typo");
}
return entropy;
}
/**
* The string fed to the KDF. Derived from the code rather than used raw so that
* formatting differences -- grouping, case, folded glyphs -- cannot produce two
* different keys from one code.
*/
export function kdfSecret(entropy) {
return [...entropy].map((b) => b.toString(16).padStart(2, "0")).join("");
}
export { utf8 };
-122
View File
@@ -1,122 +0,0 @@
import { labelBytes } from "./lattice.js";
import { createLabelKey, grantLabelKey, acceptLabelKey,
wrapNodeKey, unwrapNodeKey } from "./keys.js";
/**
* Rotating a label key, which is what makes a revocation mean anything.
*
* Withdrawing somebody's grant removes a row. The key is already on their
* device, and every node key at that label is still wrapped to it, so on its
* own that changes nothing about what they can read. Rotation is the part that
* does: a new label key, granted to everyone who remains, and every node key
* re-wrapped under it.
*
* 🔴 **The server cannot do any of this**, which is why it lives here. It holds
* no key that opens a label key, a node key or a content key. It records that a
* rotation was asked for and which generation ends it, and waits for a cleared
* client to say it is done.
*/
/**
* 🔴 **Grants first, re-wraps second, and this order is the entire safety
* argument.**
*
* Re-wrapping node keys first and dying before the grants land leaves every
* file at that label wrapped to a key NOBODY HOLDS. That is not a failed
* rotation, it is permanent data loss for everyone still cleared — the revoked
* person included, which is the only sense in which it works.
*
* The other order fails softly. Grants land, the process dies, and the node
* keys are still at the old generation: everyone can read everything exactly as
* before, the revoked person included, and the rotation can simply be run
* again. One order loses the data; the other loses only the property you were
* trying to gain, temporarily.
*
* ⚠️ So a partial rotation is a normal state, not a corrupt one, and this is
* written to be re-run. `alreadyAtNewGeneration` skips node keys a previous
* attempt finished, so resuming costs only the work still outstanding.
*/
export async function rotateLabelKey({
label,
// The caller's own identity, to open the old label key.
privateKey,
publicKey,
// The wrapped old label key, as this principal holds it.
wrappedOldLabelKey,
// 🔴 This principal's grant at `toGeneration`, if a previous attempt got
// far enough to write one. Passing it is what makes a resume safe; see
// below.
wrappedNewLabelKey = null,
// Everyone who keeps access, as { principalID, publicKey }. The revoked
// principal is simply absent — there is no "exclude" step to get wrong.
remaining,
// Node keys at this label: { nodeID, wrapped, generation }.
nodeKeys,
// The generation this rotation produces.
toGeneration,
// Applied in order; each may throw to abort the rotation.
persistGrant, // ({ principalID, wrapped, generation }) => Promise
persistNodeKey, // ({ nodeID, wrapped, generation }) => Promise
} = {}) {
if (!Array.isArray(remaining) || remaining.length === 0) {
// Rotating to nobody would wrap every file at this label under a key
// that is then discarded. Refusing is the only safe answer: a label
// with no cleared holders needs a decision about its data, not a
// silently unopenable set of files.
throw new Error("rotation needs at least one remaining principal");
}
const aad = labelBytes(label);
const oldLabelKey = await acceptLabelKey(wrappedOldLabelKey, label, privateKey, publicKey);
// 🔴 **A resume must reuse the key the abandoned run minted, not make a
// fresh one.**
//
// Minting again looks harmless and loses data. Both runs write generation
// `toGeneration`, so the node keys the first run finished are wrapped under
// key A and the rest under key B, while every grant now names B. The rows
// are consistent, the generations agree, and the files from the first run
// open under nothing anybody holds.
//
// The abandoned run's key is recoverable precisely because grants are
// written first: if it re-wrapped even one node key, it had already granted
// itself the new key, so this principal's grant at the new generation IS
// that key. That ordering was chosen for crash-safety and turns out to be
// what makes resuming possible at all.
const newLabelKey = wrappedNewLabelKey
? await acceptLabelKey(wrappedNewLabelKey, label, privateKey, publicKey)
: createLabelKey();
const resumed = Boolean(wrappedNewLabelKey);
// 1. Everyone who remains can open the new key BEFORE anything is wrapped
// under it.
const grants = [];
for (const principal of remaining) {
const wrapped = await grantLabelKey(newLabelKey, label, principal.publicKey);
await persistGrant({
principalID: principal.principalID,
wrapped,
generation: toGeneration,
});
grants.push(principal.principalID);
}
// 2. Now the node keys. Anything already at the new generation was done by
// an earlier attempt.
let rewrapped = 0;
let skipped = 0;
for (const node of nodeKeys) {
if (node.generation >= toGeneration) { skipped += 1; continue; }
const nodeKey = await unwrapNodeKey(node.wrapped, oldLabelKey, label);
const wrapped = await wrapNodeKey(nodeKey, newLabelKey, label);
await persistNodeKey({
nodeID: node.nodeID,
wrapped,
generation: toGeneration,
});
rewrapped += 1;
}
return { generation: toGeneration, granted: grants, rewrapped, skipped, resumed,
aadBytes: aad.length };
}
-478
View File
@@ -1,478 +0,0 @@
import { b64, unb64, utf8, fromUtf8 } from "./bytes.js";
import { label as makeLabel, permits } from "./lattice.js";
import {
generateIdentity, protectIdentity, unlockIdentity, exportPublicKey,
protectIdentityWithRecovery, unlockWithRecovery,
} from "./identity.js";
import {
generateRecoveryCode, decode as decodeRecoveryCode, encode as encodeRecoveryCode,
} from "./recovery.js";
import {
createLabelKey, createNodeKey, createContentKey,
grantLabelKey, acceptLabelKey, wrapNodeKey, unwrapNodeKey,
wrapContentKey, unwrapContentKey,
} from "./keys.js";
import { encryptName, decryptName } from "./names.js";
import { encryptContent, decryptContent } from "./content.js";
import {
createShareSecret, sealShare, openShare as unsealShare,
encodeShareSecret, decodeShareSecret,
} from "./shares.js";
const labelKey = (l) => `${l.classification}:${l.compartments.join(",")}`;
/**
* An unlocked working session.
*
* Holds the identity private key and any unwrapped label keys in memory only.
* Nothing here is persisted; closing the tab forgets everything, which is the
* intended behaviour.
*/
export class Session {
#identity;
#labelKeys = new Map();
constructor(api, identity, clearance, { accounts = null, token = null } = {}) {
this.api = api;
// Identity records live on the account service, not the file server, so
// a session needs both clients: one for files, one for who you are.
this.accounts = accounts;
this.token = token;
this.#identity = identity;
this.clearance = clearance;
this.label = null;
/// Set only when a code was just issued. Never persisted.
this.recoveryCode = null;
}
/**
* Unlock an existing identity, or enrol a new one.
*
* Enrolment is once per principal: overwriting a public key would orphan
* every label key already wrapped to the old one, and the server refuses.
*
* On enrolment this returns a `recoveryCode`, and it is the only time it
* exists anywhere. It is not stored, not derivable from the passphrase, and
* cannot be reissued -- only replaced by rekeying with a known secret.
*/
static async open({ api, accounts, token, passphrase, clearance, recoveryEntropy = null }) {
// File requests still need a label, and the clearance minimum is always
// assertable. The identity call itself no longer does: it goes to the
// account service, which knows nothing about labels.
api.setLabel(clearance.minimum);
const existing = await accounts.identity(token);
if (existing?.protectedRecord) {
const record = JSON.parse(existing.protectedRecord);
const privateKey = await unlockIdentity(record, passphrase);
const publicKey = await crypto.subtle.importKey(
"raw", unb64(existing.publicKey), "X25519", true, []
);
return new Session(api, { privateKey, publicKey }, clearance, { accounts, token });
}
const pair = await generateIdentity();
// Supplied by the caller when the same code must also register with the
// account service; generated here otherwise.
const { entropy, code } = recoveryEntropy
? { entropy: recoveryEntropy, code: await encodeRecoveryCode(recoveryEntropy) }
: await generateRecoveryCode();
const [record, recovery] = await Promise.all([
protectIdentity(pair.privateKey, passphrase),
protectIdentityWithRecovery(pair.privateKey, entropy),
]);
await accounts.enrollIdentity(token, {
publicKey: b64(await exportPublicKey(pair.publicKey)),
protectedRecord: JSON.stringify(record),
recoveryRecord: JSON.stringify(recovery),
});
const session = new Session(api, pair, clearance, { accounts, token });
session.recoveryCode = code;
return session;
}
/**
* Adopt an identity the caller has already built.
*
* Registration now sends the identity along with the account, in one
* transaction, so by the time there is a token to sign in with the keypair
* is already stored. Re-deriving it here would be wasted work — and worse,
* would race the copy the server just wrote.
*/
static enrolled({ api, accounts, token, pair, clearance, recoveryCode = null }) {
api.setLabel(clearance.minimum);
const session = new Session(api, pair, clearance, { accounts, token });
session.recoveryCode = recoveryCode;
return session;
}
/**
* Unlock with a recovery code and set a new passphrase.
*
* The identity keypair is unchanged, so every label key already wrapped to
* it stays valid and no re-encryption is needed. A fresh recovery code is
* issued and the old one stops working, because leaving a code in play that
* the user has already had cause to use somewhere is the wrong default.
*/
static async recover({ api, accounts, token, code, newPassphrase, clearance, nextEntropy = null }) {
api.setLabel(clearance.minimum);
const existing = await accounts.identity(token);
if (!existing?.recoveryRecord) {
throw new Error("this account has no recovery code on file");
}
const entropy = await decodeRecoveryCode(code);
const privateKey = await unlockWithRecovery(JSON.parse(existing.recoveryRecord), entropy);
const publicKey = await crypto.subtle.importKey(
"raw", unb64(existing.publicKey), "X25519", true, []
);
const next = nextEntropy
? { entropy: nextEntropy, code: await encodeRecoveryCode(nextEntropy) }
: await generateRecoveryCode();
const [record, recovery] = await Promise.all([
protectIdentity(privateKey, newPassphrase),
protectIdentityWithRecovery(privateKey, next.entropy),
]);
await accounts.rekeyIdentity(token, {
protectedRecord: JSON.stringify(record),
recoveryRecord: JSON.stringify(recovery),
});
const session = new Session(api, { privateKey, publicKey }, clearance, { accounts, token });
session.recoveryCode = next.code;
return session;
}
/** Load and unwrap every label key granted to this principal. */
async loadLabelKeys() {
const grants = await this.api.get("/api/keys/labels");
for (const grant of grants ?? []) {
const l = makeLabel(grant.classification, grant.compartments);
try {
const key = await acceptLabelKey(
unb64(grant.wrappedKey), l, this.#identity.privateKey, this.#identity.publicKey
);
this.#labelKeys.set(labelKey(l), key);
} catch {
// A grant that will not unwrap is not fatal: it may have been
// wrapped to a superseded identity key. Skip it rather than
// failing the whole session.
}
}
return [...this.#labelKeys.keys()];
}
/**
* Ensure a label key exists for `l`, creating and self-granting one if not.
*
* The server's insert policy allows self-grant at exactly the session label
* and nothing else, so this cannot widen anyone's clearance -- it only
* materialises a key for a label the caller could already assert.
*/
async ensureLabelKey(l) {
if (!permits(this.clearance, l)) throw new Error("label exceeds clearance");
const existing = this.#labelKeys.get(labelKey(l));
if (existing) return existing;
const key = createLabelKey();
const previousLabel = this.api.label;
this.api.setLabel(l);
try {
await this.api.post("/api/keys/labels", {
classification: l.classification,
compartments: l.compartments,
wrappedKey: b64(await grantLabelKey(key, l, this.#identity.publicKey)),
});
} finally {
this.api.setLabel(previousLabel);
}
this.#labelKeys.set(labelKey(l), key);
return key;
}
/**
* Switch to an area.
*
* Deliberately does *not* mint a key. Minting on arrival was the reason
* sharing an area almost never worked: two people cleared for the same
* label each self-granted a different key the moment they looked at it, and
* the later gift then collided with the key they had already made for
* themselves. Browsing is not a reason to own a key.
*
* A key is minted on the first write instead, by which point the caller has
* committed to putting something there and a collision is a real conflict
* rather than an artefact of having glanced at a folder.
*/
async use(l) {
if (!permits(this.clearance, l)) throw new Error("label exceeds clearance");
this.label = l;
this.api.setLabel(l);
return this.#labelKeys.get(labelKey(l)) ?? null;
}
/// The key for the current label, minting one if this is the first write.
async requireLabelKey() {
if (!this.label) throw new Error("Choose an area first.");
return this.ensureLabelKey(this.label);
}
/**
* The key for the current label, if this session holds one.
*
* Throws rather than minting. Reading paths use it, and a read that quietly
* created a key would produce a key that decrypts nothing — the confusing
* failure being a successful-looking operation that returns garbage.
* Writers call `requireLabelKey` first.
*/
get currentLabelKey() {
// Checked rather than left to fall through: without it a read before
// any area is chosen dies inside the key-name helper with "cannot read
// properties of null", which sends whoever hits it looking at the
// crypto instead of at the missing step.
if (!this.label) throw new Error("Choose an area first.");
const key = this.#labelKeys.get(labelKey(this.label));
if (!key) {
throw new Error("You don't have a key for this area yet.");
}
return key;
}
/** The key that names a folder's children. Root entries use the label key. */
async folderKey(folderID) {
if (!folderID) return this.currentLabelKey;
const record = await this.api.get(`/api/keys/nodes/${folderID}`);
return unwrapNodeKey(unb64(record.wrappedKey), this.currentLabelKey, this.label);
}
/** List a folder, decrypting each visible child's name locally. */
async list(folderID) {
const rows = await this.api.get(
folderID ? `/api/nodes/${folderID}/children` : "/api/nodes/roots"
);
// Inside a folder, every child is named under that folder's node key,
// which the caller necessarily holds to have got here at all.
//
// A root listing is different: it spans labels, and each entry was
// named under the key of its *own* label. Using the session's label key
// for all of them leaves a cleared user staring at rows they can see but
// cannot read — which is worse than not showing them at all.
const folderNodeKey = folderID ? await this.folderKey(folderID) : null;
return Promise.all((rows ?? []).map(async (row) => {
const rowLabel = makeLabel(row.classification, row.compartments);
const key = folderNodeKey ?? this.#labelKeys.get(labelKey(rowLabel));
let name = null;
if (key) {
try {
name = await decryptName(
key, unb64(row.nameCiphertext), unb64(row.nameDigest), rowLabel
);
} catch {
// Visible to the database but not decryptable here — a label
// key this session has not been granted.
name = null;
}
}
return { ...row, label: rowLabel, name };
}));
}
async #create({ name, parentID, isFolder, blobID, sizeBytes }) {
await this.requireLabelKey();
const folderKey = await this.folderKey(parentID);
const nodeKeyBytes = createNodeKey();
const { digest, ciphertext } = await encryptName(folderKey, name, this.label);
return this.api.post("/api/nodes", {
parentID: parentID ?? null,
nameDigest: b64(digest),
nameCiphertext: b64(ciphertext),
isFolder,
wrappedKey: b64(await wrapNodeKey(nodeKeyBytes, this.currentLabelKey, this.label)),
blobID: blobID ?? null,
sizeBytes: sizeBytes ?? 0,
});
}
createFolder(name, parentID = null) {
return this.#create({ name, parentID, isFolder: true });
}
/**
* Encrypt then upload. The content key is wrapped to the *node* key, which
* is itself wrapped to the label key -- never to the parent folder's key.
*/
async uploadFile(name, bytes, parentID = null) {
await this.requireLabelKey();
const folderKey = await this.folderKey(parentID);
const nodeKeyBytes = createNodeKey();
const contentKeyBytes = createContentKey();
const ciphertext = await encryptContent(contentKeyBytes, bytes, this.label);
const blob = await this.api.putBytes("/api/blobs", ciphertext);
const { digest, ciphertext: nameCiphertext } = await encryptName(folderKey, name, this.label);
return this.api.post("/api/nodes", {
parentID: parentID ?? null,
nameDigest: b64(digest),
nameCiphertext: b64(nameCiphertext),
isFolder: false,
wrappedKey: b64(await wrapNodeKey(nodeKeyBytes, this.currentLabelKey, this.label)),
contentKey: b64(await wrapContentKey(contentKeyBytes, nodeKeyBytes, this.label)),
blobID: blob.id,
sizeBytes: bytes.length,
});
}
/**
* Change the passphrase, rekeying both halves.
*
* The account credential changes first, then the identity record. If the
* second write fails the account is already on the new passphrase while the
* identity record still opens with the old one — so this retries using the
* private key already held in memory, which needs neither passphrase.
*/
async changePassphrase({ handle, currentPassphrase, newPassphrase, accounts = null }) {
const service = accounts ?? this.accounts;
await service.changePassphrase({ handle, currentPassphrase, newPassphrase });
const record = await protectIdentity(this.#identity.privateKey, newPassphrase);
// The old token still verifies until it expires, and the rekey is
// authorised by the token rather than the passphrase, so this does not
// need a fresh sign-in to land.
await service.rekeyIdentity(this.token, { protectedRecord: JSON.stringify(record) });
}
/**
* Give someone else the key to the area you are working in.
*
* This is what makes the system usable by more than one person. Until it
* existed every account was an island: two people cleared for the same
* label could see each other's rows and decrypt none of them, because each
* had minted its own key for that label on first use.
*
* The key is wrapped to the recipient's public key here, in this tab. The
* server stores a blob it cannot open and never sees the label key — which
* is why this cannot be an administrative action performed on your behalf.
*
* Refused unless they are cleared, which the account service decides. That
* check is defence in depth rather than the load-bearing control: a label
* key on its own opens nothing, because every row at that label stays hidden
* from a session whose token does not carry the clearance.
*/
async shareArea(handle) {
if (!this.label) throw new Error("Choose an area before sharing it.");
// Not `requireLabelKey`: giving away a key you have never used would
// mint one on the spot and share an empty area, which is not what the
// person meant and would collide with whatever the recipient holds.
const key = this.#labelKeys.get(labelKey(this.label));
if (!key) {
throw new Error(
"You don't have a key for this area yet. Put something in it first.");
}
const recipient = await this.accounts.resolveRecipient(this.token, {
handle, label: this.label,
});
// The pseudonym is what the file server knows them as, and what the
// key is wrapped for. Sent back to the file server so it can check the
// handle still resolves to the same person — a mismatch would mean the
// key was wrapped for somebody who cannot open it, which looks like
// access and is not.
await this.api.post("/api/keys/labels/delegate", {
handle: handle.toLowerCase(),
principalID: recipient.pseudonym,
wrappedKey: b64(await grantLabelKey(
key, this.label,
await crypto.subtle.importKey(
"raw", unb64(recipient.publicKey), "X25519", true, []
)
)),
});
return recipient.pseudonym;
}
/**
* Create a share link for a file.
*
* Returns the secret separately from the id: the secret belongs in the URL
* fragment, which browsers never transmit, so the server storing this share
* cannot open it. Both halves are needed — the link and a label key.
*/
async createShare(node, { expiresInHours = 168, password = null } = {}) {
const record = await this.api.get(`/api/keys/nodes/${node.id}`);
const nodeKeyBytes = await unwrapNodeKey(
unb64(record.wrappedKey), this.currentLabelKey, node.label);
const contentKeyBytes = await unwrapContentKey(
unb64(node.contentKey), nodeKeyBytes, node.label);
const secret = createShareSecret();
const sealed = await sealShare({
labelKey: this.currentLabelKey, label: node.label,
secret, contentKey: contentKeyBytes, name: node.name, password,
});
const created = await this.api.post("/api/shares", {
nodeID: node.id,
wrappedContentKey: b64(sealed.wrappedContentKey),
wrappedName: b64(sealed.wrappedName),
passwordSalt: sealed.passwordSalt ? b64(sealed.passwordSalt) : null,
passwordIterations: sealed.passwordIterations,
expiresInHours,
});
return { id: created.id, secret: encodeShareSecret(secret), expiresAt: created.expiresAt };
}
/** Whether a link needs a password, so the interface can ask first. */
async shareNeedsPassword(shareID) {
return (await this.api.get(`/api/shares/${shareID}`)).needsPassword === true;
}
listShares(nodeID) { return this.api.get(`/api/shares/for/${nodeID}`); }
revokeShare(shareID) { return this.api.delete(`/api/shares/${shareID}`); }
/**
* Open a shared file.
*
* Fails for anyone not cleared for its label, twice over: the server will
* not serve the wrapped material to an undominated session, and without the
* label key the share key cannot be derived even if it did.
*/
async openSharedFile(shareID, secretText, password = null) {
const row = await this.api.get(`/api/shares/${shareID}`);
const shareLabel = makeLabel(row.classification, row.compartments);
const key = this.#labelKeys.get(labelKey(shareLabel));
if (!key) throw new Error("You aren't cleared for this file's area.");
const { contentKey, name } = await unsealShare({
labelKey: key, label: shareLabel,
secret: decodeShareSecret(secretText),
wrappedContentKey: unb64(row.wrappedContentKey),
wrappedName: unb64(row.wrappedName),
password,
passwordSalt: row.passwordSalt ? unb64(row.passwordSalt) : null,
passwordIterations: row.passwordIterations ?? undefined,
});
const ciphertext = await this.api.getBytes(`/api/blobs/${row.blobID}`);
return { name, label: shareLabel, bytes: await decryptContent(contentKey, ciphertext, shareLabel) };
}
async download(node) {
const nodeRecord = await this.api.get(`/api/keys/nodes/${node.id}`);
const nodeKeyBytes = await unwrapNodeKey(
unb64(nodeRecord.wrappedKey), this.currentLabelKey, node.label
);
const contentKeyBytes = await unwrapContentKey(
unb64(node.contentKey), nodeKeyBytes, node.label
);
const ciphertext = await this.api.getBytes(`/api/blobs/${node.blobID}`);
return decryptContent(contentKeyBytes, ciphertext, node.label);
}
}
export { utf8, fromUtf8 };
-123
View File
@@ -1,123 +0,0 @@
import { concat, random, utf8, fromUtf8, b64, unb64 } from "./bytes.js";
import { labelBytes } from "./lattice.js";
import { wrapWithKey, unwrapWithKey } from "./wrap.js";
/**
* Share links that still respect the lattice.
*
* An ordinary "anyone with the link" share is incompatible with labels. A label
* makes access depend on who you are; a bearer link makes it depend on what you
* hold, and forwarding defeats it. So a share here needs *two* things:
*
* - the link, whose fragment carries a secret the server never receives
* - the label key, which only a cleared principal holds
*
* shareKey = HKDF-SHA256(labelKey || secret, info = "enclave/share/v1")
*
* Forward the link to someone who is not cleared and they get nothing: no label
* key, no share key, no plaintext. The server cannot read it either, since the
* secret lives only in the URL fragment and fragments are never sent.
*
* ## What this does not do
*
* It grants access to *any* cleared holder of the link, not one named person.
* If a share must be for exactly one recipient, wrap to their identity public
* key instead — that is a different construction.
*
* Revocation and expiry are enforced by the server, not by the mathematics.
* Someone who already fetched and kept the wrapped key can still use it, the
* same as any system where a key has left your hands.
*/
const SHARE_INFO = "enclave/share/v1";
const SHARE_INFO_PASSWORD = "enclave/share/v2";
/**
* Optional third factor: a password sent out of band, as DoD SAFE does.
*
* Deliberately stretched, because a share password is chosen by a person under
* time pressure and will be short. The salt is stored with the share and is not
* secret; the password itself is never sent anywhere, so the server cannot test
* a guess against it. A wrong password produces a key that fails to decrypt,
* and there is no verifier for anyone to attack offline.
*/
export const SHARE_PASSWORD_ITERATIONS = 250_000;
export async function deriveSharePasswordKey(password, salt, iterations = SHARE_PASSWORD_ITERATIONS) {
const base = await crypto.subtle.importKey("raw", utf8(password), "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations, hash: "SHA-256" }, base, 256
);
return new Uint8Array(bits);
}
/**
* The share key.
*
* Two factors always — the label key and the link secret — and a third when a
* password is set. The info string differs between the two constructions, so a
* password-protected share cannot be opened as though it had none.
*/
export async function deriveShareKey(labelKey, secret, passwordKey = null) {
const material = await crypto.subtle.importKey(
"raw", passwordKey ? concat(labelKey, secret, passwordKey) : concat(labelKey, secret),
"HKDF", false, ["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0),
info: utf8(passwordKey ? SHARE_INFO_PASSWORD : SHARE_INFO),
},
material, 256
);
return new Uint8Array(bits);
}
/** Secret bytes for a new link. Belongs in the fragment and nowhere else. */
export const createShareSecret = () => random(32);
/**
* Wrap a file's content key and name for a share.
*
* Both carry the label as AAD, exactly as everything else does, so a share
* cannot be replayed against a row the server has relabelled.
*/
export async function sealShare({ labelKey, label, secret, contentKey, name, password = null }) {
const passwordSalt = password ? random(16) : null;
const passwordKey = password
? await deriveSharePasswordKey(password, passwordSalt)
: null;
const shareKey = await deriveShareKey(labelKey, secret, passwordKey);
const aad = labelBytes(label);
return {
wrappedContentKey: await wrapWithKey(shareKey, contentKey, aad),
wrappedName: await wrapWithKey(shareKey, utf8(name), aad),
// Public. A salt is not a secret, and the recipient needs it to derive.
passwordSalt,
passwordIterations: password ? SHARE_PASSWORD_ITERATIONS : null,
};
}
export async function openShare({
labelKey, label, secret, wrappedContentKey, wrappedName,
password = null, passwordSalt = null, passwordIterations = SHARE_PASSWORD_ITERATIONS,
}) {
if (passwordSalt && !password) throw new Error("This link needs the password it was sent with.");
const passwordKey = passwordSalt
? await deriveSharePasswordKey(password, passwordSalt, passwordIterations)
: null;
const shareKey = await deriveShareKey(labelKey, secret, passwordKey);
const aad = labelBytes(label);
return {
contentKey: await unwrapWithKey(shareKey, wrappedContentKey, aad),
name: fromUtf8(await unwrapWithKey(shareKey, wrappedName, aad)),
};
}
/** The fragment form. Base64url so it survives a URL untouched. */
export const encodeShareSecret = (secret) =>
b64(secret).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
export const decodeShareSecret = (text) => {
const padded = text.replace(/-/g, "+").replace(/_/g, "/");
return unb64(padded + "=".repeat((4 - (padded.length % 4)) % 4));
};
-82
View File
@@ -1,82 +0,0 @@
import { CONTEXT } from "./kdf.js";
import { wrapWithKey, unwrapWithKey } from "./wrap.js";
import { toMnemonic, fromMnemonic, toSeed } from "./bip39.js";
/**
* A wallet seed, and the two independent ways back to it.
*
* 🔴 **The seed is its own secret and is never derived from the passphrase.**
* Files and Messenger derive their identities from it (§2); a wallet must not,
* for two reasons that are each sufficient. A passphrase can be changed, and
* where a Files identity is re-wrapped a wallet would derive different
* addresses — coins sent to an address nobody can derive again are gone. And a
* derived seed is not portable, which was the entire requirement.
*
* So: fresh entropy, a BIP-39 phrase that restores anywhere, and a copy wrapped
* under the account so day-to-day use does not mean typing 24 words.
*
* entropy ──▶ phrase ──▶ seed portable, understood by other wallets
* │
* └──▶ wrapped under walletKEK convenient, this account only
*
* ⚠️ Both doors open the SAME wallet. Either alone is enough, and losing both
* is unrecoverable by anyone including us — which is the honest shape of
* self-custody and needs saying out loud wherever a phrase is first shown.
*/
/** AAD for the wrapped record, exactly as an identity record uses its context. */
const aad = () => new TextEncoder().encode(CONTEXT.walletSeed);
/**
* A new wallet: entropy, the phrase for it, and the record to store.
*
* ⚠️ 256 bits by default — 24 words. The extra length costs nothing to store
* and is what people expect to see from a wallet; 128 remains available for
* anyone who wants 12.
*/
export async function createWallet({ walletKEK, words, entropyBytes = 32 } = {}) {
const entropy = crypto.getRandomValues(new Uint8Array(entropyBytes));
const phrase = await toMnemonic(entropy, words);
return {
phrase,
record: await wrapEntropy(entropy, walletKEK),
};
}
/**
* Wrap the ENTROPY, not the seed.
*
* 🔴 The seed is a one-way function of the phrase, so storing it would give a
* record that opens the wallet but cannot produce the words. Somebody who lost
* their phrase but still had their account could spend, and could never move to
* another wallet or write the phrase down again — self-custody in name only.
* Keeping the entropy means the account can always regenerate the phrase.
*/
export const wrapEntropy = (entropy, walletKEK) =>
wrapWithKey(walletKEK, entropy, aad());
export const unwrapEntropy = (record, walletKEK) =>
unwrapWithKey(walletKEK, record, aad());
/** The phrase, from the stored record — for showing it again later. */
export async function recoverPhrase(record, walletKEK, words) {
return toMnemonic(await unwrapEntropy(record, walletKEK), words);
}
/**
* Adopt a phrase that came from somewhere else.
*
* ⚠️ Validates before storing. A phrase that fails its checksum is refused
* here rather than wrapped and discovered later, when the wallet it names
* turns out to be empty and nobody can say why.
*/
export async function importPhrase(phrase, walletKEK, words) {
const entropy = await fromMnemonic(phrase, words);
return wrapEntropy(entropy, walletKEK);
}
/** The 64-byte seed everything derives from. */
export async function seedFor(record, walletKEK, words, passphrase = "") {
const phrase = await recoverPhrase(record, walletKEK, words);
return toSeed(phrase, passphrase);
}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
-106
View File
@@ -1,106 +0,0 @@
import { concat, random } from "./bytes.js";
/**
* Key wrapping, in two flavours.
*
* Every wrap takes an `aad` argument and every caller passes the canonical
* label encoding. That is what stops the server from reclassifying data by
* editing a column: the ciphertext is bound to the label it was created under,
* so a relabelled row fails to decrypt instead of quietly changing sensitivity.
*
* ## Wire format -- asymmetric (version 1)
*
* offset size field
* 0 1 version = 1
* 1 32 ephemeral X25519 public key
* 33 12 AES-GCM nonce
* 45 .. AES-256-GCM ciphertext || 16-byte tag
*
* ## Wire format -- symmetric (version 17)
*
* offset size field
* 0 1 version = 17
* 1 12 AES-GCM nonce
* 13 .. AES-256-GCM ciphertext || 16-byte tag
*
* Version numbers are disjoint across the two so a blob can never be fed to the
* wrong unwrap path and produce anything but an error.
*/
export const WRAP_ASYMMETRIC_V1 = 1;
export const WRAP_SYMMETRIC_V1 = 17;
const HKDF_INFO = new TextEncoder().encode("enclave/wrap/v1");
async function deriveSharedKEK(privateKey, publicKey, ephemeralPublicRaw, recipientPublicRaw) {
const shared = await crypto.subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256);
const base = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
// Binding both public keys into the salt ties the derived KEK to this exact
// sender/recipient pair, so a wrap cannot be replayed at another recipient.
return crypto.subtle.deriveKey(
{
name: "HKDF",
hash: "SHA-256",
salt: concat(ephemeralPublicRaw, recipientPublicRaw),
info: HKDF_INFO,
},
base,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
/** Wrap raw key material to an X25519 public key. */
export async function wrapToPublicKey(recipientPublicKey, keyBytes, aad) {
const ephemeral = await crypto.subtle.generateKey("X25519", true, ["deriveBits"]);
const ephemeralRaw = new Uint8Array(await crypto.subtle.exportKey("raw", ephemeral.publicKey));
const recipientRaw = new Uint8Array(await crypto.subtle.exportKey("raw", recipientPublicKey));
const kek = await deriveSharedKEK(ephemeral.privateKey, recipientPublicKey, ephemeralRaw, recipientRaw);
const nonce = random(12);
const ciphertext = new Uint8Array(
await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, kek, keyBytes)
);
return concat(new Uint8Array([WRAP_ASYMMETRIC_V1]), ephemeralRaw, nonce, ciphertext);
}
export async function unwrapWithPrivateKey(recipientPrivateKey, recipientPublicKey, blob, aad) {
if (blob[0] !== WRAP_ASYMMETRIC_V1) throw new Error(`unsupported wrap version ${blob[0]}`);
const ephemeralRaw = blob.subarray(1, 33);
const nonce = blob.subarray(33, 45);
const ciphertext = blob.subarray(45);
const ephemeralPublic = await crypto.subtle.importKey("raw", ephemeralRaw, "X25519", true, []);
const recipientRaw = new Uint8Array(await crypto.subtle.exportKey("raw", recipientPublicKey));
const kek = await deriveSharedKEK(recipientPrivateKey, ephemeralPublic, ephemeralRaw, recipientRaw);
return new Uint8Array(
await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, kek, ciphertext)
);
}
async function importAESKey(keyBytes, usages) {
return crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM", length: 256 }, false, usages);
}
/** Wrap raw key material under a symmetric key-encryption key. */
export async function wrapWithKey(kekBytes, keyBytes, aad) {
const kek = await importAESKey(kekBytes, ["encrypt"]);
const nonce = random(12);
const ciphertext = new Uint8Array(
await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, kek, keyBytes)
);
return concat(new Uint8Array([WRAP_SYMMETRIC_V1]), nonce, ciphertext);
}
export async function unwrapWithKey(kekBytes, blob, aad) {
if (blob[0] !== WRAP_SYMMETRIC_V1) throw new Error(`unsupported wrap version ${blob[0]}`);
const kek = await importAESKey(kekBytes, ["decrypt"]);
return new Uint8Array(
await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: blob.subarray(1, 13), additionalData: aad },
kek,
blob.subarray(13)
)
);
}
-79
View File
@@ -1,79 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { toMnemonic, fromMnemonic, toSeed, verifyWordlist } from "../src/bip39.js";
import { english } from "../src/wordlists/english.js";
/**
* The official BIP-39 vectors, against the vendored list.
*
* 🔴 This is the check that matters. A digest proves the file is the one that
* was published; these prove the file plus this implementation produce what
* every other wallet produces. Only the pair is worth anything — a correct list
* with a wrong bit-packing derives a valid-looking phrase for the wrong wallet.
*/
const hex = (s) => new Uint8Array(s.match(/../g).map(b => parseInt(b, 16)));
const toHex = (u8) => [...u8].map(b => b.toString(16).padStart(2, "0")).join("");
/** From the BIP-39 specification's test vector set; passphrase "TREZOR". */
const VECTORS = [
{
entropy: "00000000000000000000000000000000",
phrase: "abandon abandon abandon abandon abandon abandon abandon abandon " +
"abandon abandon abandon about",
seed: "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e5349553" +
"1f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",
},
{
entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
phrase: "legal winner thank year wave sausage worth useful legal winner " +
"thank yellow",
// ⚠️ Seed deliberately absent. The entropy and phrase here are from the
// specification and are asserted; the seed is not, because I have not
// checked it against the published value. A plausible-looking constant
// nobody verified is worse than none — the next person to add an
// assertion would be pinning my guess.
seed: null,
},
{
entropy: "ffffffffffffffffffffffffffffffff",
phrase: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
seed: null, // asserted only for entropy/phrase; see below
},
{
entropy: "0000000000000000000000000000000000000000000000000000000000000000",
phrase: "abandon abandon abandon abandon abandon abandon abandon abandon " +
"abandon abandon abandon abandon abandon abandon abandon abandon " +
"abandon abandon abandon abandon abandon abandon abandon art",
seed: null,
},
];
test("the vendored list matches its pinned digest", async () => {
assert.equal(await verifyWordlist(english), true);
});
test("🔴 entropy produces the phrase every other wallet produces", async () => {
for (const v of VECTORS) {
assert.equal(await toMnemonic(hex(v.entropy), english), v.phrase,
`entropy ${v.entropy.slice(0, 8)}…`);
}
});
test("🔴 those phrases decode back to the same entropy", async () => {
for (const v of VECTORS) {
assert.equal(toHex(await fromMnemonic(v.phrase, english)), v.entropy);
}
});
test("🔴 the seed matches the published vector", async () => {
// The first vector is the one every implementation is checked against.
const v = VECTORS[0];
assert.equal(toHex(await toSeed(v.phrase, "TREZOR")), v.seed);
});
test("a real phrase with one word swapped fails its checksum", async () => {
const phrase = "abandon abandon abandon abandon abandon abandon abandon " +
"abandon abandon abandon abandon abandon"; // "about" -> "abandon"
await assert.rejects(() => fromMnemonic(phrase, english), /checksum/);
});
-117
View File
@@ -1,117 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { toMnemonic, fromMnemonic, toSeed, verifyWordlist,
ENGLISH_SHA256 } from "../src/bip39.js";
/**
* A stand-in wordlist: 2048 distinct words, deterministic, and NOT the real
* one. It exercises every part of the algorithm — bit packing, checksum, the
* round trip — without depending on a list this repository does not vendor yet.
*
* ⚠️ Seed values below therefore do NOT match the published BIP-39 vectors,
* because those are tied to the real English list. Those vectors become
* meaningful the moment the list is vendored, and `verifyWordlist` is what
* makes vendoring it safe.
*/
const words = Array.from({ length: 2048 }, (_, i) => `w${i.toString(36)}`);
const entropyOf = (n, fill = 0) => new Uint8Array(n).fill(fill);
test("entropy round-trips through a phrase", async () => {
for (const size of [16, 20, 24, 28, 32]) {
const entropy = crypto.getRandomValues(new Uint8Array(size));
const phrase = await toMnemonic(entropy, words);
assert.deepEqual(await fromMnemonic(phrase, words), entropy, `${size} bytes`);
}
});
test("phrase length follows entropy size", async () => {
const expected = { 16: 12, 20: 15, 24: 18, 28: 21, 32: 24 };
for (const [size, count] of Object.entries(expected)) {
const phrase = await toMnemonic(entropyOf(Number(size)), words);
assert.equal(phrase.split(" ").length, count);
}
});
test("entropy that is not a permitted size is refused", async () => {
await assert.rejects(() => toMnemonic(entropyOf(15), words), /16, 20, 24, 28 or 32/);
await assert.rejects(() => toMnemonic(entropyOf(64), words), /16, 20, 24, 28 or 32/);
});
// MARK: the checksum, which is the whole reason a word list is tolerable
test("🔴 a mistyped word fails the checksum rather than naming another wallet",
async () => {
const entropy = crypto.getRandomValues(new Uint8Array(16));
const phrase = (await toMnemonic(entropy, words)).split(" ");
// Swap one word for a different valid one: still all real words, still the
// right length, and it must not decode.
const swapped = [...phrase];
swapped[3] = words[(words.indexOf(phrase[3]) + 1) % 2048];
await assert.rejects(() => fromMnemonic(swapped.join(" "), words), /checksum/);
});
test("a word that is not on the list is named, not ignored", async () => {
const phrase = (await toMnemonic(entropyOf(16), words)).split(" ");
phrase[5] = "notaword";
await assert.rejects(() => fromMnemonic(phrase.join(" "), words), /"notaword"/);
});
test("a phrase of the wrong length is refused", async () => {
const phrase = (await toMnemonic(entropyOf(16), words)).split(" ");
await assert.rejects(() => fromMnemonic(phrase.slice(0, 11).join(" "), words),
/12, 15, 18, 21 or 24/);
});
test("whitespace and case-normalised input still decodes", async () => {
const entropy = crypto.getRandomValues(new Uint8Array(32));
const phrase = await toMnemonic(entropy, words);
const messy = " " + phrase.split(" ").join(" ") + "\n";
assert.deepEqual(await fromMnemonic(messy, words), entropy);
});
// MARK: seeds
test("the same phrase always gives the same seed", async () => {
const phrase = await toMnemonic(entropyOf(16, 7), words);
const a = await toSeed(phrase);
const b = await toSeed(phrase);
assert.deepEqual(a, b);
assert.equal(a.length, 64);
});
test("⚠️ a BIP-39 passphrase yields a different wallet, silently and by design",
async () => {
const phrase = await toMnemonic(entropyOf(16, 7), words);
const plain = await toSeed(phrase);
const withExtra = await toSeed(phrase, "a second factor");
assert.notDeepEqual(plain, withExtra,
"the standard's behaviour, and the reason it must be surfaced clearly");
});
// MARK: the wordlist guard
test("🔴 a wordlist that does not match its digest is refused", async () => {
await assert.rejects(() => verifyWordlist(words), /does not match/);
});
test("a list of the wrong length is refused before any digest is taken", async () => {
await assert.rejects(() => verifyWordlist(words.slice(0, 2047)), /exactly 2048/);
await assert.rejects(() => verifyWordlist([]), /exactly 2048/);
});
test("the expected digest is pinned as a constant, not computed", () => {
assert.match(ENGLISH_SHA256, /^[0-9a-f]{64}$/);
});
test("⚠️ a single altered word changes the digest", async () => {
const altered = [...words];
altered[2047] = "different";
const digestOf = async (list) => {
try { await verifyWordlist(list, "0".repeat(64)); } catch (e) {
return String(e.message).match(/digest ([0-9a-f]{64})/)?.[1];
}
};
assert.notEqual(await digestOf(words), await digestOf(altered),
"which is exactly what the check exists to notice");
});
-79
View File
@@ -1,79 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { encryptContent, decryptContent, DEFAULT_CHUNK_SIZE } from "../src/content.js";
import { label } from "../src/lattice.js";
import { random } from "../src/bytes.js";
const L = label(2, [0]);
const OTHER = label(3, [0]);
const TAG = 16;
test("round-trips across chunk boundaries", async () => {
const key = random(32);
const chunk = 1024;
for (const size of [0, 1, chunk - 1, chunk, chunk + 1, chunk * 3, chunk * 3 + 7]) {
const plaintext = random(size);
const blob = await encryptContent(key, plaintext, L, chunk);
assert.deepEqual(await decryptContent(key, blob, L), plaintext, `size ${size}`);
}
});
test("an empty file is still one authenticated chunk", async () => {
const key = random(32);
const blob = await encryptContent(key, new Uint8Array(0), L, 1024);
assert.equal(blob.length, 17 + TAG);
assert.deepEqual(await decryptContent(key, blob, L), new Uint8Array(0));
});
test("the default chunk size is used when none is given", async () => {
const key = random(32);
const plaintext = random(100);
const blob = await encryptContent(key, plaintext, L);
assert.equal(new DataView(blob.buffer, blob.byteOffset).getUint32(5, false), DEFAULT_CHUNK_SIZE);
assert.deepEqual(await decryptContent(key, blob, L), plaintext);
});
// The attack that independent per-chunk authentication would otherwise permit.
test("truncating trailing chunks is detected", async () => {
const key = random(32);
const chunk = 256;
const blob = await encryptContent(key, random(chunk * 4), L, chunk);
const truncated = blob.subarray(0, blob.length - (chunk + TAG));
await assert.rejects(() => decryptContent(key, truncated, L));
});
test("truncating to a single chunk is detected", async () => {
const key = random(32);
const chunk = 256;
const blob = await encryptContent(key, random(chunk * 3), L, chunk);
await assert.rejects(() => decryptContent(key, blob.subarray(0, 17 + chunk + TAG), L));
});
test("reordering chunks is detected", async () => {
const key = random(32);
const chunk = 256, stored = chunk + TAG;
const blob = await encryptContent(key, random(chunk * 3), L, chunk);
const body = blob.subarray(17);
const first = body.slice(0, stored);
body.set(body.slice(stored, stored * 2), 0);
body.set(first, stored);
await assert.rejects(() => decryptContent(key, blob, L));
});
test("content does not decrypt under a different label", async () => {
const key = random(32);
const blob = await encryptContent(key, random(500), L, 256);
await assert.rejects(() => decryptContent(key, blob, OTHER));
});
test("bit-flips are detected", async () => {
const key = random(32);
const blob = await encryptContent(key, random(500), L, 256);
blob[blob.length - 5] ^= 0x01;
await assert.rejects(() => decryptContent(key, blob, L));
});
test("a foreign blob is rejected before any crypto runs", async () => {
await assert.rejects(() => decryptContent(random(32), random(64), L), /not an Enclave content blob/);
await assert.rejects(() => decryptContent(random(32), random(4), L), /truncated content header/);
});
-134
View File
@@ -1,134 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { generateIdentity } from "../src/identity.js";
import {
createLabelKey, createNodeKey, createContentKey,
grantLabelKey, acceptLabelKey, wrapNodeKey, unwrapNodeKey,
wrapContentKey, unwrapContentKey,
} from "../src/keys.js";
import { encryptContent, decryptContent } from "../src/content.js";
import { encryptName, decryptName } from "../src/names.js";
import { label, permits } from "../src/lattice.js";
import { b64, unb64, utf8, fromUtf8 } from "../src/bytes.js";
const CONFIDENTIAL = label(2, []);
const RESTRICTED_FINANCE = label(3, [0]);
/** Everything the server would hold for one file. All ciphertext. */
async function storeFile({ labelKey, fileLabel, folderKey, name, body }) {
const nodeKey = createNodeKey();
const contentKey = createContentKey();
const { digest, ciphertext: nameCiphertext } = await encryptName(folderKey, name, fileLabel);
return {
nameDigest: b64(digest),
nameCiphertext: b64(nameCiphertext),
wrappedNodeKey: b64(await wrapNodeKey(nodeKey, labelKey, fileLabel)),
wrappedContentKey: b64(await wrapContentKey(contentKey, nodeKey, fileLabel)),
blob: b64(await encryptContent(contentKey, utf8(body), fileLabel)),
};
}
async function readFile(row, labelKey, fileLabel, folderKey) {
const nodeKey = await unwrapNodeKey(unb64(row.wrappedNodeKey), labelKey, fileLabel);
const contentKey = await unwrapContentKey(unb64(row.wrappedContentKey), nodeKey, fileLabel);
return {
name: await decryptName(folderKey, unb64(row.nameCiphertext), unb64(row.nameDigest), fileLabel),
body: fromUtf8(await decryptContent(contentKey, unb64(row.blob), fileLabel)),
};
}
test("a cleared principal reads a file end to end", async () => {
const alice = await generateIdentity();
const labelKey = createLabelKey();
// The label key is granted by wrapping it to Alice's identity public key.
const grant = await grantLabelKey(labelKey, RESTRICTED_FINANCE, alice.publicKey);
const received = await acceptLabelKey(grant, RESTRICTED_FINANCE, alice.privateKey, alice.publicKey);
assert.deepEqual(received, labelKey);
const row = await storeFile({
labelKey: received,
fileLabel: RESTRICTED_FINANCE,
folderKey: received,
name: "Q3 Forecast.xlsx",
body: "revenue: 41",
});
const out = await readFile(row, received, RESTRICTED_FINANCE, received);
assert.equal(out.name, "Q3 Forecast.xlsx");
assert.equal(out.body, "revenue: 41");
});
/**
* The property that row-level security alone cannot provide.
*
* Bob is cleared to CONFIDENTIAL only. Here he is handed the complete stored
* row -- every wrapped key and the whole content blob, exactly what a stolen
* backup or a malicious server would yield. Without the label key for
* RESTRICTED//FINANCE he still cannot open any of it.
*/
test("an uncleared principal cannot read the ciphertext even with full access", async () => {
const alice = await generateIdentity();
const bob = await generateIdentity();
const confidentialKey = createLabelKey();
const financeKey = createLabelKey();
// Bob's clearance permits CONFIDENTIAL and nothing above it.
const bobClearance = { maximum: CONFIDENTIAL, minimum: label(0, []) };
assert.ok(permits(bobClearance, CONFIDENTIAL));
assert.ok(!permits(bobClearance, RESTRICTED_FINANCE));
// So Bob is granted the CONFIDENTIAL label key only.
const bobGrant = await grantLabelKey(confidentialKey, CONFIDENTIAL, bob.publicKey);
const bobsKey = await acceptLabelKey(bobGrant, CONFIDENTIAL, bob.privateKey, bob.publicKey);
const row = await storeFile({
labelKey: financeKey,
fileLabel: RESTRICTED_FINANCE,
folderKey: financeKey,
name: "Payroll.csv",
body: "salaries",
});
// Every route in, with the whole row in hand.
await assert.rejects(() => unwrapNodeKey(unb64(row.wrappedNodeKey), bobsKey, RESTRICTED_FINANCE));
await assert.rejects(() => unwrapNodeKey(unb64(row.wrappedNodeKey), bobsKey, CONFIDENTIAL));
// Even a grant addressed to Alice is useless to Bob.
const aliceGrant = await grantLabelKey(financeKey, RESTRICTED_FINANCE, alice.publicKey);
await assert.rejects(
() => acceptLabelKey(aliceGrant, RESTRICTED_FINANCE, bob.privateKey, bob.publicKey)
);
});
/**
* A node key wrapped to its parent folder's key instead of its label key -- the
* conventional Drive design -- would let a CONFIDENTIAL folder holder open a
* RESTRICTED file inside it. keys.js cannot express that, and the label AAD
* makes the mistake fail loudly if it is ever constructed by hand.
*/
test("a node key does not open under a folder key from a lower label", async () => {
const parentFolderKey = createNodeKey();
const nodeKey = createNodeKey();
// Deliberately wrapped the wrong way: to the parent's key, not the label's.
const wrapped = await wrapNodeKey(nodeKey, parentFolderKey, CONFIDENTIAL);
// The child sits at RESTRICTED//FINANCE, so unwrapping at its real label fails.
await assert.rejects(() => unwrapNodeKey(wrapped, parentFolderKey, RESTRICTED_FINANCE));
});
test("the wire format survives base64 round-tripping to the API", async () => {
const labelKey = createLabelKey();
const row = await storeFile({
labelKey, fileLabel: CONFIDENTIAL, folderKey: labelKey,
name: "notes.txt", body: "hello",
});
// Every field is a base64 string, which is what Vapor decodes into `Data`.
for (const [field, value] of Object.entries(row)) {
assert.equal(typeof value, "string", field);
assert.match(value, /^[A-Za-z0-9+/]*={0,2}$/, field);
}
const out = await readFile(JSON.parse(JSON.stringify(row)), labelKey, CONFIDENTIAL, labelKey);
assert.equal(out.body, "hello");
});
-71
View File
@@ -1,71 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { generateIdentity, protectIdentity, unlockIdentity, exportPublicKey } from "../src/identity.js";
import { CONTEXT, deriveIdentityKEK } from "../src/kdf.js";
// Reduced iterations so the suite stays fast. The default (650k) is exercised
// by the "records its own iteration count" test below.
const FAST = { id: 1, name: "PBKDF2-SHA256", iterations: 1_000, saltBytes: 16 };
test("identity round-trips through passphrase protection", async () => {
const pair = await generateIdentity();
const record = await protectIdentity(pair.privateKey, "correct horse battery staple", { params: FAST });
const unlocked = await unlockIdentity(record, "correct horse battery staple");
// Same private key => same X25519 agreement against a third party.
const other = await generateIdentity();
const a = await crypto.subtle.deriveBits({ name: "X25519", public: other.publicKey }, pair.privateKey, 256);
const b = await crypto.subtle.deriveBits({ name: "X25519", public: other.publicKey }, unlocked, 256);
assert.deepEqual(new Uint8Array(a), new Uint8Array(b));
});
test("wrong passphrase fails to unlock", async () => {
const pair = await generateIdentity();
const record = await protectIdentity(pair.privateKey, "right", { params: FAST });
await assert.rejects(() => unlockIdentity(record, "wrong"));
});
test("the record carries its own iteration count", async () => {
const pair = await generateIdentity();
const record = await protectIdentity(pair.privateKey, "pw", { params: FAST });
assert.equal(record.iterations, FAST.iterations);
// Raising the registry default must not strand this account.
assert.ok(await unlockIdentity(record, "pw"));
});
test("a record missing its iteration count is refused rather than guessed", async () => {
const pair = await generateIdentity();
const record = await protectIdentity(pair.privateKey, "pw", { params: FAST });
delete record.iterations;
await assert.rejects(() => unlockIdentity(record, "pw"), /iteration count/);
});
// The shared-login property: one credential across FlameNet products, but no
// shared key material between them.
test("the same passphrase yields different keys per product", async () => {
const salt = crypto.getRandomValues(new Uint8Array(16));
const opts = { params: FAST };
const filesKEK = await deriveIdentityKEK("shared passphrase", salt, { ...opts, context: CONTEXT.files });
const messengerKEK = await deriveIdentityKEK("shared passphrase", salt, { ...opts, context: CONTEXT.messenger });
const probe = new TextEncoder().encode("probe");
const nonce = new Uint8Array(12);
const underFiles = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, filesKEK, probe);
// Messenger's key cannot open what Files' key sealed, from one passphrase.
await assert.rejects(
() => crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, messengerKEK, underFiles)
);
});
test("a Messenger identity record cannot be unlocked as a Files record", async () => {
const pair = await generateIdentity();
const record = await protectIdentity(pair.privateKey, "pw", { params: FAST, context: CONTEXT.messenger });
await assert.rejects(() => unlockIdentity({ ...record, context: CONTEXT.files }, "pw"));
});
test("public keys export to 32 raw bytes", async () => {
const pair = await generateIdentity();
assert.equal((await exportPublicKey(pair.publicKey)).length, 32);
});
-54
View File
@@ -1,54 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { label, dominates, incomparable, leastUpperBound, permits, labelBytes } from "../src/lattice.js";
// These mirror Tests/EnclaveLatticeTests/LatticeTests.swift. The Swift side is
// the source of truth; if these diverge, the Swift suite wins.
const PUBLIC = 0, INTERNAL = 1, CONFIDENTIAL = 2, RESTRICTED = 3;
const FINANCE = 0, LEGAL = 1;
test("dominance is reflexive", () => {
for (const l of [label(PUBLIC), label(CONFIDENTIAL, [FINANCE]), label(RESTRICTED, [FINANCE, LEGAL])]) {
assert.ok(dominates(l, l));
}
});
test("dominance is transitive", () => {
const low = label(INTERNAL), mid = label(CONFIDENTIAL, [FINANCE]), high = label(RESTRICTED, [FINANCE, LEGAL]);
assert.ok(dominates(mid, low));
assert.ok(dominates(high, mid));
assert.ok(dominates(high, low));
});
test("a higher classification does not confer compartment access", () => {
const secretFinance = label(CONFIDENTIAL, [FINANCE]);
const restrictedLegal = label(RESTRICTED, [LEGAL]);
assert.ok(!dominates(restrictedLegal, secretFinance));
assert.ok(!dominates(secretFinance, restrictedLegal));
assert.ok(incomparable(secretFinance, restrictedLegal));
});
test("least upper bound absorbs both inputs", () => {
const lub = leastUpperBound(label(CONFIDENTIAL, [FINANCE]), label(RESTRICTED, [LEGAL]));
assert.deepEqual(lub, label(RESTRICTED, [FINANCE, LEGAL]));
});
test("clearance rejects a label incomparable to its maximum", () => {
const clearance = { maximum: label(RESTRICTED, [FINANCE]), minimum: label(PUBLIC) };
assert.ok(permits(clearance, label(CONFIDENTIAL, [FINANCE])));
assert.ok(!permits(clearance, label(INTERNAL, [LEGAL])));
});
test("canonical encoding matches the Postgres column layout", () => {
// int16be classification, then uint64be compartment mask.
assert.deepEqual([...labelBytes(label(3, [0]))], [0, 3, 0, 0, 0, 0, 0, 0, 0, 1]);
assert.deepEqual([...labelBytes(label(1, []))], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
// Bit 63 -- the case that overflows a signed 64-bit conversion.
assert.deepEqual([...labelBytes(label(0, [63]))], [0, 0, 128, 0, 0, 0, 0, 0, 0, 0]);
});
test("compartment bits outside 0..63 are rejected", () => {
assert.throws(() => label(1, [64]), RangeError);
assert.throws(() => label(1, [-1]), RangeError);
});
-56
View File
@@ -1,56 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { nameDigest, encryptName, decryptName } from "../src/names.js";
import { label } from "../src/lattice.js";
import { random, equal } from "../src/bytes.js";
const L = label(2, [0]);
const OTHER = label(3, [0]);
test("the digest is deterministic under one folder key", async () => {
const folderKey = random(32);
const a = await nameDigest(folderKey, "Q3 Forecast.xlsx");
const b = await nameDigest(folderKey, "Q3 Forecast.xlsx");
assert.ok(equal(a, b));
});
// Keying per folder is what stops the server correlating names across folders.
test("the same name digests differently under different folder keys", async () => {
const a = await nameDigest(random(32), "Payroll");
const b = await nameDigest(random(32), "Payroll");
assert.ok(!equal(a, b));
});
test("Unicode-equivalent names produce the same digest", async () => {
const folderKey = random(32);
// "café" precomposed vs decomposed.
const a = await nameDigest(folderKey, "café");
const b = await nameDigest(folderKey, "café");
assert.ok(equal(a, b));
});
test("comparison stays case-sensitive", async () => {
const folderKey = random(32);
assert.ok(!equal(await nameDigest(folderKey, "Payroll"), await nameDigest(folderKey, "payroll")));
});
test("names round-trip", async () => {
const folderKey = random(32);
const { digest, ciphertext } = await encryptName(folderKey, "Q3 Forecast.xlsx", L);
assert.equal(await decryptName(folderKey, ciphertext, digest, L), "Q3 Forecast.xlsx");
});
test("a name ciphertext does not open under a different label", async () => {
const folderKey = random(32);
const { digest, ciphertext } = await encryptName(folderKey, "Payroll", L);
await assert.rejects(() => decryptName(folderKey, ciphertext, digest, OTHER));
});
// Binding the digest into the AAD stops the server swapping name ciphertexts
// between rows to learn which plaintext belongs to which digest.
test("a name ciphertext cannot be paired with another row's digest", async () => {
const folderKey = random(32);
const { ciphertext } = await encryptName(folderKey, "Payroll", L);
const { digest: otherDigest } = await encryptName(folderKey, "Holiday Party", L);
await assert.rejects(() => decryptName(folderKey, ciphertext, otherDigest, L));
});
-111
View File
@@ -1,111 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { generateRecoveryCode, encode, decode, normalize, kdfSecret } from "../src/recovery.js";
import {
generateIdentity, protectIdentity, unlockIdentity,
protectIdentityWithRecovery, unlockWithRecovery,
} from "../src/identity.js";
const FAST = { id: 1, name: "PBKDF2-SHA256", iterations: 1_000, saltBytes: 16 };
test("a generated code round-trips to its entropy", async () => {
const { entropy, code } = await generateRecoveryCode();
assert.match(code, /^[0-9A-HJKMNP-TV-Z]{4}(-[0-9A-HJKMNP-TV-Z]{4}){6}$/);
assert.deepEqual(await decode(code), entropy);
});
test("codes carry 128 bits and are unique across generations", async () => {
const seen = new Set();
for (let i = 0; i < 50; i++) {
const { entropy, code } = await generateRecoveryCode();
assert.equal(entropy.length, 16);
assert.equal(normalize(code).length, 28);
seen.add(code);
}
assert.equal(seen.size, 50);
});
test("formatting, case and grouping do not change the result", async () => {
const { entropy, code } = await generateRecoveryCode();
const mangled = code.toLowerCase().replace(/-/g, " ").replace(/ +/g, " ");
assert.deepEqual(await decode(mangled), entropy);
});
// Crockford folding: a code read off paper with O for zero still decodes.
test("ambiguous glyphs are folded", async () => {
assert.equal(normalize("O0-Il1"), "00111");
const { entropy, code } = await generateRecoveryCode();
const misread = code.replace(/0/g, "O").replace(/1/g, "l");
assert.deepEqual(await decode(misread), entropy);
});
test("a typo is caught by the checksum, not by a failed decryption", async () => {
const { code } = await generateRecoveryCode();
const normalized = normalize(code);
// Flip one character to a different valid symbol.
const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const swapped = alphabet[(alphabet.indexOf(normalized[3]) + 1) % 32];
const typo = normalized.slice(0, 3) + swapped + normalized.slice(4);
await assert.rejects(() => decode(typo), /checksum/);
});
test("a wrong-length or invalid code is rejected", async () => {
await assert.rejects(() => decode("ABCD-EFGH"), /28 characters/);
await assert.rejects(() => decode("!".repeat(28)), /0 characters|28 characters/);
});
test("the recovery code unlocks the same identity as the passphrase", async () => {
const pair = await generateIdentity();
const { entropy } = await generateRecoveryCode();
const byPassphrase = await protectIdentity(pair.privateKey, "the passphrase", { params: FAST });
const byRecovery = await protectIdentityWithRecovery(pair.privateKey, entropy, { params: FAST });
const a = await unlockIdentity(byPassphrase, "the passphrase");
const b = await unlockWithRecovery(byRecovery, entropy);
// Both yield the same private key: identical agreement against a third party.
const other = await generateIdentity();
const viaA = await crypto.subtle.deriveBits({ name: "X25519", public: other.publicKey }, a, 256);
const viaB = await crypto.subtle.deriveBits({ name: "X25519", public: other.publicKey }, b, 256);
assert.deepEqual(new Uint8Array(viaA), new Uint8Array(viaB));
});
test("the two records are independent secrets", async () => {
const pair = await generateIdentity();
const { entropy } = await generateRecoveryCode();
const byPassphrase = await protectIdentity(pair.privateKey, "the passphrase", { params: FAST });
const byRecovery = await protectIdentityWithRecovery(pair.privateKey, entropy, { params: FAST });
// Neither secret opens the other's record, because the contexts differ.
await assert.rejects(() => unlockIdentity(byRecovery, "the passphrase"));
await assert.rejects(() => unlockIdentity(byPassphrase, kdfSecret(entropy)));
});
test("a different recovery code does not unlock", async () => {
const pair = await generateIdentity();
const { entropy } = await generateRecoveryCode();
const other = await generateRecoveryCode();
const record = await protectIdentityWithRecovery(pair.privateKey, entropy, { params: FAST });
await assert.rejects(() => unlockWithRecovery(record, other.entropy));
});
// The property the shared account service rests on.
test("the authentication secret cannot decrypt anything", async () => {
const { deriveAuthSecret, deriveIdentityKEK, CONTEXT } = await import("../src/kdf.js");
const salt = crypto.getRandomValues(new Uint8Array(16));
const options = { params: FAST };
const authSecret = await deriveAuthSecret("one passphrase", salt, options);
const encryptionKEK = await deriveIdentityKEK("one passphrase", salt, {
...options, context: CONTEXT.files,
});
// Seal something with the encryption key, then try the value the server holds.
const nonce = new Uint8Array(12);
const sealed = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: nonce }, encryptionKEK, new TextEncoder().encode("secret")
);
const asKey = await crypto.subtle.importKey("raw", authSecret, { name: "AES-GCM" }, false, ["decrypt"]);
await assert.rejects(() => crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, asKey, sealed));
});
-238
View File
@@ -1,238 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { generateIdentity } from "../src/identity.js";
import { createLabelKey, createNodeKey, grantLabelKey, acceptLabelKey,
wrapNodeKey, unwrapNodeKey } from "../src/keys.js";
import { rotateLabelKey } from "../src/rotate.js";
import { label } from "../src/lattice.js";
const CONFIDENTIAL = label(2, []);
/** A principal, and the server's copy of their grant. */
async function principal(labelKey) {
const id = await generateIdentity("passphrase-for-a-test");
return {
principalID: crypto.randomUUID(),
publicKey: id.publicKey,
privateKey: id.privateKey,
wrapped: await grantLabelKey(labelKey, CONFIDENTIAL, id.publicKey),
};
}
/** A tiny stand-in for the server: grants and node keys, by generation. */
function store() {
const grants = [];
const nodes = new Map();
return {
grants, nodes,
persistGrant: async (g) => { grants.push(g); },
persistNodeKey: async (n) => { nodes.set(n.nodeID, n); },
};
}
async function setup({ files = 3 } = {}) {
const oldLabelKey = createLabelKey();
const alice = await principal(oldLabelKey);
const bob = await principal(oldLabelKey);
const mallory = await principal(oldLabelKey);
const nodeKeys = [];
const plaintextKeys = new Map();
for (let i = 0; i < files; i++) {
const nodeID = `node-${i}`;
const nodeKey = createNodeKey();
plaintextKeys.set(nodeID, nodeKey);
nodeKeys.push({
nodeID,
wrapped: await wrapNodeKey(nodeKey, oldLabelKey, CONFIDENTIAL),
generation: 1,
});
}
return { oldLabelKey, alice, bob, mallory, nodeKeys, plaintextKeys };
}
test("rotation re-wraps every node key and grants the new key to everyone left",
async () => {
const { alice, bob, mallory, nodeKeys, plaintextKeys } = await setup();
const db = store();
const result = await rotateLabelKey({
label: CONFIDENTIAL,
privateKey: alice.privateKey,
publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining: [
{ principalID: alice.principalID, publicKey: alice.publicKey },
{ principalID: bob.principalID, publicKey: bob.publicKey },
],
nodeKeys,
toGeneration: 2,
persistGrant: db.persistGrant,
persistNodeKey: db.persistNodeKey,
});
assert.equal(result.rewrapped, 3);
assert.equal(db.grants.length, 2, "one grant each for the two who remain");
assert.ok(!db.grants.some(g => g.principalID === mallory.principalID),
"the revoked principal is granted nothing");
// Bob can open the new key, and through it every file.
const bobsGrant = db.grants.find(g => g.principalID === bob.principalID);
const newLabelKey = await acceptLabelKey(bobsGrant.wrapped, CONFIDENTIAL,
bob.privateKey, bob.publicKey);
for (const [nodeID, original] of plaintextKeys) {
const stored = db.nodes.get(nodeID);
const opened = await unwrapNodeKey(stored.wrapped, newLabelKey, CONFIDENTIAL);
assert.deepEqual(opened, original, `${nodeID} survived the rotation`);
}
});
test("🔴 the revoked holder's old key opens nothing that was re-wrapped",
async () => {
const { oldLabelKey, alice, bob, mallory, nodeKeys } = await setup({ files: 1 });
const db = store();
// Mallory kept the old key — that is the whole premise of the feature.
const malloryHas = await acceptLabelKey(mallory.wrapped, CONFIDENTIAL,
mallory.privateKey, mallory.publicKey);
assert.deepEqual(malloryHas, oldLabelKey, "she really does still hold it");
await rotateLabelKey({
label: CONFIDENTIAL,
privateKey: alice.privateKey, publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining: [
{ principalID: alice.principalID, publicKey: alice.publicKey },
{ principalID: bob.principalID, publicKey: bob.publicKey },
],
nodeKeys, toGeneration: 2,
persistGrant: db.persistGrant, persistNodeKey: db.persistNodeKey,
});
const stored = db.nodes.get("node-0");
await assert.rejects(
() => unwrapNodeKey(stored.wrapped, malloryHas, CONFIDENTIAL),
"the key she kept must not open the re-wrapped node key");
});
test("rotating to nobody is refused rather than orphaning every file", async () => {
const { alice, nodeKeys } = await setup({ files: 1 });
const db = store();
await assert.rejects(
() => rotateLabelKey({
label: CONFIDENTIAL,
privateKey: alice.privateKey, publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining: [],
nodeKeys, toGeneration: 2,
persistGrant: db.persistGrant, persistNodeKey: db.persistNodeKey,
}),
/at least one remaining principal/);
assert.equal(db.nodes.size, 0, "nothing was re-wrapped under a discarded key");
});
test("⚠️ grants are written before any node key is re-wrapped", async () => {
const { alice, bob, nodeKeys } = await setup({ files: 2 });
const order = [];
await rotateLabelKey({
label: CONFIDENTIAL,
privateKey: alice.privateKey, publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining: [
{ principalID: alice.principalID, publicKey: alice.publicKey },
{ principalID: bob.principalID, publicKey: bob.publicKey },
],
nodeKeys, toGeneration: 2,
persistGrant: async () => { order.push("grant"); },
persistNodeKey: async () => { order.push("node"); },
});
assert.deepEqual(order, ["grant", "grant", "node", "node"],
"a crash between the two must leave files readable, not orphaned");
});
test("a rotation that died halfway can be re-run and only finishes the rest",
async () => {
const { alice, bob, nodeKeys, plaintextKeys } = await setup({ files: 3 });
const db = store();
const remaining = [
{ principalID: alice.principalID, publicKey: alice.publicKey },
{ principalID: bob.principalID, publicKey: bob.publicKey },
];
const common = {
label: CONFIDENTIAL,
privateKey: alice.privateKey, publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining, toGeneration: 2,
persistGrant: db.persistGrant, persistNodeKey: db.persistNodeKey,
};
// First attempt dies after one node key.
let done = 0;
await assert.rejects(() => rotateLabelKey({
...common,
nodeKeys,
persistNodeKey: async (n) => {
if (done++ >= 1) throw new Error("network died");
await db.persistNodeKey(n);
},
}), /network died/);
// The server's view: one node key at generation 2, the rest still at 1.
const resumed = nodeKeys.map(n =>
db.nodes.has(n.nodeID) ? { ...n, generation: 2 } : n);
// 🔴 The resume is handed the key the first run minted, recovered from the
// grant that run wrote for this principal. Without it the second run mints
// a different key, and node-0 — already re-wrapped under the first — opens
// under nothing anybody holds. That is data loss in the exact path
// resumability exists to make safe.
const mine = db.grants.filter(g => g.principalID === alice.principalID).pop();
const second = await rotateLabelKey({
...common, nodeKeys: resumed, wrappedNewLabelKey: mine.wrapped,
});
assert.equal(second.resumed, true);
assert.equal(second.skipped, 1, "the finished one is not redone");
assert.equal(second.rewrapped, 2);
// EVERY file opens under the surviving grant, including the one the
// abandoned run wrapped.
const grant = db.grants.filter(g => g.principalID === bob.principalID).pop();
const key = await acceptLabelKey(grant.wrapped, CONFIDENTIAL,
bob.privateKey, bob.publicKey);
for (const [nodeID, original] of plaintextKeys) {
const opened = await unwrapNodeKey(db.nodes.get(nodeID).wrapped, key, CONFIDENTIAL);
assert.deepEqual(opened, original, `${nodeID} opens after the resume`);
}
});
test("🔴 resuming WITHOUT the abandoned run's key would strand its work",
async () => {
// The bug this guards against, demonstrated rather than described: two runs
// that each mint a key leave the same generation split across both.
const { alice, bob, nodeKeys } = await setup({ files: 2 });
const db = store();
const remaining = [
{ principalID: alice.principalID, publicKey: alice.publicKey },
{ principalID: bob.principalID, publicKey: bob.publicKey },
];
const common = {
label: CONFIDENTIAL,
privateKey: alice.privateKey, publicKey: alice.publicKey,
wrappedOldLabelKey: alice.wrapped,
remaining, toGeneration: 2,
persistGrant: db.persistGrant, persistNodeKey: db.persistNodeKey,
};
await rotateLabelKey({ ...common, nodeKeys: [nodeKeys[0]] });
const firstRunWrapped = db.nodes.get("node-0").wrapped;
// A second run with no key handed to it mints a new one.
await rotateLabelKey({ ...common, nodeKeys: [nodeKeys[1]] });
const latest = db.grants.filter(g => g.principalID === bob.principalID).pop();
const key = await acceptLabelKey(latest.wrapped, CONFIDENTIAL,
bob.privateKey, bob.publicKey);
await assert.rejects(
() => unwrapNodeKey(firstRunWrapped, key, CONFIDENTIAL),
"the first run's work is unreadable — which is why the key is passed in");
});
-154
View File
@@ -1,154 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
deriveShareKey, createShareSecret, sealShare, openShare,
encodeShareSecret, decodeShareSecret,
} from "../src/shares.js";
import { createLabelKey, createContentKey } from "../src/keys.js";
import { label } from "../src/lattice.js";
import { equal } from "../src/bytes.js";
const RESTRICTED = label(3, [0, 1]);
const CONFIDENTIAL = label(2, []);
test("a cleared holder of the link recovers the key and the name", async () => {
const labelKey = createLabelKey();
const contentKey = createContentKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret, contentKey, name: "Q3 Forecast.txt",
});
const opened = await openShare({ labelKey, label: RESTRICTED, secret, ...sealed });
assert.deepEqual(opened.contentKey, contentKey);
assert.equal(opened.name, "Q3 Forecast.txt");
});
/**
* The property the whole design exists for: forwarding the link to someone who
* is not cleared gives them nothing at all.
*/
test("the link alone is useless without the label key", async () => {
const labelKey = createLabelKey();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret: createShareSecret(),
contentKey: createContentKey(), name: "Payroll.csv",
});
// Everything an uncleared recipient could have: the link, and their own
// (different) label key from a clearance that does not cover this label.
const theirLabelKey = createLabelKey();
await assert.rejects(() => openShare({
labelKey: theirLabelKey, label: RESTRICTED, secret: createShareSecret(), ...sealed,
}));
});
test("holding the right label key but not the link is also useless", async () => {
const labelKey = createLabelKey();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret: createShareSecret(),
contentKey: createContentKey(), name: "Payroll.csv",
});
await assert.rejects(() => openShare({
labelKey, label: RESTRICTED, secret: createShareSecret(), ...sealed,
}));
});
test("both halves are required together", async () => {
const labelKey = createLabelKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret, contentKey: createContentKey(), name: "x",
});
// Right secret, wrong key.
await assert.rejects(() => openShare({
labelKey: createLabelKey(), label: RESTRICTED, secret, ...sealed }));
// Right key, wrong secret.
await assert.rejects(() => openShare({
labelKey, label: RESTRICTED, secret: createShareSecret(), ...sealed }));
// Both right.
assert.ok(await openShare({ labelKey, label: RESTRICTED, secret, ...sealed }));
});
/// The label is AAD, so a share cannot be replayed against a relabelled row.
test("a share does not open under a different label", async () => {
const labelKey = createLabelKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret, contentKey: createContentKey(), name: "x",
});
await assert.rejects(() => openShare({
labelKey, label: CONFIDENTIAL, secret, ...sealed }));
});
test("the share key depends on both inputs", async () => {
const labelKey = createLabelKey(), secret = createShareSecret();
const base = await deriveShareKey(labelKey, secret);
assert.ok(equal(base, await deriveShareKey(labelKey, secret)));
assert.ok(!equal(base, await deriveShareKey(createLabelKey(), secret)));
assert.ok(!equal(base, await deriveShareKey(labelKey, createShareSecret())));
});
test("the secret survives a URL fragment round trip", async () => {
for (let i = 0; i < 30; i++) {
const secret = createShareSecret();
const encoded = encodeShareSecret(secret);
assert.match(encoded, /^[A-Za-z0-9_-]+$/, "must be fragment-safe");
assert.deepEqual(decodeShareSecret(encoded), secret);
}
});
// ---- optional password, the DoD SAFE pattern ----
test("a password adds a third factor without weakening the other two", async () => {
const labelKey = createLabelKey();
const contentKey = createContentKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret, contentKey,
name: "Board pack.pdf", password: "the spoken word",
});
assert.ok(sealed.passwordSalt, "a salt must be published for the recipient");
const opened = await openShare({
labelKey, label: RESTRICTED, secret, ...sealed, password: "the spoken word",
});
assert.deepEqual(opened.contentKey, contentKey);
assert.equal(opened.name, "Board pack.pdf");
});
test("the link and clearance are not enough once a password is set", async () => {
const labelKey = createLabelKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret,
contentKey: createContentKey(), name: "x", password: "correct",
});
// Everything except the password.
await assert.rejects(() => openShare({ labelKey, label: RESTRICTED, secret, ...sealed }),
/needs the password/);
await assert.rejects(() => openShare({
labelKey, label: RESTRICTED, secret, ...sealed, password: "wrong" }));
});
/// A password must not become a way around clearance.
test("a password does not substitute for being cleared", async () => {
const labelKey = createLabelKey();
const secret = createShareSecret();
const sealed = await sealShare({
labelKey, label: RESTRICTED, secret,
contentKey: createContentKey(), name: "x", password: "known to everyone",
});
await assert.rejects(() => openShare({
labelKey: createLabelKey(), label: RESTRICTED, secret, ...sealed,
password: "known to everyone",
}));
});
test("a protected share cannot be opened as an unprotected one", async () => {
const labelKey = createLabelKey(), secret = createShareSecret();
const withPassword = await deriveShareKey(labelKey, secret, new Uint8Array(32));
const without = await deriveShareKey(labelKey, secret);
assert.ok(!equal(withPassword, without), "the two constructions must differ");
});
-97
View File
@@ -1,97 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createWallet, wrapEntropy, unwrapEntropy, recoverPhrase,
importPhrase, seedFor } from "../src/wallet.js";
import { toMnemonic, fromMnemonic, toSeed } from "../src/bip39.js";
import { CONTEXT } from "../src/kdf.js";
/** Stand-in list; see bip39.test.mjs for why the real one is not vendored yet. */
const words = Array.from({ length: 2048 }, (_, i) => `w${i.toString(36)}`);
const kek = () => crypto.getRandomValues(new Uint8Array(32));
test("a new wallet gives a phrase and a record that agree", async () => {
const walletKEK = kek();
const { phrase, record } = await createWallet({ walletKEK, words });
assert.equal(phrase.split(" ").length, 24, "256 bits by default");
const again = await recoverPhrase(record, walletKEK, words);
assert.equal(again, phrase, "the record regenerates the same phrase");
});
test("🔴 either door alone opens the same wallet", async () => {
const walletKEK = kek();
const { phrase, record } = await createWallet({ walletKEK, words });
// Door one: the account.
const viaAccount = await seedFor(record, walletKEK, words);
// Door two: the phrase, with no account involved at all.
const viaPhrase = await toSeed(phrase);
assert.deepEqual(viaAccount, viaPhrase,
"the same wallet, reached two ways — this is the promise");
});
test("🔴 the ENTROPY is stored, not the seed, so the phrase can always be shown again",
async () => {
const walletKEK = kek();
const { phrase, record } = await createWallet({ walletKEK, words });
const stored = await unwrapEntropy(record, walletKEK);
// Storing a seed would make this impossible: it is a one-way function of
// the phrase, so the words could never be recovered from it.
assert.deepEqual(stored, await fromMnemonic(phrase, words));
assert.equal(stored.length, 32);
assert.notEqual(stored.length, 64, "a seed is 64 bytes; entropy is not a seed");
});
test("the wrong account key opens nothing", async () => {
const { record } = await createWallet({ walletKEK: kek(), words });
await assert.rejects(() => unwrapEntropy(record, kek()));
});
test("⚠️ the record is bound to the wallet context", async () => {
const walletKEK = kek();
const entropy = crypto.getRandomValues(new Uint8Array(32));
const record = await wrapEntropy(entropy, walletKEK);
// Re-wrapping the same bytes under a different context must not produce
// something the wallet path accepts — the same separation that stops a
// Files identity record being opened as Messenger's.
const { wrapWithKey } = await import("../src/wrap.js");
const asFiles = await wrapWithKey(walletKEK, entropy,
new TextEncoder().encode(CONTEXT.files));
await assert.rejects(() => unwrapEntropy(asFiles, walletKEK),
"a record made for another context must not open here");
});
test("a phrase from another wallet can be imported", async () => {
const walletKEK = kek();
const entropy = crypto.getRandomValues(new Uint8Array(16));
const elsewhere = await toMnemonic(entropy, words); // 12 words, another app
const record = await importPhrase(elsewhere, walletKEK, words);
assert.equal(await recoverPhrase(record, walletKEK, words), elsewhere);
assert.deepEqual(await seedFor(record, walletKEK, words), await toSeed(elsewhere));
});
test("⚠️ a phrase that fails its checksum is refused at import, not stored",
async () => {
const walletKEK = kek();
const phrase = (await toMnemonic(crypto.getRandomValues(new Uint8Array(16)), words))
.split(" ");
phrase[2] = words[(words.indexOf(phrase[2]) + 1) % 2048];
await assert.rejects(() => importPhrase(phrase.join(" "), walletKEK, words),
/checksum/);
});
test("12-word wallets are supported for people who want them", async () => {
const walletKEK = kek();
const { phrase } = await createWallet({ walletKEK, words, entropyBytes: 16 });
assert.equal(phrase.split(" ").length, 12);
});
test("two wallets made in a row are different", async () => {
const walletKEK = kek();
const a = await createWallet({ walletKEK, words });
const b = await createWallet({ walletKEK, words });
assert.notEqual(a.phrase, b.phrase);
});
-70
View File
@@ -1,70 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { generateIdentity } from "../src/identity.js";
import { wrapToPublicKey, unwrapWithPrivateKey, wrapWithKey, unwrapWithKey } from "../src/wrap.js";
import { labelBytes, label } from "../src/lattice.js";
import { random } from "../src/bytes.js";
const CONFIDENTIAL = label(2, [0]);
const RESTRICTED = label(3, [0]);
test("asymmetric wrap round-trips to the holder of the private key", async () => {
const recipient = await generateIdentity();
const secret = random(32);
const blob = await wrapToPublicKey(recipient.publicKey, secret, labelBytes(CONFIDENTIAL));
const out = await unwrapWithPrivateKey(recipient.privateKey, recipient.publicKey, blob, labelBytes(CONFIDENTIAL));
assert.deepEqual(out, secret);
});
test("another principal cannot unwrap it", async () => {
const recipient = await generateIdentity();
const intruder = await generateIdentity();
const blob = await wrapToPublicKey(recipient.publicKey, random(32), labelBytes(CONFIDENTIAL));
await assert.rejects(
() => unwrapWithPrivateKey(intruder.privateKey, intruder.publicKey, blob, labelBytes(CONFIDENTIAL))
);
});
// The property that makes labels something the server cannot edit.
test("a wrap does not open under a different label", async () => {
const recipient = await generateIdentity();
const blob = await wrapToPublicKey(recipient.publicKey, random(32), labelBytes(CONFIDENTIAL));
await assert.rejects(
() => unwrapWithPrivateKey(recipient.privateKey, recipient.publicKey, blob, labelBytes(RESTRICTED))
);
});
test("symmetric wrap round-trips and rejects the wrong KEK", async () => {
const kek = random(32), other = random(32), secret = random(32);
const blob = await wrapWithKey(kek, secret, labelBytes(CONFIDENTIAL));
assert.deepEqual(await unwrapWithKey(kek, blob, labelBytes(CONFIDENTIAL)), secret);
await assert.rejects(() => unwrapWithKey(other, blob, labelBytes(CONFIDENTIAL)));
});
test("symmetric wrap does not open under a different label", async () => {
const kek = random(32);
const blob = await wrapWithKey(kek, random(32), labelBytes(CONFIDENTIAL));
await assert.rejects(() => unwrapWithKey(kek, blob, labelBytes(RESTRICTED)));
});
test("version bytes keep the two wrap kinds from being confused", async () => {
const recipient = await generateIdentity();
const kek = random(32);
const asymmetric = await wrapToPublicKey(recipient.publicKey, random(32), labelBytes(CONFIDENTIAL));
const symmetric = await wrapWithKey(kek, random(32), labelBytes(CONFIDENTIAL));
assert.equal(asymmetric[0], 1);
assert.equal(symmetric[0], 17);
await assert.rejects(() => unwrapWithKey(kek, asymmetric, labelBytes(CONFIDENTIAL)), /unsupported wrap version/);
await assert.rejects(
() => unwrapWithPrivateKey(recipient.privateKey, recipient.publicKey, symmetric, labelBytes(CONFIDENTIAL)),
/unsupported wrap version/
);
});
test("tampering with the ciphertext is detected", async () => {
const kek = random(32);
const blob = await wrapWithKey(kek, random(32), labelBytes(CONFIDENTIAL));
blob[blob.length - 1] ^= 0x01;
await assert.rejects(() => unwrapWithKey(kek, blob, labelBytes(CONFIDENTIAL)));
});
-96
View File
@@ -1,96 +0,0 @@
// Produce interop vectors for the native engines.
//
// Encryption here is randomised, so there is no fixed expected ciphertext to
// assert against. What a second implementation must reproduce is the *decrypt*
// side: given this key material and this blob, it must recover exactly this
// plaintext. Anything that gets the framing, the AAD, or the key hierarchy
// wrong fails, which is the whole point.
//
// The reverse direction — native encrypts, JS decrypts — is checked in the
// native repositories against these same key values.
import { b64 } from "../src/bytes.js";
import { label, labelBytes } from "../src/lattice.js";
import { generateIdentity, protectIdentity, exportPublicKey } from "../src/identity.js";
import {
createLabelKey, createNodeKey, createContentKey,
grantLabelKey, wrapNodeKey, wrapContentKey,
} from "../src/keys.js";
import { encryptName, nameDigest } from "../src/names.js";
import { encryptContent } from "../src/content.js";
import { generateRecoveryCode } from "../src/recovery.js";
import { deriveIdentityKEK, deriveAuthSecret, CONTEXT, AUTH_CONTEXT } from "../src/kdf.js";
const FAST = { id: 1, name: "PBKDF2-SHA256", iterations: 1000, saltBytes: 16 };
const utf8 = (s) => new TextEncoder().encode(s);
const vectors = { version: 1, note: "Decrypt these. See docs/SPEC.md.", cases: {} };
// --- canonical label encoding -------------------------------------------
vectors.cases.labelBytes = [
{ classification: 3, compartments: [0], expected: b64(labelBytes(label(3, [0]))) },
{ classification: 1, compartments: [], expected: b64(labelBytes(label(1, []))) },
{ classification: 0, compartments: [63], expected: b64(labelBytes(label(0, [63]))) },
{ classification: 2, compartments: [0, 1, 63], expected: b64(labelBytes(label(2, [0, 1, 63]))) },
];
// --- key derivation ------------------------------------------------------
const kdfSalt = new Uint8Array(16).fill(7);
const passphrase = "correct horse battery staple";
const kek = await deriveIdentityKEK(passphrase, kdfSalt, { params: FAST, context: CONTEXT.files });
const kekRaw = new Uint8Array(await crypto.subtle.exportKey("raw", await crypto.subtle.importKey(
"raw", await crypto.subtle.exportKey("raw", kek).catch(() => new ArrayBuffer(32)),
{ name: "AES-GCM" }, true, ["encrypt"]).catch(() => kek)).catch(() => new ArrayBuffer(32)));
vectors.cases.kdf = {
passphrase,
salt: b64(kdfSalt),
iterations: FAST.iterations,
contexts: {
filesIdentity: CONTEXT.files,
filesAuth: AUTH_CONTEXT.files,
messengerIdentity: CONTEXT.messenger,
},
// The auth secret is exportable raw, so it pins the derivation exactly.
authSecret: b64(await deriveAuthSecret(passphrase, kdfSalt, { params: FAST })),
};
// --- the hierarchy, end to end ------------------------------------------
const fileLabel = label(3, [0, 1]);
const identity = await generateIdentity();
const labelKey = createLabelKey();
const nodeKey = createNodeKey();
const contentKey = createContentKey();
const body = utf8("revenue: 41\nheadcount: 12\n");
const { digest, ciphertext: nameCiphertext } = await encryptName(nodeKey, "Q3 Forecast.txt", fileLabel);
vectors.cases.hierarchy = {
label: { classification: 3, compartments: [0, 1] },
identityPublicKey: b64(await exportPublicKey(identity.publicKey)),
identityRecord: await protectIdentity(identity.privateKey, passphrase, { params: FAST }),
labelKey: b64(labelKey),
nodeKey: b64(nodeKey),
contentKey: b64(contentKey),
labelKeyGrant: b64(await grantLabelKey(labelKey, fileLabel, identity.publicKey)),
wrappedNodeKey: b64(await wrapNodeKey(nodeKey, labelKey, fileLabel)),
wrappedContentKey: b64(await wrapContentKey(contentKey, nodeKey, fileLabel)),
nameDigest: b64(digest),
nameCiphertext: b64(nameCiphertext),
expectedName: "Q3 Forecast.txt",
content: b64(await encryptContent(contentKey, body, fileLabel, 16)),
expectedContent: b64(body),
contentChunkSize: 16,
};
// --- name digests are keyed, so they pin the HMAC exactly ----------------
vectors.cases.nameDigest = [
{ folderKey: b64(nodeKey), name: "Q3 Forecast.txt", expected: b64(await nameDigest(nodeKey, "Q3 Forecast.txt")) },
{ folderKey: b64(nodeKey), name: "café", expected: b64(await nameDigest(nodeKey, "café")) },
{ folderKey: b64(nodeKey), name: "Payroll", expected: b64(await nameDigest(nodeKey, "Payroll")) },
];
// --- recovery codes ------------------------------------------------------
const recovery = await generateRecoveryCode();
vectors.cases.recovery = { code: recovery.code, entropy: b64(recovery.entropy) };
console.log(JSON.stringify(vectors, null, 2));
+8 -12
View File
@@ -5,11 +5,8 @@ marked, because two of them cannot.
## Before anything
**DNS does not exist yet.** Neither `accounts.flamenet.io` nor
`files.flamenet.io` resolves. `flamenet.io` and `flamenetmessenger.com` both
point at `135.148.121.177`; `flamenetfiles.com` resolves through Cloudflare but
serves nothing. Create an A record for `accounts.flamenet.io` →
`135.148.121.177` and let it propagate before requesting a certificate, or
**Check DNS first.** `accounts.flamenet.io` must resolve to
`135.148.121.177` and have propagated before you request a certificate, or
certbot will fail and rate-limit the attempt.
**Check the architecture.** `uname -m` on the box. Images built on an Apple
@@ -28,10 +25,10 @@ openssl rand -base64 36 # ENCLAVE_ACCOUNTS_DB_PASSWORD
⛔ **`ENCLAVE_ACCOUNTS_SECRET` is permanent.** Every product pseudonym is
`HMAC(secret, account_id || product)`. Rotating it changes who every account
*is* to the file server, orphaning their data with no way back. Set it once.
*is* to a relay, orphaning their data with no way back. Set it once.
⛔ **`ENCLAVE_JWT_SECRET` must match whatever the file server verifies with.**
The account service signs clearance tokens; the file server checks them. A
⛔ **`ENCLAVE_JWT_SECRET` must match whatever verifies the tokens.**
The account service signs session tokens; a relay checks them. A
mismatch looks like every login being rejected. Rotating it invalidates every
outstanding session, which is a legitimate emergency action but not a routine
one.
@@ -57,7 +54,7 @@ ACCOUNTS_SERVICE_DATABASE_URL=postgres://accounts_service:<ENCLAVE_ACCOUNTS_DB_P
```
⚠️ The service URL must **not** be a superuser and must not hold `BYPASSRLS`.
That is what keeps the account service out of tenant data.
That is what keeps the account service inside its own schema and nowhere else.
## 3. Image
@@ -162,6 +159,5 @@ What it costs, so nobody is surprised:
22 after failed authentication attempts. Clear it from the box:
`sudo fail2ban-client set sshd unbanip 71.191.250.34`, or
`sudo cscli decisions delete --ip 71.191.250.34` if CrowdSec holds it.
- The file server (`files.flamenet.io`) is not deployed either. The account
service is usable without it, but `ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS` needs to
name that origin before the web client can reach it.
- `ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS` needs to name any browser origin that
calls this service. The apps are not browsers and do not need it.
-61
View File
@@ -80,69 +80,8 @@ services:
- "${ENCLAVE_BIND:-127.0.0.1}:${ENCLAVE_ACCOUNTS_PORT:-8100}:8100"
restart: unless-stopped
migrate:
build: .
depends_on:
db:
condition: service_healthy
# Serialised deliberately. Both services keep their ledger in the same
# `_fluent_migrations` table, and two concurrent `CREATE TABLE IF NOT
# EXISTS` calls race in the Postgres catalog rather than one backing off.
accounts-migrate:
condition: service_completed_successfully
environment:
DATABASE_URL: postgres://enclave_owner:${POSTGRES_PASSWORD}@db:5432/enclave
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET:?set ENCLAVE_JWT_SECRET in .env}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
ENCLAVE_TENANT_PASSWORD: ${ENCLAVE_TENANT_PASSWORD:?set ENCLAVE_TENANT_PASSWORD in .env}
command: ["./EnclaveServer", "migrate", "--yes"]
restart: "no"
app:
build: .
depends_on:
migrate:
condition: service_completed_successfully
environment:
# The tenant role, not the owner. This is the whole point.
DATABASE_URL: postgres://tenant_${ENCLAVE_TENANT:-default}:${ENCLAVE_TENANT_PASSWORD}@db:5432/enclave
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
ENCLAVE_BLOB_PATH: /app/blobs
# Where the browser reaches the account service. A different origin, so
# the app page carries it and that service allow-lists this one.
# What the browser dials. Published, and therefore a host address.
ENCLAVE_ACCOUNTS_URL: ${ENCLAVE_ACCOUNTS_URL:-http://127.0.0.1:8100}
# What this container dials. Different on purpose: inside the network,
# 127.0.0.1 is this container, and the failure reads as "could not reach
# the account service" while the service is plainly running.
ENCLAVE_ACCOUNTS_INTERNAL_URL: ${ENCLAVE_ACCOUNTS_INTERNAL_URL:-http://accounts:8100}
ENCLAVE_SITE_URL: ${ENCLAVE_SITE_URL:-http://127.0.0.1:8080}
ENCLAVE_APP_URL: ${ENCLAVE_APP_URL:-/app}
FN_DONATE_PROVIDER: ${FN_DONATE_PROVIDER:-}
FN_DONATE_SECRET: ${FN_DONATE_SECRET:-}
# The connected account the donation is charged on, and the publishable
# key the browser mounts the form with. Without the first, the same key
# charges the platform account and Stripe reports no error.
FN_DONATE_ACCOUNT: ${FN_DONATE_ACCOUNT:-}
FN_DONATE_PUBLISHABLE_KEY: ${FN_DONATE_PUBLISHABLE_KEY:-}
LOG_LEVEL: ${LOG_LEVEL:-info}
volumes:
# Ciphertext blobs. Without this the files themselves live only in the
# container layer and vanish on the next `docker compose up --build`,
# leaving every node row pointing at nothing.
- enclave-blobs:/app/blobs
ports:
- "${ENCLAVE_BIND:-127.0.0.1}:${ENCLAVE_PORT:-8080}:8080"
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/healthz || exit 1"]
interval: 15s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
enclave-pgdata:
name: enclave-pgdata
enclave-blobs:
name: enclave-blobs
-274
View File
@@ -1,274 +0,0 @@
# Enclave client crypto — wire format
Version 1. Byte layouts are normative: an iOS (CryptoKit) or Android
implementation must produce and accept exactly these. `client/src/` is the
reference implementation; where an implementation disagrees with it, this
document decides, and the reference is corrected.
All integers are big-endian. All AEAD is AES-256-GCM with a 128-bit tag.
## 1. Labels
A label is a classification (`int16`) and a compartment set (bit indices
`0…63`). Canonical encoding is **10 bytes**:
```
offset size field
0 2 classification, int16be
2 8 compartment bitmask, uint64be
```
This layout matches the `classification` and `compartments` columns so the two
representations cannot drift. Bit 63 makes the Postgres `bigint` negative; that
is expected, and `Compartments.postgresBitPattern` in Swift performs the
reinterpretation.
**The canonical label encoding is the AAD for every construction below.** That
is what prevents the server from reclassifying data by editing a column: a
relabelled row fails to decrypt rather than silently changing sensitivity. A
downgrade therefore requires a client that re-encrypts — the regrade workflow.
## 2. Key derivation
```
master = PBKDF2-SHA256(passphrase, salt, iterations) -> 32 bytes
productKEK = HKDF-SHA256(master, salt = "", info = context) -> AES-256 key
```
`context` is a per-product ASCII string, currently:
| Product | Context |
|---|---|
| Files | `flamenet/files/identity/v1` |
| Messenger | `flamenet/messenger/identity/v1` |
One credential can back several products without any sharing key material.
⚠️ Context strings cannot be changed later without stranding every account.
Defaults for new accounts: `iterations = 650000`, `saltBytes = 16`. The
iteration count is **recorded per account**, not looked up from a registry, so
raising the default never locks anyone out.
## 3. Identity record
X25519 keypair. The private half is stored PKCS#8, encrypted under `productKEK`
with `context` as AAD, so a record made for one product cannot be opened as
another's even with the right passphrase.
```json
{ "v": 1, "kdf": 1, "iterations": 650000, "context": "...",
"salt": "base64", "nonce": "base64", "privateKey": "base64" }
```
## 4. Key wrapping
### 4.1 Asymmetric (version 1) — to an identity public key
```
offset size field
0 1 version = 1
1 32 ephemeral X25519 public key
33 12 nonce
45 .. ciphertext || tag
```
```
shared = X25519(ephemeralPrivate, recipientPublic)
kek = HKDF-SHA256(shared, salt = ephemeralPublic || recipientPublic,
info = "enclave/wrap/v1")
```
Both public keys enter the salt, binding the wrap to that sender/recipient pair.
### 4.2 Symmetric (version 17) — under a key-encryption key
```
offset size field
0 1 version = 17
1 12 nonce
13 .. ciphertext || tag
```
Version numbers are disjoint across 4.1 and 4.2 so a blob fed to the wrong
unwrap path errors rather than producing anything.
## 5. Key hierarchy
```
identity key per user, unlocked by passphrase
| wraps (4.1, AAD = label)
label key one per label in use, granted per principal
| wraps (4.2, AAD = label)
node key one per file or folder
| wraps (4.2, AAD = label)
content key one per revision
```
**A node key is wrapped to its own label key, never to its parent folder's node
key.** The tree invariant permits a RESTRICTED file inside a CONFIDENTIAL
folder, so parent-derived keys — the conventional Drive design — would hand
every folder-key holder content above their clearance, leaving the lattice
enforced only by the database. A stolen backup would read straight through it.
## 6. Filenames
```
digest = HMAC-SHA256(folderKey, NFC(name)) -> 32 bytes
```
`folderKey` is the containing folder's node key; for root-level entries the
label key stands in. Keying per folder stops the server inverting names,
dictionary-attacking them, or correlating them across folders.
Comparison is case-sensitive; only NFC normalisation is applied. Adding case
folding later changes every digest.
```
offset size field
0 1 version = 1
1 12 nonce
13 .. ciphertext || tag AAD = label(10) || digest(32)
```
Binding the digest into the AAD stops the server pairing a name ciphertext with
another row's digest.
## 7. Content
Framed into independently authenticated chunks, because a single GCM blob
cannot be verified incrementally.
```
offset size field
0 4 magic "ENCL"
4 1 version = 1
5 4 chunk size in plaintext bytes, uint32be
9 8 base nonce
17 .. chunks
```
Each stored chunk is `chunkSize + 16` bytes except the last.
```
chunk i nonce = baseNonce(8) || uint32be(i)
chunk i AAD = label(10) || uint32be(i) || uint8(i == lastIndex)
```
The three attacks that independent chunk authentication would otherwise permit,
and what closes each:
| Attack | Closed by |
|---|---|
| Truncation — drop trailing chunks | `isLast` flag in AAD |
| Reordering | chunk index in nonce and AAD |
| Cross-file splicing | label in AAD, content key per revision |
An empty file is still one chunk, so it carries an authenticated end marker and
cannot be confused with a file truncated to nothing.
## 8. Wallet keys
A wallet is a third product context, and almost everything above applies to it
unchanged. One thing does not, and it is the thing that matters.
### 8.1 The seed is NOT derived from the passphrase
Files and Messenger both derive their identity from the account passphrase
(§2). A wallet must not.
Two reasons, and either alone is decisive:
- **A passphrase can be changed.** Changing it re-derives `productKEK`, which
for Files means re-wrapping an identity record and for a wallet would mean
every address deriving differently. Files can be re-wrapped. Coins sent to an
address nobody can derive again are gone.
- **A derived seed is not portable, which is the whole requirement.** The point
of a standard seed phrase is that it restores into somebody else's wallet.
A phrase that only means anything alongside a Flamenet passphrase is not
portable, and one that can be exported without it makes the derivation
decoration — the phrase was the root all along.
So the wallet root is its own secret, generated from 128 or 256 bits of fresh
entropy and never a function of anything else the account knows.
### 8.2 Recovery is BIP-39, not §2's recovery codes
The recovery codes in this system are Crockford base32 with a 12-bit checksum,
and the reasoning for rejecting a word list is written down: vendoring 2,048
words that must be byte-exact is a footgun, and one wrong entry produces codes
that cannot be decoded.
That reasoning is right for Files and does not carry here. A wallet phrase has
to be understood by software nobody in this project controls, which means
BIP-39 or nothing. Two things make the footgun manageable:
- BIP-39 carries its own checksum, so a mistyped word fails to validate rather
than silently deriving a different wallet.
- ⚠️ **The vendored word list is verified against its published SHA-256 by a
test.** That is what turns "silently wrong" into "fails at build", and it is
not optional — a corrupted list is exactly the failure the objection above
describes.
### 8.3 At rest, and why there are two doors
The seed is stored wrapped under the wallet `productKEK` using §4.2, with the
context string as AAD, exactly as an identity record is.
```
context = flamenet/wallet/seed/v1
```
That gives two independent ways back in, and both are wanted:
| You have | You can |
|---|---|
| The account passphrase | Open the wallet on any device that syncs it |
| The BIP-39 phrase | Restore into this wallet **or any other** |
| Neither | Nothing — and this is not recoverable by anyone, by design |
🔴 **The second row is the promise, and it outlives this project.** A wallet
whose funds are reachable only through Flamenet infrastructure is a custodial
product wearing a self-custody label. The phrase is what makes that untrue.
### 8.4 Derivation
Standard BIP-32 over the BIP-39 seed, BIP-44 paths per chain. Nothing bespoke:
a non-standard path is another way of being unable to restore elsewhere, which
§8.1 already spent the argument on.
### 8.5 Labels and compartments — deliberately deferred
The obvious move is to put wallet keys inside the lattice, so a wallet can be
classified and compartmented like a file. It fits, and it would be unusual in a
good way.
⚠️ **It is not specified here, because it inherits key rotation.** Revoking a
compartment rotates its label key and re-wraps everything under it. That
is correct for documents. Applied to the wrap around a wallet seed it means a
revocation event re-encrypts the thing standing between somebody and their
money, and every failure mode in that path — a partial rewrap, a client that
dies halfway, a generation mismatch — has a worse worst case than it does for a
file.
A wallet at the bottom of the lattice, wrapped only under the account identity,
has none of that and loses nothing anyone has asked for yet. Compartmented
wallets can be specified once rotation has been exercised on data where the
worst case is recoverable.
## 9. Not yet specified
- **Post-quantum wrapping.** Section 4.1 is classical X25519. A hybrid
ML-KEM-768 variant would take a new version byte; harvest-now-decrypt-later
is the motivating threat, since identity keys are long-lived. No PQ claim is
made until it exists on every client — see the same staging in flamenet-e2e.
- ~~**Recovery phrases.**~~ Built — Crockford base32, 128 bits and a 12-bit
checksum, wrapping the same identity key under its own context so neither
secret reveals the other. This list said otherwise for a while after they
shipped; a spec that under-claims is a smaller problem than one that
over-claims, and still a problem.
- **Key rotation on clearance revocation.** Half done. The server side records
a revocation and the generation it ends, and refuses to call it `rotated`
without a client naming itself — a status that cannot be reached by deleting
a grant, because the key is already on the revoked person's device. The
client that mints the new generation and re-wraps every node key under it
does not exist yet, so a revoked holder still reads what they held.
-136
View File
@@ -1,136 +0,0 @@
{
"version": 1,
"note": "Decrypt these. See docs/SPEC.md.",
"cases": {
"labelBytes": [
{
"classification": 3,
"compartments": [
0
],
"expected": "AAMAAAAAAAAAAQ=="
},
{
"classification": 1,
"compartments": [],
"expected": "AAEAAAAAAAAAAA=="
},
{
"classification": 0,
"compartments": [
63
],
"expected": "AACAAAAAAAAAAA=="
},
{
"classification": 2,
"compartments": [
0,
1,
63
],
"expected": "AAKAAAAAAAAAAw=="
}
],
"kdf": {
"passphrase": "correct horse battery staple",
"salt": "BwcHBwcHBwcHBwcHBwcHBw==",
"iterations": 1000,
"contexts": {
"filesIdentity": "flamenet/files/identity/v1",
"filesAuth": "flamenet/files/auth/v1",
"messengerIdentity": "flamenet/messenger/identity/v1"
},
"authSecret": "67XBl7YK3eWLxlwCsQfvGZKiokbcY8mEqCw1E8QDxaE="
},
"hierarchy": {
"label": {
"classification": 3,
"compartments": [
0,
1
]
},
"identityPublicKey": "rx6FBwu0ekejPG/KuVDGUjDGgpk1KeuneLAjxSQ4Ul0=",
"identityRecord": {
"v": 1,
"kdf": 1,
"iterations": 1000,
"context": "flamenet/files/identity/v1",
"salt": "3nW9N41kTjy+XV4MTrZpBw==",
"nonce": "/RfcIYNdqzoJjFJ0",
"privateKey": "Cq0gk03SqDC0QrYMdhyz/KwdwRxAaG95Cow0sE2+nilEjAnbgeDZPDSkKoZKSVla5Jv2Tf0AsDwYmGS01EWVGQ=="
},
"labelKey": "mdghL5vAIw5DeSsY9/BwRARhADaDBQnCxZDqeRHxl20=",
"nodeKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
"contentKey": "WP2IXXEHgqN9B4LosOtkeQgbfNgaqmLPSm9t02XQkc0=",
"labelKeyGrant": "Acacc9qfWCLxyXcc6rRTEyUDJxwdc0wxqy4UW8NSHwlhv/rvokK6kYMRfcTyUfXoE8H68Sk6nvIuC3sBAYMIcGkX/El9tUms+c90ffr+EbRZqyR16dREwtPowST+",
"wrappedNodeKey": "EUITJmLQVJgoL8z+lcfoKXIxHsGDWGVXDsxqdQnoPghuMvbD3eyhCCVT3lkDOQJ2sOKrfm8aAgEpzUSGMw==",
"wrappedContentKey": "EUQ1b+IbuxUblsm1gKGp1GWk8Tw3IsNNCGvTVwfQBA8OHLWmiHgpDburxl3GweXMzo9rFbhPazZkYKBsmw==",
"nameDigest": "zEu1hnRTyD+91Vke88XDSSVa/jfVERPIbMLB2kul4hY=",
"nameCiphertext": "AZlKWc9giJcswo4Fva4Ez7BhdljC5MfIsUpeSYz4LxwlAl9bobFz6Te/jCQ=",
"expectedName": "Q3 Forecast.txt",
"content": "RU5DTAEAAAAQfPLZFLMzaHtthhTgPXIbF6Q5iDW4RM+x97t9Ggd4lEJ3V1xMmyKvg8ISLjEUixPNrNGpzhx58+qfkj0pXqqzZijC",
"expectedContent": "cmV2ZW51ZTogNDEKaGVhZGNvdW50OiAxMgo=",
"contentChunkSize": 16
},
"nameDigest": [
{
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
"name": "Q3 Forecast.txt",
"expected": "zEu1hnRTyD+91Vke88XDSSVa/jfVERPIbMLB2kul4hY="
},
{
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
"name": "café",
"expected": "yiuuJ6pdJeJX7gQ3YJFGWbtu10Qz4VvUwE2cdWhMLB4="
},
{
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
"name": "Payroll",
"expected": "NN1zYjaALbTzp1MAf8dUNbfd/DVQVQ8jN3cN0DiEZt8="
}
],
"recovery": {
"code": "BKKR-SJXB-E8M8-1A6B-CN47-WNM7-6RQN",
"entropy": "XOeMy6tyKICoy2VIflaHNg=="
}
},
"recovery": [
{
"entropy": "AEeO1RxjqvE4f8YNVJviKQ==",
"code": "013R-XN8W-CENF-2E3Z-RR6N-96Z2-57K9",
"kdfSecret": "00478ed51c63aaf1387fc60d549be229"
},
{
"entropy": "JWyz+kGIzxZdpOsyecAHTg==",
"code": "4NPB-7YJ1-H37H-CQD4-XCS7-KG07-9RBA",
"kdfSecret": "256cb3fa4188cf165da4eb3279c0074e"
},
{
"entropy": "SpHYH2at9DuCyRBXnuUscw==",
"code": "9A8X-G7V6-NQT3-Q0P9-21BS-XS9C-EE7C",
"kdfSecret": "4a91d81f66adf43b82c910579ee52c73"
},
{
"entropy": "b7b9RIvSGWCn7jV8wwpRmA==",
"code": "DYVF-TH4B-T8CP-19ZE-6NYC-62JH-K3JD",
"kdfSecret": "6fb6fd448bd21960a7ee357cc30a5198"
},
{
"entropy": "lNsiabD3PoXME1qh6C92vQ==",
"code": "JKDJ-4TDG-YWZ8-BK0K-BAGY-GBVP-QN2Y",
"kdfSecret": "94db2269b0f73e85cc135aa1e82f76bd"
},
{
"entropy": "uQBHjtUcY6rxOH/GDVSb4g==",
"code": "Q404-F3PN-3HHT-NW9R-FZ30-TN4V-W87R",
"kdfSecret": "b900478ed51c63aaf1387fc60d549be2"
}
],
"recoveryWithQ": {
"entropy": "AB06V3SRrsvoBSI/XHmWsw==",
"code": "00EK-MNVM-J6QC-QT05-48ZN-RYCP-PDSA",
"kdfSecret": "001d3a577491aecbe805223f5c7996b3"
}
}
-18
View File
@@ -1,18 +0,0 @@
#!/usr/bin/env bash
#
# The browser loads the crypto engine straight from client/src -- same files the
# Node test suite runs against, so what ships is what is tested. This copies
# them into the served directory rather than duplicating them in git.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -rf Public/js/crypto
mkdir -p Public/js/crypto
cp client/src/*.js Public/js/crypto/
# The wordlist is a module of its own, and the browser needs it to derive
# anything. Its digest is re-checked at runtime, so copying is not trusted.
mkdir -p Public/js/crypto/wordlists
cp client/src/wordlists/english.js Public/js/crypto/wordlists/
echo "ok: copied $(ls client/src/*.js | wc -l | tr -d ' ') modules into Public/js/crypto"

Some files were not shown because too many files have changed in this diff Show More