Skip to content

Commit b6aa553

Browse files
wesbillmanBrainBrain
authored
feat(mobile): account onboarding, key recovery and hosted reconnect (#8375)
## Behavior Adds optional mobile Builderlab sign-in, identity backup/recovery, community discovery/creation, and account-aware reconnect. **Builderlab features are disabled by default:** when `BUZZ_AUTH_DOMAINS` is unset or empty, account login, creation, backup/recovery, reconnect prompts, and background account restoration are hidden/disabled. QR/code pairing, links, and invites retain Nostr-only entry. Saved account state is retained for later opt-in. `--dart-define=BUZZ_AUTH_DOMAINS=communities.buzz.xyz,communities.public.builderlabstaging.xyz` opts those DNS domains and their subdomains into required account setup. The same policy gates pairing, deep links, durable community admission, and reconnect. A nonempty list enables Builderlab features; `BUZZ_BUILDERLAB_URL` alone does not. Enabled flows still require their backend services. Existing Nostr relay authentication remains mandatory. `BUZZ_HOSTED_RELAY_AUTH=true` enables scoped relay assertions and reconnect prompts only for configured authentication domains. Configure assertion issuance and each community's issuer binding before enabling assertions; enable relay enforcement last. Account credentials stay at Builderlab. Wrong-account recovery preserves keys; failed writes are not replayed; authentication is bounded by request deadlines. Hosted flows preserve keys across cancellation/restart, reconcile interrupted creation/invitation acceptance, and support manual nsec file import/export. Account identities are scoped to backend and authenticated subject; reusing an existing local key for an unbound account requires an explicit selection. Recovery reconciles the advertised and recovered inventories before automatic selection. Successful self-hosted admission retires its pending key, and iOS startup removes interrupted export files. Adds authenticated relay `GET /operator/communities/joined` for the companion Builderlab membership endpoint. ## Validation - Follow-up review repair at `66a12ac92`: self-hosted entry presents readable choices and import despite incomplete enumeration, while generation still requires a complete empty inventory; explicit selection uses exact-key lookup. Consuming a value-equal duplicate now advances dispatch. Reconnect requires an existing account binding or a subject-scoped backup receipt before signing an assertion, and pins the subject inside the serialized account request. An empty different account is refused without sending key proof. Focused checks: configured domains 58 passed; default 49 passed, 9 hosted-only skips. Separate isolated mutations fail the incomplete-inventory sheet, exact-key reuse, duplicate dispatch and reconnect journeys (including an empty-account-only bypass); restored controls pass. Evidence uses synthetic storage/network boundaries, not physical Android or live backend association. All mandatory commit/push hooks passed; fresh GitHub CI is pending. - Bounded review repair at `d3cc0003f`: incomplete secure-storage enumeration now blocks automatic identity generation while explicit known-key reads retain their fallback; declined/failed onboarding links release the queue; HTTP 429/5xx keeps Retry regardless of response encoding. Default app-gate coverage exercises a bind link followed by ordinary community entry. Focused checks: configured domains 47 passed; default 38 passed, 9 hosted-only skips. Removing the three production fixes in an isolated source/Git/build copy fails the identity-resolution, declined/failed queue, and Retry journey assertions; clean and restored controls pass. Storage and HTTP failures are synthetic; physical Android and live outage behavior were not exercised. Published after all mandatory commit/push hooks passed (mobile analysis/tests, branch-skew and file-size gates); fresh GitHub CI remains pending. - Existing whole-PR source review cleared the reconnect defects at `fb15d5b82`. - Domain-policy increment: focused environment, entry, app-gate, pairing and onboarding journeys pass with empty and configured domains. Existing pairing provider/page tests pass. Changed Dart files analyze cleanly. - Isolated source/Git/build mutation: forcing paired credentials through hosted login fails the default-build journey; clean and restored controls pass. CI now runs configured-domain journeys in addition to the default-build suite. - Integrated main through `5b433d929` at `0067c069c`, including its pinned Flutter upgrade. Preserved the PR welcome UI with the updated transition API and added Material surfaces around onboarding selection/consent rows. Focused post-merge runs pass in both configurations; all mandatory local push gates passed (mobile analysis/tests, Rust tests, desktop-native checks, branch-skew and file-size checks). - Merge-review repair at `a315bce11`: focused identity/storage/admission and widget journeys pass, including account switching with an empty or already-bound second account, explicit reuse, and self-hosted removal/rejoin with another key. Default-domain journeys pass too (hosted-only cases intentionally skip there). - Isolated source/Git/build mutation checks: bypassing account scoping, reuse consent, pending-key retirement, or recovery inventory reconciliation fails the relevant journey/invariant assertions; clean and restored controls pass. - Native `RunnerTests/IdentityFilePluginTests`: both tests pass on the iPhone 18 Pro iOS 27 simulator with an isolated app identifier. At `24a0dcaac`, the picker journey seeds residue in Library/Caches, matching path_provider_foundation, and verifies plugin startup removes it while preserving an unrelated file. The earlier tmp-only fixture did not exercise the actual export location. This is synthetic native cleanup/picker evidence, not a real terminated-share or live account round trip. - Follow-up: Caches and tmp cleanup; fallback to individually known identity slots when Android bulk enumeration fails; explicit replacement of a refused self-hosted key preserves its original before swapping the retry slot. Configured-domain journeys/invariants: 34 passed; default: 31 passed, 3 hosted-only skips. Isolated enumeration/retry mutations fail with passing controls. Bulk-read fallback preserves but cannot enumerate arbitrary other-account slots until bulk reads recover. - Configured-domain CI exposed a stale pairing-status assertion after account scoping. The repaired test checks the admission mismatch, preserved account/transfer keys, and no admitted community. The configured-domain CI selection passes locally (56 tests); removing the production mismatch guard fails the updated test, with clean/restored controls passing. This is synthetic coordinator evidence, not physical QR acceptance. - Final review repair (`40e1e6101`): native iOS export creation uses atomic complete file protection; normal and restart cleanup remain. Account/policy/claim HTTP uses one 30-second total deadline with request abort and body cancellation. Removed the unrelated NIP-FA spec edit. - Focused account/admission/export tests: 25 pass; configured-domain account/admission/onboarding journeys: 33 pass. Isolated deadline and native-dispatch mutations fail, with passing clean/restored controls. Native export/picker tests: 2 pass on iOS 27 simulator. The real file-protection attribute assertion is physical-device-only because simulator provides no Data Protection attribute; locked-device protection and interrupted real sharing have not been observed. - Opt-in UI: configured-domain CI selection passes (57 tests); default selection passes (7 tests, 10 hosted-only skips); URL-only plus whitespace/empty domains passes (6 tests, 9 hosted-only skips). Changed Dart files analyze cleanly. Independent mutations that unconditionally initialize the coordinator in the app gate, welcome entry, or link form fail the default journey; clean/restored controls pass. - Native welcome screens exercised on iPhone 18 Pro / iOS 27 simulator in default and configured builds: default exposes community link / QR / pairing code only; configured build additionally exposes Builderlab connection and community creation. No live hosted login was exercised in this check. - Delivery at `e48fe73a9`: all mandatory push hooks passed (full mobile analysis/tests, Rust tests, desktop-native checks, branch and file-size checks). GitHub checks had not yet populated at the immediate post-push snapshot. ## Review disposition | Feedback | Disposition | | --- | --- | | Explicit self-hosted entry under unreadable inventory, duplicate invite dispatch, reconnect cross-account binding ([entry](#8375 (comment)), [queue](#8375 (comment)), [reconnect](#8375 (comment))) | Repaired at `66a12ac92`; evidence above. Reconnect refuses unproven ownership rather than silently establishing a binding. | | Incomplete Android identity inventory, stranded deep-link queue, transient HTTP retry classification ([review](#8375 (review))) | All three repaired in `d3cc0003f`; focused journeys and isolated mutation evidence above. | | Account cross-link, incomplete recovery inventory, committed invite checkpoint, pending local key retirement/replacement | Repaired in the preceding commits; journey and mutation evidence above. | | iOS interrupted key export ([review](#8375 (review))) | Native cleanup plus complete protection at creation implemented. Physical-device lock and real interrupted sharing acceptance remains pending. | | Trickle responses bypass idle timeout; unrelated NIP-FA edit ([review](#8375 (review))) | Total request deadline/abort implemented; spec edit removed. | | Production domains rejected | Ordinary entry now needs no Builderlab configuration. Opt-in account-required domains must still use supported community mappings. | | Lost Android Keystore recovery | Backup exclusions prevent the reviewed stale-restore scenario; genuine key loss still has no in-app recovery/reset and remains deferred. | | Native secp256k1 dependency question | Obsolete against the current base: upstream C integration landed in #8398; no package diff remains here. | | Operator membership endpoint contract | Documentation now states the operator chooses the pubkey; no end-user session binding is implied. Additional handler-level coverage is optional follow-up. | | Optional Android partial document cleanup/activity retention; local work after backup cancellation | Follow-up hardening, not claimed implemented. Cancellation prevents remote backup upload. | | Semgrep crypto inventory notices | Informational inventory, not demonstrated defects. | ## Remaining draft gates Native QR/browser-return acceptance remains unverified for this revision. Optional Builderlab onboarding still needs backend backup-status and joined-community routes, recovery policy/configuration, and real backup/recovery/reconnect acceptance. The empty-domain build removes these services as prerequisites for ordinary pairing; it does not make the optional hosted flows backend-ready. Human acceptance and current CI are still required before merge. Review dispositions retained: production auth-domain configuration must use supported community mappings; enabling `builderlab.xyz` does not add support for `buzz.block.builderlab.xyz`. Recovery after genuinely losing an Android Keystore key remains a follow-up, not a newly implemented capability. Human acceptance steps: build once without `BUZZ_AUTH_DOMAINS` (including with a previously saved account) and confirm no Builderlab controls/restoration while ordinary link and QR/code entry work. Build with supported domains and confirm connection/creation appear; exercise browser return and live backup/recovery/reconnect. On physical iOS, exercise export and interrupted sharing/locked-device protection. Record results before marking review complete. --------- Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@wes.communities.public.builderlabstaging.xyz>
1 parent cc6336d commit b6aa553

128 files changed

Lines changed: 13893 additions & 241 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/_ci-clients.yml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,21 @@ jobs:
135135
- name: Test
136136
if: matrix.lane == 'test'
137137
run: cd mobile && flutter test --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example --total-shards=3 --shard-index=${{ matrix.shard }}
138+
- name: Test configured authentication domains
139+
if: matrix.lane == 'checks'
140+
run: >-
141+
cd mobile && flutter test
142+
--dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example
143+
--dart-define=BUZZ_AUTH_DOMAINS=buzz.xyz,builderlab.xyz,builderlabstaging.xyz
144+
test/shared/auth/community_entry_requirements_test.dart
145+
test/features/invites/invite_join_provider_test.dart
146+
test/features/onboarding/onboarding_entry_routes_test.dart
147+
test/shared/hosted/hosted_environment_test.dart
148+
test/shared/hosted/self_hosted_entry_test.dart
149+
test/features/onboarding/hosted_app_gate_environment_test.dart
150+
test/features/onboarding/hosted_journeys_test.dart
151+
test/features/onboarding/hosted_communities_test.dart
152+
test/features/pairing/pairing_hosted_handoff_test.dart
138153
- name: Test mobile without push configuration
139154
if: matrix.lane == 'checks'
140155
run: cd mobile && flutter test test/shared/push/push_unconfigured_build_test.dart
@@ -212,6 +227,7 @@ jobs:
212227
-configuration Debug -destination "platform=iOS Simulator,id=$device" \
213228
-parallel-testing-enabled NO \
214229
-only-testing:RunnerTests/BuzzPushNavigationBridgeTests \
230+
-only-testing:RunnerTests/IdentityFilePluginTests \
215231
CODE_SIGNING_ALLOWED=NO test
216232
- name: Build complete unsigned iOS release
217233
if: matrix.lane == 'release'

‎crates/buzz-db/src/store/community.rs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,40 @@ impl Db {
291291
.transpose()
292292
}
293293

294+
/// Active communities the identity has joined, regardless of role.
295+
/// Operator-plane callers must authenticate before exposing this cross-tenant read.
296+
#[datastore_span(name = "list_communities_joined_by", system = "postgresql")]
297+
pub async fn list_communities_joined_by(&self, pubkey: &str) -> Result<Vec<CommunityRecord>> {
298+
let mut connection = crate::observability::acquire_writer(
299+
&self.pool,
300+
crate::observability::WriterOperation::Authorization,
301+
)
302+
.await?;
303+
let rows = sqlx::query(
304+
r#"
305+
SELECT c.id, c.host FROM communities c
306+
JOIN relay_members rm ON rm.community_id = c.id
307+
WHERE rm.pubkey = $1 AND c.archived_at IS NULL
308+
AND NOT EXISTS (
309+
SELECT 1 FROM community_deletion_requests request
310+
WHERE request.community_id = c.id AND request.stage <> 'aborted'
311+
)
312+
ORDER BY c.created_at ASC, c.host ASC
313+
"#,
314+
)
315+
.bind(pubkey.to_ascii_lowercase())
316+
.fetch_all(&mut *connection)
317+
.await?;
318+
rows.into_iter()
319+
.map(|row| {
320+
Ok(CommunityRecord {
321+
id: CommunityId::from_uuid(row.try_get("id")?),
322+
host: row.try_get("host")?,
323+
})
324+
})
325+
.collect()
326+
}
327+
294328
/// Lists communities where `owner_pubkey` currently holds the `owner` role.
295329
///
296330
/// This is an operator-plane helper, not a tenant-scoped data-plane read:
@@ -1587,6 +1621,28 @@ mod postgres_tests {
15871621
crate::relay_members::max_communities_per_owner()
15881622
);
15891623
assert!(owned.can_create);
1624+
1625+
// Discovery includes every membership role, while management remains owner-only.
1626+
let community_d = CommunityId::from_uuid(make_community(&db.pool).await);
1627+
db.add_relay_member(community_d, owner, "member", None)
1628+
.await
1629+
.expect("member D");
1630+
let joined = db
1631+
.list_communities_joined_by(&owner.to_uppercase())
1632+
.await
1633+
.expect("joined");
1634+
let ids: Vec<_> = joined.iter().map(|row| row.id).collect();
1635+
assert_eq!(ids.len(), 3);
1636+
assert!(ids.contains(&community_a));
1637+
assert!(ids.contains(&community_c));
1638+
assert!(ids.contains(&community_d));
1639+
assert!(!ids.contains(&community_b));
1640+
sqlx::query("UPDATE communities SET archived_at = NOW() WHERE id = $1")
1641+
.bind(community_d.as_uuid())
1642+
.execute(&db.pool)
1643+
.await
1644+
.unwrap();
1645+
assert_eq!(db.list_communities_joined_by(owner).await.unwrap().len(), 2);
15901646
}
15911647

