1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use std::sync::Arc;
use pubky_common::auth::{
AuthToken,
grant::GrantClaims,
jws::{ClientId, GRANT_JWS_TYP, GrantId},
};
use pubky_common::crypto::Keypair;
use reqwest::Method;
use url::Url;
use super::PubkySigner;
use crate::{
Capabilities, Capability, PubkySession, PublicKey, Result,
actors::auth::{
cookie::CookieCredential,
grant::constants::DEFAULT_GRANT_LIFETIME_SECS,
grant::grant_exchange::{credential_from_grant_exchange, signup_account_from_grant},
grant::pop_signer::GrantPopSigner,
},
cross_log,
util::check_http_status,
};
const SIGNUP_CLIENT_ID: &str = "pubky.signup";
const SIGNUP_GRANT_LIFETIME_SECS: u64 = 5 * 60;
#[derive(Debug, Clone, Copy)]
enum PublishMode {
Background,
Blocking,
}
impl PubkySigner {
/// Create an account on a homeserver.
///
/// This is a **one-time** operation. After signing up, call
/// [`signin`](Self::signin) to obtain a [`PubkySession`] for reading and
/// writing data.
///
/// Side effects:
/// - Publishes the `_pubky` PKARR record pointing to `homeserver` (force mode),
/// so other users can discover this identity.
///
/// # Arguments
/// - `homeserver` — public key of the homeserver to register on.
/// - `signup_token` — optional invite token required by some homeservers.
///
/// # Errors
/// - Returns [`crate::errors::Error::Parse`] if the homeserver URL cannot be constructed.
/// - Propagates transport failures while creating the account or publishing the homeserver record.
/// - Propagates validation errors from the session hydration step.
pub async fn signup(&self, homeserver: &PublicKey, signup_token: Option<&str>) -> Result<()> {
cross_log!(info, "Signing up new account on homeserver {}", homeserver);
let client_keypair = Keypair::random();
let (grant_jws, grant_claims) = self.signup_grant(&client_keypair)?;
let client_signer = GrantPopSigner::local(client_keypair);
signup_account_from_grant(
&self.client,
&grant_jws,
&grant_claims,
&client_signer,
homeserver,
signup_token,
)
.await?;
self.publish_signup_homeserver(homeserver).await?;
Ok(())
}
/// Sign in to the user's homeserver and return a [`PubkySession`].
///
/// Locally signs a root-capability grant and exchanges it for a
/// session at the homeserver. If the user's PKDNS record is stale,
/// it is republished **in the background** so this call returns fast.
///
/// # Arguments
/// - `client_id` — a [`ClientId`] identifying your application (e.g.
/// `ClientId::new("my.app").unwrap()`). The homeserver records which
/// app holds each grant.
///
/// # Example
/// ```no_run
/// # use pubky::{Pubky, Keypair, ClientId};
/// # async fn run() -> pubky::Result<()> {
/// let signer = Pubky::new()?.signer(Keypair::random());
/// let session = signer.signin(ClientId::new("my.app").unwrap()).await?;
/// println!("Signed in as {}", session.public_key());
/// # Ok(()) }
/// ```
///
/// # Errors
/// - Propagates transport failures during the session exchange.
/// - Propagates validation errors from the session exchange or PKDNS publishing.
pub async fn signin(&self, client_id: ClientId) -> Result<PubkySession> {
self.signin_with_publish(client_id, PublishMode::Background)
.await
}
/// Sign in, **blocking** until the PKDNS record is republished (if stale).
///
/// Unlike [`Self::signin`], this variant waits for the homeserver PKDNS
/// record to be fully published before returning. This gives the highest
/// guarantee of discoverability from the DHT and Pkarr relays, at the
/// cost of being slower (~3–5 seconds).
///
/// Use this when the signer's identity must be immediately discoverable
/// by other users (e.g. first-time setup). For interactive apps, prefer
/// [`Self::signin`] which publishes in the background.
///
/// # Errors
/// - Propagates transport failures during the session exchange.
/// - Propagates validation errors from the session exchange or PKDNS publishing.
pub async fn signin_blocking(&self, client_id: ClientId) -> Result<PubkySession> {
self.signin_with_publish(client_id, PublishMode::Blocking)
.await
}
/// Internal helper to sign in, then optionally refresh `_pubky` record.
async fn signin_with_publish(
&self,
client_id: ClientId,
mode: PublishMode,
) -> Result<PubkySession> {
let user = self.keypair.public_key();
let homeserver = self.pkdns().require_homeserver_of(&user).await?;
let client_keypair = Keypair::random();
let (grant_jws, grant_claims) = self.session_grant(client_id, &client_keypair);
let client_signer = GrantPopSigner::local(client_keypair);
let credential = credential_from_grant_exchange(
&self.client,
grant_jws,
grant_claims,
client_signer,
homeserver,
)
.await?;
let session = PubkySession::from_grant_credential(self.client.clone(), credential);
cross_log!(
info,
"Signin completed for {}; mode {:?}",
self.keypair.public_key(),
mode
);
self.publish_after_signin(mode).await?;
Ok(session)
}
/// Legacy cookie signup. Prefer [`Self::signup`] plus [`Self::signin`].
///
/// # Errors
/// - Returns [`crate::errors::Error::Parse`] if the homeserver URL cannot be constructed.
/// - Propagates transport failures while creating the account or publishing the homeserver record.
/// - Propagates validation errors while hydrating the cookie session.
pub async fn signup_cookie(
&self,
homeserver: &PublicKey,
signup_token: Option<&str>,
) -> Result<PubkySession> {
let url = Self::build_signup_url(homeserver, signup_token)?;
let auth_token = self.root_capability_token();
let response = self
.send_signup_request(url, auth_token.serialize())
.await?;
self.publish_signup_homeserver(homeserver).await?;
let cookie_credential =
CookieCredential::from_response(response, Some(homeserver.clone())).await?;
Ok(PubkySession::from_credential(
self.client.clone(),
Arc::new(cookie_credential),
))
}
/// Legacy cookie signin. Prefer [`Self::signin`].
///
/// # Errors
/// - Propagates transport failures during the session exchange.
/// - Propagates validation errors while creating the cookie credential.
pub async fn signin_cookie(&self) -> Result<PubkySession> {
self.signin_cookie_with_publish(PublishMode::Background)
.await
}
/// Legacy cookie signin with blocking PKDNS refresh. Prefer [`Self::signin_blocking`].
///
/// # Errors
/// - Propagates transport failures during the session exchange.
/// - Propagates failures while refreshing the homeserver record.
pub async fn signin_cookie_blocking(&self) -> Result<PubkySession> {
self.signin_cookie_with_publish(PublishMode::Blocking).await
}
async fn signin_cookie_with_publish(&self, mode: PublishMode) -> Result<PubkySession> {
let token = self.root_capability_token();
let user = self.keypair.public_key();
let homeserver = self.pkdns().get_homeserver_of(&user).await?;
let credential =
CookieCredential::from_auth_token(&token, &self.client, homeserver).await?;
let session = PubkySession::from_cookie_credential(self.client.clone(), credential);
self.publish_after_signin(mode).await?;
Ok(session)
}
async fn publish_after_signin(&self, mode: PublishMode) -> Result<()> {
match mode {
PublishMode::Blocking => {
cross_log!(
info,
"Publishing homeserver for {} in blocking mode",
self.keypair.public_key()
);
self.pkdns().publish_homeserver_if_stale(None).await?;
}
PublishMode::Background => {
let signer = self.clone();
let fut = async move {
cross_log!(
info,
"Background publish of homeserver for {} started",
signer.keypair.public_key()
);
if let Err(e) = signer.pkdns().publish_homeserver_if_stale(None).await {
cross_log!(
error,
"Background publish for {} failed: {:?}",
signer.keypair.public_key(),
e
);
} else {
cross_log!(
info,
"Background publish task for {} completed",
signer.keypair.public_key()
);
}
};
#[cfg(not(target_arch = "wasm32"))]
tokio::spawn(fut);
#[cfg(target_arch = "wasm32")]
wasm_bindgen_futures::spawn_local(fut);
}
}
Ok(())
}
fn build_signup_url(homeserver: &PublicKey, signup_token: Option<&str>) -> Result<Url> {
let mut url = Url::parse(&format!("https://{}", homeserver.z32()))?;
url.set_path("/signup");
if let Some(token) = signup_token {
url.query_pairs_mut().append_pair("signup_token", token);
}
Ok(url)
}
fn root_capability_token(&self) -> AuthToken {
let capabilities = Capabilities::builder().cap(Capability::root()).finish();
AuthToken::sign(&self.keypair, capabilities)
}
fn signup_grant(&self, client_keypair: &Keypair) -> Result<(String, GrantClaims)> {
let client_id = ClientId::new(SIGNUP_CLIENT_ID)
.map_err(|e| crate::errors::AuthError::Validation(e.to_string()))?;
let claims = self.grant_claims(client_id, client_keypair, SIGNUP_GRANT_LIFETIME_SECS);
let jws = claims.sign(&self.keypair, GRANT_JWS_TYP);
Ok((jws, claims))
}
fn session_grant(
&self,
client_id: ClientId,
client_keypair: &Keypair,
) -> (String, GrantClaims) {
let claims = self.grant_claims(client_id, client_keypair, DEFAULT_GRANT_LIFETIME_SECS);
let jws = claims.sign(&self.keypair, GRANT_JWS_TYP);
(jws, claims)
}
fn grant_claims(
&self,
client_id: ClientId,
client_keypair: &Keypair,
lifetime_secs: u64,
) -> GrantClaims {
let now = web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
GrantClaims {
iss: self.keypair.public_key(),
client_id,
caps: Capabilities::builder()
.cap(Capability::root())
.finish()
.to_vec(),
cnf: client_keypair.public_key(),
jti: GrantId::generate(),
iat: now,
exp: now + lifetime_secs,
}
}
async fn send_signup_request(&self, url: Url, body: Vec<u8>) -> Result<reqwest::Response> {
let response = self
.client
.cross_request(Method::POST, url)
.await?
.body(body)
.send()
.await?;
// Map non-2xx into our error type; keep body/headers intact for the caller.
check_http_status(response).await
}
async fn publish_signup_homeserver(&self, homeserver: &PublicKey) -> Result<()> {
cross_log!(
info,
"Signup request for {} succeeded; publishing homeserver",
self.keypair.public_key()
);
self.pkdns()
.publish_homeserver_force(Some(homeserver))
.await?;
cross_log!(
info,
"Signup homeserver publish complete for {}",
self.keypair.public_key()
);
Ok(())
}
}