Skip to content

Commit b87b0f8

Browse files
kalvinnchaunpub1c4alndp82zyt9veaklm5d965quss79vlhk9awv7qu5erwhmf42qqlvc25cnpub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xcnpub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7
authored
feat(invites): add use-limited invite links (#3141)
## Summary - add database-backed v2 invite links with optional maximum-use limits and atomic final-slot redemption - preserve v1 invite compatibility while adding exhausted/expired/invalid client handling across desktop, web, and mobile - emit structured claim-outcome logs with community, invite ID, outcome, maximum uses, and post-claim count ## Verification - `cargo fmt --all -- --check` - `cargo test -p buzz-db` (85 passed, 134 Postgres-dependent ignored) - `cargo clippy -p buzz-db --all-targets -- -D warnings` - desktop `npm run typecheck` - push hook: desktop checks/tests, desktop Tauri tests, Rust tests, and branch-skew passed - Postgres integration tests were previously reviewed green at the pre-rebase tree; local rerun on this session was unavailable because Postgres/Docker were not running - mobile push-hook check could not start because Flutter is unavailable locally --------- Signed-off-by: Kalvin Chau <[email protected]> Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz> Co-authored-by: npub1c4alndp82zyt9veaklm5d965quss79vlhk9awv7qu5erwhmf42qqlvc25c <c57bf9b4275088b2b33db7f746975407210f159fbd8bd733c0e532375f69aa80@buzz.block.builderlab.xyz> Co-authored-by: npub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xc <5288f082d91aff2de5bc8be23fbfa01ca2e3859cac57a91b7a3fa9f12349505c@buzz.block.builderlab.xyz> Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
1 parent 26fa4b9 commit b87b0f8

24 files changed

Lines changed: 1732 additions & 35 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ jobs:
340340
cargo build --profile ci -p buzz-relay -p git-credential-nostr
341341
cargo nextest archive \
342342
--cargo-profile ci \
343+
-p buzz-db \
343344
-p buzz-relay \
344345
-p buzz-test-client \
345346
--lib \
@@ -671,11 +672,11 @@ jobs:
671672
done
672673
cat /tmp/buzz-relay.log
673674
exit 1
674-
- name: Invite claim security tests
675+
- name: Invite security tests
675676
run: |
676677
cargo nextest run \
677678
--archive-file target/ci/backend-integration-tests.tar.zst \
678-
-E 'package(buzz-relay) and test(claim_)' \
679+
-E '(package(buzz-db) and test(/relay_invite::tests/)) or (package(buzz-relay) and test(/api::invites::tests/))' \
679680
--run-ignored ignored-only
680681
env:
681682
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ reqwest = { version = "0.13", features = ["json", "rustls"], default-features =
9696
sha2 = "0.11"
9797
hex = "0.4"
9898
hmac = "0.13"
99+
base64 = "0.22"
99100

100101
# Randomness
101102
rand = "0.10"

‎crates/buzz-core/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ description = "Core types, event verification, and filter matching for Buzz"
1111
test-utils = []
1212

1313
[dependencies]
14+
base64 = { workspace = true }
1415
nostr = { workspace = true }
1516
serde = { workspace = true }
1617
serde_json = { workspace = true }

‎crates/buzz-core/src/invite.rs‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
//! Shared pure contracts for relay invite links.
2+
//!
3+
//! The relay transport and database persistence layers both depend on
4+
//! `buzz-core`. Protocol constants and deterministic v2 code operations live
5+
//! here so neither layer becomes the accidental source of truth.
6+
7+
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
8+
use base64::Engine as _;
9+
use sha2::{Digest, Sha256};
10+
11+
/// Minimum invite lifetime accepted by the mint API: 60 seconds.
12+
pub const MIN_INVITE_TTL_SECS: u64 = 60;
13+
14+
/// Default invite lifetime when the mint request omits `ttl_secs`: 72 hours.
15+
pub const DEFAULT_INVITE_TTL_SECS: u64 = 72 * 60 * 60;
16+
17+
/// Maximum invite lifetime accepted by the mint API: 30 days.
18+
pub const MAX_INVITE_TTL_SECS: u64 = 30 * 24 * 60 * 60;
19+
20+
/// Maximum supported `max_uses` value. Matches the database constraint.
21+
pub const MAX_INVITE_USES: i32 = 10_000;
22+
23+
/// Prefix that distinguishes v2 opaque database-backed codes from v1 tokens.
24+
pub const V2_PREFIX: &str = "v2.";
25+
26+
/// Number of random bytes encoded in a v2 invite code.
27+
pub const V2_SECRET_LEN: usize = 32;
28+
29+
/// A malformed v2 opaque invite code.
30+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31+
pub struct InvalidV2InviteCode;
32+
33+
/// Build a canonical v2 code from its random secret.
34+
pub fn encode_v2_code(secret: &[u8; V2_SECRET_LEN]) -> String {
35+
format!("{V2_PREFIX}{}", URL_SAFE_NO_PAD.encode(secret))
36+
}
37+
38+
/// Validate the canonical v2 opaque-code shape without consulting storage.
39+
///
40+
/// A valid code is exactly `v2.` followed by the unpadded base64url encoding
41+
/// of a 32-byte secret. The decode/re-encode comparison rejects aliases such
42+
/// as padded or otherwise non-canonical encodings.
43+
pub fn validate_v2_code(code: &str) -> Result<(), InvalidV2InviteCode> {
44+
let encoded = code.strip_prefix(V2_PREFIX).ok_or(InvalidV2InviteCode)?;
45+
let secret = URL_SAFE_NO_PAD
46+
.decode(encoded)
47+
.map_err(|_| InvalidV2InviteCode)?;
48+
if secret.len() != V2_SECRET_LEN || URL_SAFE_NO_PAD.encode(&secret) != encoded {
49+
return Err(InvalidV2InviteCode);
50+
}
51+
Ok(())
52+
}
53+
54+
/// Hash the complete v2 code to the digest persisted by the database.
55+
pub fn hash_v2_code(code: &str) -> [u8; 32] {
56+
Sha256::digest(code.as_bytes()).into()
57+
}
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn v2_code_round_trip_is_canonical() {
65+
let secret = [7_u8; V2_SECRET_LEN];
66+
let code = encode_v2_code(&secret);
67+
68+
assert_eq!(validate_v2_code(&code), Ok(()));
69+
assert_eq!(
70+
code,
71+
format!("{V2_PREFIX}{}", URL_SAFE_NO_PAD.encode(secret))
72+
);
73+
}
74+
75+
#[test]
76+
fn v2_validation_rejects_malformed_and_noncanonical_codes() {
77+
let valid = encode_v2_code(&[7_u8; V2_SECRET_LEN]);
78+
let short = format!(
79+
"{V2_PREFIX}{}",
80+
URL_SAFE_NO_PAD.encode([7_u8; V2_SECRET_LEN - 1])
81+
);
82+
83+
for malformed in [
84+
"v2.",
85+
"v2.not-base64!",
86+
short.as_str(),
87+
&format!("{valid}="),
88+
] {
89+
assert_eq!(
90+
validate_v2_code(malformed),
91+
Err(InvalidV2InviteCode),
92+
"accepted malformed v2 code: {malformed}"
93+
);
94+
}
95+
}
96+
97+
#[test]
98+
fn v2_hash_covers_the_complete_code() {
99+
let code = encode_v2_code(&[7_u8; V2_SECRET_LEN]);
100+
101+
let expected: [u8; 32] = Sha256::digest(code.as_bytes()).into();
102+
103+
assert_eq!(hash_v2_code(&code), expected);
104+
assert_ne!(
105+
hash_v2_code(&code),
106+
hash_v2_code(code.trim_start_matches(V2_PREFIX))
107+
);
108+
}
109+
}

‎crates/buzz-core/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ pub mod event;
2020
pub mod filter;
2121
/// Git permission types — ref patterns, protection rules, policy evaluation.
2222
pub mod git_perms;
23+
/// Shared invite-link contract constants.
24+
pub mod invite;
2325
/// Buzz kind number registry — custom event type constants.
2426
pub mod kind;
2527
/// Network utilities — SSRF-safe IP classification.

‎crates/buzz-db/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ sha2 = { workspace = true }
2020
tracing = { workspace = true }
2121
thiserror = { workspace = true }
2222
nostr = { workspace = true }
23+
rand = { workspace = true }
2324

2425
[dev-dependencies]
2526
tokio = { workspace = true }

‎crates/buzz-db/src/lib.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ pub mod product_feedback;
3939
pub mod push;
4040
/// Reaction persistence.
4141
pub mod reaction;
42+
/// Use-limited relay invite persistence (v2 opaque tokens).
43+
pub mod relay_invite;
4244
/// Relay-level membership persistence (NIP-43).
4345
pub mod relay_members;
4446
/// Replica freshness fence for keyset-cursor read routing.
@@ -3045,6 +3047,51 @@ impl Db {
30453047
relay_members::backfill_from_allowlist(&self.pool, community).await
30463048
}
30473049

3050+
/// Mints a v2 use-limited relay invite. The plaintext code is returned
3051+
/// exactly once; only its SHA-256 hash is persisted.
3052+
///
3053+
/// `max_uses` is `None` for unlimited or `Some(1..=10000)`.
3054+
/// `ttl_secs` must be in the shared invite lifetime range.
3055+
pub async fn mint_relay_invite(
3056+
&self,
3057+
community: CommunityId,
3058+
created_by: &str,
3059+
ttl_secs: u64,
3060+
max_uses: Option<i32>,
3061+
) -> Result<relay_invite::MintedInvite> {
3062+
relay_invite::mint_relay_invite(&self.pool, community, created_by, ttl_secs, max_uses).await
3063+
}
3064+
3065+
/// Delete one bounded batch of invites expired before `cutoff`.
3066+
pub async fn reap_expired_relay_invites(
3067+
&self,
3068+
cutoff: chrono::DateTime<chrono::Utc>,
3069+
) -> Result<u64> {
3070+
relay_invite::reap_expired_relay_invites(&self.pool, cutoff).await
3071+
}
3072+
3073+
/// Atomically claims a v2 relay invite. The full redemption (membership
3074+
/// insert, policy evidence, use_count increment) runs in one PostgreSQL
3075+
/// transaction with `FOR UPDATE` on the invite row.
3076+
///
3077+
/// `token_hash` is the SHA-256 of the presented v2 code (32 bytes).
3078+
pub async fn claim_relay_invite(
3079+
&self,
3080+
community: CommunityId,
3081+
token_hash: &[u8; 32],
3082+
claimer_pubkey: &str,
3083+
policy_version: Option<&str>,
3084+
) -> Result<relay_invite::ClaimOutcome> {
3085+
relay_invite::claim_relay_invite(
3086+
&self.pool,
3087+
community,
3088+
token_hash,
3089+
claimer_pubkey,
3090+
policy_version,
3091+
)
3092+
.await
3093+
}
3094+
30483095
/// Sidecar an accepted product-feedback event, idempotent by event id.
30493096
pub async fn insert_product_feedback(
30503097
&self,

‎crates/buzz-db/src/migration.rs‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ mod tests {
560560
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
561561
migrations.sort_by_key(|migration| migration.version);
562562

563-
assert_eq!(migrations.len(), 24);
563+
assert_eq!(migrations.len(), 25);
564564
assert_eq!(migrations[0].version, 1);
565565
assert_eq!(&*migrations[0].description, "initial schema");
566566
assert!(migrations[0]
@@ -879,6 +879,31 @@ mod tests {
879879
.to_lowercase()
880880
.contains("for update"));
881881
assert!(ttl_shared.contains("NEW.kind <> 9007"));
882+
883+
// Use-limited invite links: durable relay_invites table stores only
884+
// the SHA-256 of an opaque v2 code, scoped by community_id. Never
885+
// listed in _operator_global_tables — it is community-scoped.
886+
assert_eq!(migrations[24].version, 25);
887+
let relay_invites = migrations[24].sql.as_str();
888+
assert!(relay_invites.contains("CREATE TABLE relay_invites"));
889+
assert!(relay_invites
890+
.contains("token_hash BYTEA NOT NULL CHECK (length(token_hash) = 32)"));
891+
assert!(relay_invites.contains("PRIMARY KEY (community_id, id)"));
892+
assert!(relay_invites.contains("UNIQUE (community_id, token_hash)"));
893+
assert!(
894+
relay_invites.contains("max_uses INTEGER CHECK (max_uses BETWEEN 1 AND 10000)")
895+
);
896+
assert!(relay_invites.contains("CHECK (max_uses IS NULL OR use_count <= max_uses)"));
897+
assert!(relay_invites.contains("role = 'member'"));
898+
assert!(relay_invites
899+
.contains("CREATE INDEX relay_invites_expires_at_idx ON relay_invites (expires_at)"));
900+
assert!(!relay_invites.contains("_operator_global_tables"));
901+
902+
let desired_schema = include_str!("../../../schema/schema.sql");
903+
assert!(
904+
desired_schema.contains("CREATE TABLE join_policy_acceptances"),
905+
"desired-state schema must include join-policy evidence used by invite claims",
906+
);
882907
}
883908

884909
#[test]
@@ -1121,7 +1146,7 @@ mod tests {
11211146
run_migrations(&pool)
11221147
.await
11231148
.expect("retry succeeds after operator repair");
1124-
assert_eq!(applied_versions(&pool).await.last().copied(), Some(24));
1149+
assert_eq!(applied_versions(&pool).await.last().copied(), Some(25));
11251150
}
11261151

11271152
#[tokio::test]

0 commit comments

Comments
 (0)