15921648
#[tokio::test]

‎crates/buzz-relay/src/api/operator.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ pub struct ListCommunitiesQuery {
4141
owner_pubkey: String,
4242
}
4343

44+
/// Query parameters for joined-community discovery by an authenticated operator.
45+
#[derive(Debug, Deserialize)]
46+
pub struct JoinedCommunitiesQuery {
47+
member_pubkey: String,
48+
}
49+
4450
/// Query parameters for `GET /operator/communities/availability`.
4551
#[derive(Debug, Deserialize)]
4652
pub struct CommunityAvailabilityQuery {
@@ -688,6 +694,42 @@ pub async fn delete_community(
688694
))
689695
}
690696

697+
/// Return active memberships for an operator-supplied pubkey.
698+
/// The operator is trusted to select the identity; this route does not bind it to a user session.
699+
pub async fn list_joined_communities(
700+
State(state): State<Arc<AppState>>,
701+
headers: HeaderMap,
702+
RawQuery(raw_query): RawQuery,
703+
Query(query): Query<JoinedCommunitiesQuery>,
704+
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
705+
authorize_operator_request(
706+
&state,
707+
&headers,
708+
"GET",
709+
"/operator/communities/joined",
710+
raw_query.as_deref(),
711+
None,
712+
)
713+
.await?;
714+
let pubkey = validate_pubkey_hex(&query.member_pubkey).ok_or_else(|| {
715+
api_error(
716+
StatusCode::BAD_REQUEST,
717+
"invalid member_pubkey: expected 64-char hex pubkey",
718+
)
719+
})?;
720+
let communities = state
721+
.db
722+
.list_communities_joined_by(&pubkey)
723+
.await
724+
.map_err(|e| internal_error(&format!("list joined communities: {e}")))?;
725+
Ok(Json(serde_json::json!({
726+
"member_pubkey": pubkey,
727+
"communities": communities.into_iter().map(|row| serde_json::json!({
728+
"community_id": row.id.to_string(), "host": row.host,
729+
})).collect::<Vec<_>>()
730+
})))
731+
}
732+
691733
/// List communities where a pubkey currently holds the `owner` role.
692734
pub async fn list_owned_communities(
693735
State(state): State<Arc<AppState>>,

‎crates/buzz-relay/src/router.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,10 @@ pub fn build_router(state: Arc<AppState>) -> Router {
349349
"/operator/communities",
350350
get(api::operator::list_owned_communities).post(api::operator::provision_community),
351351
)
352+
.route(
353+
"/operator/communities/joined",
354+
get(api::operator::list_joined_communities),
355+
)
352356
.route(
353357
"/operator/listener/pubkeys",
354358
post(api::operator::register_listener_pubkeys)

‎docs/admin/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ RELAY_OPERATOR_PUBKEYS=<64-char hex pubkey>[,<64-char hex pubkey>...]
4848
with a `WARN` and provisioning requests fail closed at request time until the
4949
origin is set — the admin console is unaffected.
5050

51+
`GET /operator/communities/joined?member_pubkey=<64-char hex pubkey>` returns
52+
active memberships for an operator-selected identity, excluding archived and
53+
deleting communities. Like the provisioning routes, it requires the configured
54+
operator origin and an allowlisted NIP-98 signature over the full request URL.
55+
The relay authenticates the operator, not a Builderlab end-user session; the
56+
operator is responsible for choosing the appropriate member pubkey.
57+
5158
#### Auto-discovery via NIP-11
5259

5360
When `BUZZ_ADMIN_HOST` is set, the relay advertises the admin API origin in its

‎mobile/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,36 @@ Flutter mobile client for Buzz.
55
See [VISION_MOBILE.md](../VISION_MOBILE.md) for intended behavior and
66
architecture.
77

8+
## Optional Builderlab login
9+
10+
`BUZZ_AUTH_DOMAINS` is a comma-separated build-time environment setting, passed
11+
with Flutter's `--dart-define` (shell environment variables alone are not read):
12+
13+
```bash
14+
flutter run --dart-define=BUZZ_AUTH_DOMAINS=communities.buzz.xyz,communities.public.builderlabstaging.xyz
15+
```
16+
17+
Unset or empty means **Builderlab features are disabled**: no account login,
18+
community creation, backup/recovery UI, reconnect prompts, or background account
19+
restoration. QR/code pairing, community links and invites use Nostr-only entry.
20+
Saved account keys and sessions are retained for a later enabled build.
21+
22+
A nonempty list enables Builderlab features and requires account setup only for
23+
matching domains. Those features need their backend endpoints. Normal relay key
24+
authentication remains in place. `BUZZ_BUILDERLAB_URL` selects the backend; setting
25+
it alone does not enable Builderlab features.
26+
27+
Entries match the domain itself and its subdomains, case-insensitively. Use DNS
28+
names, not URLs or wildcards. The list does not add trusted account servers:
29+
configured domains outside the supported Builderlab realm cannot use hosted
30+
setup. `BUZZ_BUILDERLAB_URL` still selects the trusted account environment.
31+
32+
## Hosted relay authentication
33+
34+
`--dart-define=BUZZ_HOSTED_RELAY_AUTH=true` enables Builderlab relay assertions
35+
and reconnect sign-in **only for `BUZZ_AUTH_DOMAINS` matches**. It defaults off: configure backend assertion issuance
36+
before enabling mobile authentication, and enable relay enforcement last.
37+
838
## Setup
939

1040
Use the Flutter SDK pinned by the repository. Activate Hermit from the repo

‎mobile/android/app/src/main/AndroidManifest.xml‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
<application
1919
android:label="@string/app_name"
2020
android:name="${applicationName}"
21-
android:icon="@mipmap/ic_launcher">
21+
android:icon="@mipmap/ic_launcher"
22+
android:fullBackupContent="@xml/backup_rules"
23+
android:dataExtractionRules="@xml/data_extraction_rules"
24+
tools:targetApi="31">
2225
<activity
2326
android:name=".MainActivity"
2427
android:exported="true"
@@ -47,6 +50,13 @@
4750
<category android:name="android.intent.category.BROWSABLE"/>
4851
<data android:scheme="buzz"/>
4952
</intent-filter>
53+
<!-- Auth callbacks have an independent Dart consumer and PKCE state. -->
54+
<intent-filter>
55+
<action android:name="android.intent.action.VIEW"/>
56+
<category android:name="android.intent.category.DEFAULT"/>
57+
<category android:name="android.intent.category.BROWSABLE"/>
58+
<data android:scheme="xyz.block.buzz.mobile"/>
59+
</intent-filter>
5060
<!-- Disable Flutter's built-in deeplink handler; app_links owns
5161
incoming URLs so they can be routed with app state in Dart. -->
5262
<meta-data
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
package xyz.block.buzz.mobile
2+
3+
import java.math.BigInteger
4+
import java.security.AlgorithmParameters
5+
import java.security.KeyFactory
6+
import java.security.KeyPair
7+
import java.security.KeyPairGenerator
8+
import java.security.interfaces.ECPublicKey
9+
import java.security.spec.ECGenParameterSpec
10+
import java.security.spec.ECParameterSpec
11+
import java.security.spec.ECPoint
12+
import java.security.spec.ECPublicKeySpec
13+
import javax.crypto.Cipher
14+
import javax.crypto.KeyAgreement
15+
import javax.crypto.Mac
16+
import javax.crypto.spec.GCMParameterSpec
17+
import javax.crypto.spec.SecretKeySpec
18+
19+
/** RFC 9180 base mode, DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, AES-256-GCM.
20+
* Enrollment and AAD must come from the authenticated hosted coordinator.
21+
* Only JCA platform primitives are used; this is a single-message sender.
22+
*/
23+
internal object HostedHpkeBackup {
24+
private val kemSuite = "KEM".toByteArray() + byteArrayOf(0, 16)
25+
private val suite = "HPKE".toByteArray() + byteArrayOf(0, 16, 0, 1, 0, 2)
26+
private val version = "HPKE-v1".toByteArray()
27+
private val info = "buzz/nsec-backup/v1".toByteArray()
28+
private val curve: ECParameterSpec
29+
get() = AlgorithmParameters.getInstance("EC").apply {
30+
init(ECGenParameterSpec("secp256r1"))
31+
}.getParameterSpec(ECParameterSpec::class.java)
32+
33+
fun seal(recipient: ByteArray, plaintext: ByteArray, aad: ByteArray): Map<String, ByteArray> {
34+
require(plaintext.size == 32 && aad.isNotEmpty())
35+
val ephemeral = KeyPairGenerator.getInstance("EC").apply {
36+
initialize(ECGenParameterSpec("secp256r1"))
37+
}.generateKeyPair()
38+
return sealBase(recipient, plaintext, aad, info, ephemeral)
39+
}
40+
41+
// Internal seam for the RFC known-answer vector. The channel only calls seal,
42+
// which fixes the protocol info and always generates a fresh ephemeral key.
43+
internal fun sealBase(
44+
recipient: ByteArray,
45+
plaintext: ByteArray,
46+
aad: ByteArray,
47+
info: ByteArray,
48+
ephemeral: KeyPair,
49+
): Map<String, ByteArray> {
50+
val publicKey = decodePublicKey(recipient)
51+
val enc = encodePublicKey(ephemeral.public as ECPublicKey)
52+
val dh = KeyAgreement.getInstance("ECDH").run {
53+
init(ephemeral.private)
54+
doPhase(publicKey, true)
55+
generateSecret()
56+
}
57+
var shared = ByteArray(0)
58+
var secret = ByteArray(0)
59+
var key = ByteArray(0)
60+
try {
61+
val eae = extract(kemSuite, ByteArray(0), "eae_prk", dh)
62+
try {
63+
shared = expand(kemSuite, eae, "shared_secret", enc + recipient, 32)
64+
} finally {
65+
eae.fill(0)
66+
}
67+
val context = byteArrayOf(0) +
68+
extract(suite, ByteArray(0), "psk_id_hash", ByteArray(0)) +
69+
extract(suite, ByteArray(0), "info_hash", info)
70+
secret = extract(suite, shared, "secret", ByteArray(0))
71+
key = expand(suite, secret, "key", context, 32)
72+
val nonce = expand(suite, secret, "base_nonce", context, 12)
73+
// Sequence number is zero: the first and only seal in this context.
74+
val ciphertext = Cipher.getInstance("AES/GCM/NoPadding").run {
75+
init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
76+
updateAAD(aad)
77+
doFinal(plaintext)
78+
}
79+
return mapOf("enc" to enc, "ciphertext" to ciphertext)
80+
} finally {
81+
dh.fill(0)
82+
shared.fill(0)
83+
secret.fill(0)
84+
key.fill(0)
85+
}
86+
}
87+
88+
internal fun decodePublicKey(encoded: ByteArray): ECPublicKey {
89+
require(encoded.size == 65 && encoded[0] == 4.toByte())
90+
val parameters = curve
91+
val x = BigInteger(1, encoded.copyOfRange(1, 33))
92+
val y = BigInteger(1, encoded.copyOfRange(33, 65))
93+
val p = (parameters.curve.field as java.security.spec.ECFieldFp).p
94+
// Validate the SEC1 point ourselves: provider validation differs by API.
95+
require(x < p && y < p)
96+
require(y.multiply(y).mod(p) ==
97+
x.multiply(x).multiply(x).add(parameters.curve.a.multiply(x))
98+
.add(parameters.curve.b).mod(p))
99+
return KeyFactory.getInstance("EC").generatePublic(
100+
ECPublicKeySpec(ECPoint(x, y), parameters),
101+
) as ECPublicKey
102+
}
103+
104+
private fun encodePublicKey(key: ECPublicKey): ByteArray {
105+
fun coordinate(value: BigInteger): ByteArray {
106+
val bytes = value.toByteArray()
107+
return ByteArray(32).also {
108+
val length = minOf(bytes.size, 32)
109+
bytes.copyInto(it, 32 - length, bytes.size - length)
110+
}
111+
}
112+
return byteArrayOf(4) + coordinate(key.w.affineX) + coordinate(key.w.affineY)
113+
}
114+
115+
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
116+
Mac.getInstance("HmacSHA256").run {
117+
init(SecretKeySpec(if (key.isEmpty()) ByteArray(32) else key, "HmacSHA256"))
118+
doFinal(data)
119+
}
120+
121+
private fun extract(suite: ByteArray, salt: ByteArray, label: String, input: ByteArray): ByteArray {
122+
val labeledInput = version + suite + label.toByteArray() + input
123+
return try { hmac(salt, labeledInput) } finally { labeledInput.fill(0) }
124+
}
125+
126+
private fun expand(
127+
suite: ByteArray, prk: ByteArray, label: String, context: ByteArray, length: Int,
128+
): ByteArray {
129+
// Every output in this fixed suite is at most one SHA-256 block.
130+
require(length in 1..32)
131+
val labeledInfo = byteArrayOf(0, length.toByte()) + version + suite +
132+
label.toByteArray() + context
133+
val block = hmac(prk, labeledInfo + byteArrayOf(1))
134+
return try { block.copyOf(length) } finally { block.fill(0) }
135+
}
136+
}

0 commit comments

Comments
 (0)