diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 02761c5..550f8ed 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -81,6 +81,8 @@ services: HOROSCOPE_API_URL: http://horoscope-api:8080 PUBLIC_BASE_URL: https://${DOMAIN} GOOGLE_CLIENT_IDS: ${GOOGLE_CLIENT_IDS:-} + # Sign in with Apple: the Services ID (e.g. hu.sorsfonalak.web); empty: off. + APPLE_CLIENT_IDS: ${APPLE_CLIENT_IDS:-} BOOTSTRAP_ADMIN_EMAILS: ${BOOTSTRAP_ADMIN_EMAILS:-} ANALYSIS_MODEL: ${ANALYSIS_MODEL:-} SUMMARY_MODEL: ${SUMMARY_MODEL:-} @@ -131,7 +133,7 @@ services: # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md); # listing them here with an empty default would override that file. SES_REGION: ${SES_REGION:-eu-central-1} - MAIL_FROM: ${MAIL_FROM:-Sorsfonalak } + MAIL_FROM: ${MAIL_FROM:-Sorsfonalak } PUBLIC_BASE_URL: https://${DOMAIN} LOG_DIR: /logs # On a deploy the e-mails and invoices being sent finish first. diff --git a/docker-compose.yml b/docker-compose.yml index 874d19f..ebf9da0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -46,6 +46,7 @@ services: # Plain HTTP in development; leave the default (true) in production. COOKIE_SECURE: ${COOKIE_SECURE:-false} GOOGLE_CLIENT_IDS: ${GOOGLE_CLIENT_IDS:-} + APPLE_CLIENT_IDS: ${APPLE_CLIENT_IDS:-} BOOTSTRAP_ADMIN_EMAILS: ${BOOTSTRAP_ADMIN_EMAILS:-} # Paid detailed analyses (empty: anthropic/claude-opus-5.5). ANALYSIS_MODEL: ${ANALYSIS_MODEL:-} diff --git a/docs/levelkuldes.md b/docs/levelkuldes.md index d643cf0..e6dda5c 100644 --- a/docs/levelkuldes.md +++ b/docs/levelkuldes.md @@ -68,7 +68,7 @@ A droplet saját tűzfala (`sorsfonalak-fw`, DigitalOcean → Networking → Fir ## 6. Indítás -- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak ` (ez az alapérték is). +- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak ` (élesben ez van beállítva, és ez a deploy compose alapértéke is). Az Apple „Email Communication” beállításában ugyanez a cím van regisztrálva: ha változik, ott is át kell írni, különben az Apple-továbbítócímekre nem érkeznek meg a levelek. - Utána: `docker compose up -d worker`. A naplóban ennek kell megjelennie: `e-mail delivery enabled`, `via=Amazon SES eu-central-1:2587, credentials from …`. - Az eddig várakozó levelek ekkor kimennek. Ha ezt nem szeretnéd, előtte töröld őket: `DELETE FROM email_outbox WHERE sent_at IS NULL;`. - Hibaüzenetek a naplóban: diff --git a/services/backend/README.md b/services/backend/README.md index 14f6651..4f2536d 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -18,6 +18,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `FREE_PERSON_SLOTS` | `0` | ennyi személyt vehet fel csomag nélkül egy felhasználó | | `SIGNUP_MODE` | `invite` | `invite`: új fiók csak meghívóval jön létre (403 `not_invited`); `open`: bárki regisztrálhat | | `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva | +| `APPLE_CLIENT_IDS` | – | Sign in with Apple: a Services ID(k) vesszővel elválasztva (pl. `hu.sorsfonalak.web`), az ID token `aud` mezője ezek egyike kell legyen; üresen az Apple-belépés ki van kapcsolva | | `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) | | `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett | | `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | az elemzések, előrejelzések és válaszok alapmodellje, és a tartalék, ha a választott modell hibára fut | diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index aa585bf..a63c0da 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -75,6 +75,12 @@ pub struct Config { pub google_client_ids: Vec, /// `GOOGLE_JWKS_URL` (default Google's certificate endpoint). pub google_jwks_url: String, + /// `APPLE_CLIENT_IDS`: comma-separated Services IDs (e.g. + /// `hu.sorsfonalak.web`) accepted as the ID token audience; empty + /// disables Sign in with Apple. + pub apple_client_ids: Vec, + /// `APPLE_JWKS_URL` (default Apple's key endpoint). + pub apple_jwks_url: String, /// `BOOTSTRAP_ADMIN_EMAILS`: these users get the admin role when they /// register or log in (to create the first administrator). pub bootstrap_admin_emails: Vec, @@ -197,6 +203,8 @@ impl Config { google_client_ids: list("GOOGLE_CLIENT_IDS"), google_jwks_url: var("GOOGLE_JWKS_URL") .unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()), + apple_client_ids: list("APPLE_CLIENT_IDS"), + apple_jwks_url: var("APPLE_JWKS_URL").unwrap_or_else(|| "https://appleid.apple.com/auth/keys".into()), bootstrap_admin_emails: list("BOOTSTRAP_ADMIN_EMAILS").into_iter().map(|e| e.to_lowercase()).collect(), supported_locales, analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()), @@ -240,6 +248,8 @@ impl Config { user_invites: true, referral_rewards: true, google_client_ids: vec!["test-client.apps.googleusercontent.com".into()], + apple_client_ids: vec!["hu.sorsfonalak.test".into()], + apple_jwks_url: google_jwks_url.clone(), google_jwks_url, bootstrap_admin_emails: vec!["admin@example.com".into()], supported_locales: vec!["hu".into(), "en".into()], diff --git a/services/backend/src/google.rs b/services/backend/src/google.rs deleted file mode 100644 index cfbabd2..0000000 --- a/services/backend/src/google.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! Google Sign-In: verification of Google ID tokens. -//! -//! The frontend obtains an ID token with Google Identity Services (button or -//! One Tap) and posts it to `POST /v1/auth/google`. The token is a JWT signed -//! by Google; it is verified here against Google's published keys (JWKS, -//! cached), the configured client ids (audience) and the issuer. - -use std::time::{Duration, Instant}; - -use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; -use serde::Deserialize; -use tokio::sync::RwLock; - -use crate::error::ApiError; - -const ISSUERS: [&str; 2] = ["accounts.google.com", "https://accounts.google.com"]; -const JWKS_MAX_AGE: Duration = Duration::from_secs(3600); - -#[derive(Debug, Deserialize)] -pub struct GoogleClaims { - /// Stable Google account id. - pub sub: String, - pub email: Option, - #[serde(default)] - pub email_verified: bool, - pub name: Option, - pub locale: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct Jwk { - kid: String, - n: String, - e: String, -} - -#[derive(Debug, Deserialize)] -struct JwkSet { - keys: Vec, -} - -pub struct GoogleVerifier { - client_ids: Vec, - jwks_url: String, - http: reqwest::Client, - cache: RwLock)>>, -} - -impl GoogleVerifier { - pub fn new(client_ids: Vec, jwks_url: String) -> Self { - let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("static configuration"); - Self { client_ids, jwks_url, http, cache: RwLock::new(None) } - } - - pub fn enabled(&self) -> bool { - !self.client_ids.is_empty() - } - - async fn fetch_keys(&self) -> Result, ApiError> { - let set: JwkSet = self - .http - .get(&self.jwks_url) - .send() - .await - .and_then(|r| r.error_for_status()) - .map_err(|e| ApiError::Internal(format!("fetching Google keys: {e}")))? - .json() - .await - .map_err(|e| ApiError::Internal(format!("parsing Google keys: {e}")))?; - Ok(set.keys) - } - - /// The key with `kid`; the key set is refetched when it is stale or the - /// key is unknown (Google rotates its keys). - async fn key(&self, kid: &str) -> Result { - if let Some((fetched, keys)) = self.cache.read().await.as_ref() - && fetched.elapsed() < JWKS_MAX_AGE - && let Some(k) = keys.iter().find(|k| k.kid == kid) - { - return Ok(k.clone()); - } - let keys = self.fetch_keys().await?; - let found = keys.iter().find(|k| k.kid == kid).cloned(); - *self.cache.write().await = Some((Instant::now(), keys)); - found.ok_or_else(|| ApiError::InvalidCredentials("the Google token is signed with an unknown key".into())) - } - - pub async fn verify(&self, id_token: &str) -> Result { - if !self.enabled() { - return Err(ApiError::Forbidden("Google login is not configured".into())); - } - let invalid = - |e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid Google token: {e}")); - let header = decode_header(id_token).map_err(invalid)?; - if header.alg != Algorithm::RS256 { - return Err(ApiError::InvalidCredentials("invalid Google token: unexpected algorithm".into())); - } - let kid = header.kid.ok_or_else(|| ApiError::InvalidCredentials("invalid Google token: no key id".into()))?; - let jwk = self.key(&kid).await?; - let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?; - let mut validation = Validation::new(Algorithm::RS256); - validation.set_audience(&self.client_ids); - validation.set_issuer(&ISSUERS); - validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]); - Ok(decode::(id_token, &key, &validation).map_err(invalid)?.claims) - } -} diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index c2e83c6..fe7d6b8 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -12,9 +12,9 @@ mod birth_changes; mod config; mod credits; mod error; -mod google; mod invoices; mod models; +mod oidc; mod packages; mod persons; mod routes; @@ -32,7 +32,7 @@ use sqlx::PgPool; use crate::auth::LoginLimiter; use crate::config::Config; -use crate::google::GoogleVerifier; +use crate::oidc::IdTokenVerifier; const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8081"; @@ -40,7 +40,8 @@ pub struct AppState { pub db: PgPool, pub config: Config, pub horoscope: HoroscopeClient, - pub google: GoogleVerifier, + pub google: IdTokenVerifier, + pub apple: IdTokenVerifier, pub login_limiter: LoginLimiter, pub models: models::Catalog, pub stripe: stripe::Client, @@ -50,7 +51,8 @@ impl AppState { pub fn new(db: PgPool, config: Config) -> Self { Self { horoscope: HoroscopeClient::new(&config.horoscope_api_url), - google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()), + google: IdTokenVerifier::google(config.google_client_ids.clone(), config.google_jwks_url.clone()), + apple: IdTokenVerifier::apple(config.apple_client_ids.clone(), config.apple_jwks_url.clone()), login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), @@ -72,6 +74,7 @@ async fn main() -> anyhow::Result<()> { db::migrate(&pool).await.context("running database migrations")?; tracing::info!( google_login = !config.google_client_ids.is_empty(), + apple_login = !config.apple_client_ids.is_empty(), horoscope_api = %config.horoscope_api_url, "database ready" ); diff --git a/services/backend/src/oidc.rs b/services/backend/src/oidc.rs new file mode 100644 index 0000000..3124641 --- /dev/null +++ b/services/backend/src/oidc.rs @@ -0,0 +1,139 @@ +//! Sign-in with Google and Apple: verification of their ID tokens. +//! +//! The frontend obtains an ID token (Google Identity Services, or Sign in with +//! Apple JS) and posts it to `POST /v1/auth/google` / `/v1/auth/apple`. The +//! token is a JWT signed by the provider; it is verified here against the +//! provider's published keys (JWKS, cached), the configured client ids +//! (audience: Google client ids, Apple Services IDs) and the issuer. + +use std::time::{Duration, Instant}; + +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use serde::Deserialize; +use tokio::sync::RwLock; + +use crate::error::ApiError; + +const GOOGLE_ISSUERS: &[&str] = &["accounts.google.com", "https://accounts.google.com"]; +const APPLE_ISSUERS: &[&str] = &["https://appleid.apple.com"]; +const JWKS_MAX_AGE: Duration = Duration::from_secs(3600); + +#[derive(Debug, Deserialize)] +pub struct IdClaims { + /// Stable account id at the provider. + pub sub: String, + pub email: Option, + /// Apple sends it as a string ("true"). + #[serde(default, deserialize_with = "flexible_bool")] + pub email_verified: bool, + /// Google only; Apple gives the name to the frontend, at the first sign-in. + pub name: Option, + pub locale: Option, +} + +fn flexible_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(match serde_json::Value::deserialize(d)? { + serde_json::Value::Bool(b) => b, + serde_json::Value::String(s) => s == "true", + _ => false, + }) +} + +#[derive(Debug, Clone, Deserialize)] +struct Jwk { + kid: String, + n: String, + e: String, +} + +#[derive(Debug, Deserialize)] +struct JwkSet { + keys: Vec, +} + +pub struct IdTokenVerifier { + /// "Google" or "Apple", for messages. + provider: &'static str, + issuers: &'static [&'static str], + client_ids: Vec, + jwks_url: String, + http: reqwest::Client, + cache: RwLock)>>, +} + +impl IdTokenVerifier { + fn new( + provider: &'static str, + issuers: &'static [&'static str], + client_ids: Vec, + jwks_url: String, + ) -> Self { + let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("static configuration"); + Self { provider, issuers, client_ids, jwks_url, http, cache: RwLock::new(None) } + } + + pub fn google(client_ids: Vec, jwks_url: String) -> Self { + Self::new("Google", GOOGLE_ISSUERS, client_ids, jwks_url) + } + + pub fn apple(client_ids: Vec, jwks_url: String) -> Self { + Self::new("Apple", APPLE_ISSUERS, client_ids, jwks_url) + } + + pub fn enabled(&self) -> bool { + !self.client_ids.is_empty() + } + + async fn fetch_keys(&self) -> Result, ApiError> { + let set: JwkSet = self + .http + .get(&self.jwks_url) + .send() + .await + .and_then(|r| r.error_for_status()) + .map_err(|e| ApiError::Internal(format!("fetching {} keys: {e}", self.provider)))? + .json() + .await + .map_err(|e| ApiError::Internal(format!("parsing {} keys: {e}", self.provider)))?; + Ok(set.keys) + } + + /// The key with `kid`; the key set is refetched when it is stale or the + /// key is unknown (the providers rotate their keys). + async fn key(&self, kid: &str) -> Result { + if let Some((fetched, keys)) = self.cache.read().await.as_ref() + && fetched.elapsed() < JWKS_MAX_AGE + && let Some(k) = keys.iter().find(|k| k.kid == kid) + { + return Ok(k.clone()); + } + let keys = self.fetch_keys().await?; + let found = keys.iter().find(|k| k.kid == kid).cloned(); + *self.cache.write().await = Some((Instant::now(), keys)); + found.ok_or_else(|| { + ApiError::InvalidCredentials(format!("the {} token is signed with an unknown key", self.provider)) + }) + } + + pub async fn verify(&self, id_token: &str) -> Result { + let provider = self.provider; + if !self.enabled() { + return Err(ApiError::Forbidden(format!("{provider} login is not configured"))); + } + let invalid = + |e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid {provider} token: {e}")); + let header = decode_header(id_token).map_err(invalid)?; + if header.alg != Algorithm::RS256 { + return Err(ApiError::InvalidCredentials(format!("invalid {provider} token: unexpected algorithm"))); + } + let kid = + header.kid.ok_or_else(|| ApiError::InvalidCredentials(format!("invalid {provider} token: no key id")))?; + let jwk = self.key(&kid).await?; + let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?; + let mut validation = Validation::new(Algorithm::RS256); + validation.set_audience(&self.client_ids); + validation.set_issuer(self.issuers); + validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]); + Ok(decode::(id_token, &key, &validation).map_err(invalid)?.claims) + } +} diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index 092eba5..f7f1ba4 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -307,20 +307,78 @@ pub async fn google( WithRejection(Json(req), _): Body, ) -> ApiResult { let claims = state.google.verify(&req.id_token).await?; + let signup = Signup { + name: claims.name.clone(), + locale: claims.locale.clone(), + invite_token: req.invite_token, + referral: req.referral, + }; + social_login(&state, headers, jar, "google", claims, signup).await +} + +// --- Apple ------------------------------------------------------------------------------ + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AppleRequest { + /// ID token (JWT) from Sign in with Apple JS. + id_token: String, + /// The name Apple gives the page at the first sign-in only (it is not in + /// the token): used when the account is created. + name: Option, + invite_token: Option, + referral: Option, +} + +/// Logs in with Apple, like [`google`]. The address may be an Apple relay +/// (`…@privaterelay.appleid.com`), which forwards our e-mails. +pub async fn apple( + State(state): St, + headers: HeaderMap, + jar: CookieJar, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let claims = state.apple.verify(&req.id_token).await?; + let signup = Signup { name: req.name, locale: None, invite_token: req.invite_token, referral: req.referral }; + social_login(&state, headers, jar, "apple", claims, signup).await +} + +/// What a new account starts with. +struct Signup { + name: Option, + locale: Option, + invite_token: Option, + referral: Option, +} + +/// Logs in with a verified provider identity: the linked user, else the user +/// with the same (provider-verified) e-mail address, else a new user. +async fn social_login( + state: &AppState, + headers: HeaderMap, + jar: CookieJar, + provider: &'static str, + claims: crate::oidc::IdClaims, + signup: Signup, +) -> ApiResult> { let email = match (claims.email.as_deref(), claims.email_verified) { (Some(e), true) => normalize_email(e)?, - _ => return Err(ApiError::InvalidCredentials("the Google account has no verified e-mail address".into())), + _ => { + return Err(ApiError::InvalidCredentials(format!("the {provider} account has no verified e-mail address"))); + } }; let mut tx = state.db.begin().await?; let linked: Option<(Uuid,)> = - sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = 'google' AND subject = $1") + sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = $1 AND subject = $2") + .bind(provider) .bind(&claims.sub) .fetch_optional(&mut *tx) .await?; let (user_id, created) = match linked { Some((id,)) => { - sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = 'google' AND subject = $1") + sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = $1 AND subject = $2") + .bind(provider) .bind(&claims.sub) .execute(&mut *tx) .await?; @@ -331,7 +389,7 @@ pub async fn google( sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?; let (id, created) = match existing { Some((id,)) => { - // Google has verified the address, so it counts as verified here too. + // The provider has verified the address, so it counts as verified here too. sqlx::query( "UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1", ) @@ -341,9 +399,9 @@ pub async fn google( (id, false) } None => { - super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?; + super::invitations::admit(state, &mut tx, &email, signup.invite_token.as_deref()).await?; let id = Uuid::now_v7(); - let locale = claims + let locale = signup .locale .as_deref() .and_then(|l| l.split(['-', '_']).next()) @@ -355,7 +413,7 @@ pub async fn google( ) .bind(id) .bind(&email) - .bind(clean_name(claims.name.clone())) + .bind(clean_name(signup.name)) .bind(locale) .execute(&mut *tx) .await?; @@ -363,21 +421,27 @@ pub async fn google( &mut tx, id, &email, - req.invite_token.as_deref(), + signup.invite_token.as_deref(), state.config.free_person_slots, ) .await?; - super::shares::record_referral(&mut tx, state.config.referral_rewards, id, req.referral.as_deref()) - .await?; + super::shares::record_referral( + &mut tx, + state.config.referral_rewards, + id, + signup.referral.as_deref(), + ) + .await?; (id, true) } }; sqlx::query( "INSERT INTO auth_identities (id, user_id, provider, subject, email, last_used_at) \ - VALUES ($1, $2, 'google', $3, $4, now())", + VALUES ($1, $2, $3, $4, $5, now())", ) .bind(Uuid::now_v7()) .bind(id) + .bind(provider) .bind(&claims.sub) .bind(&email) .execute(&mut *tx) @@ -386,11 +450,11 @@ pub async fn google( } }; let mut user = load_user(&mut tx, user_id).await?; - apply_bootstrap_admin(&state, &mut tx, &mut user).await?; + apply_bootstrap_admin(state, &mut tx, &mut user).await?; tx.commit().await?; let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?; - Ok(login_response(&state, jar, &user, session, created)) + Ok(login_response(state, jar, &user, session, created)) } // --- logout ------------------------------------------------------------------------------- diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 87d3c99..175d70f 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -66,6 +66,7 @@ pub fn router(state: Arc) -> Router { .route("/v1/auth/register", post(auth::register)) .route("/v1/auth/login", post(auth::login)) .route("/v1/auth/google", post(auth::google)) + .route("/v1/auth/apple", post(auth::apple)) .route("/v1/auth/logout", post(auth::logout)) .route("/v1/auth/logout-all", post(auth::logout_all)) .route("/v1/auth/verify-email", post(auth::verify_email)) @@ -164,6 +165,7 @@ async fn public_config(State(state): St) -> Json { let c = &state.config; Json(json!({ "google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() }, + "apple_login": { "enabled": state.apple.enabled(), "client_id": c.apple_client_ids.first() }, "locales": c.supported_locales, "password_login": c.password_login, "mock_payments": payments::method(c) == Some("mock"), diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 030a8f0..6fb34c8 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -195,6 +195,18 @@ fn google_token(sub: &str, email: &str, audience: &str) -> String { jsonwebtoken::encode(&header, &claims, &jsonwebtoken::EncodingKey::from_rsa_pem(GOOGLE_KEY_PEM).unwrap()).unwrap() } +fn apple_token(sub: &str, email: &str, audience: &str) -> String { + let now = time::OffsetDateTime::now_utc().unix_timestamp(); + // Apple sends email_verified as a string and no name. + let claims = json!({ + "iss": "https://appleid.apple.com", "aud": audience, "sub": sub, "email": email, + "email_verified": "true", "is_private_email": "true", "iat": now, "exp": now + 600 + }); + let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256); + header.kid = Some("test-key".into()); + jsonwebtoken::encode(&header, &claims, &jsonwebtoken::EncodingKey::from_rsa_pem(GOOGLE_KEY_PEM).unwrap()).unwrap() +} + // --- test client ------------------------------------------------------------------------------- struct TestApp { @@ -851,7 +863,7 @@ async fn export_and_delete_account(pool: PgPool) { /// config and catalog, shared links, invitation pages, the waitlist and /// unsubscribing. Every other route (charts, calculations, analyses) needs a /// logged-in user, so other apps cannot use them. -const PUBLIC_ROUTES: [&str; 16] = [ +const PUBLIC_ROUTES: [&str; 17] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -860,6 +872,7 @@ const PUBLIC_ROUTES: [&str; 16] = [ "/v1/auth/register", "/v1/auth/login", "/v1/auth/google", + "/v1/auth/apple", "/v1/auth/verify-email", "/v1/auth/password-reset", "/v1/auth/password-reset/confirm", @@ -2673,3 +2686,59 @@ async fn tarot_readings_draw_on_the_server_and_use_tarot_units(pool: PgPool) { assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body); assert_eq!(count().await, 0); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn apple_login_creates_links_and_rejects(pool: PgPool) { + let app = TestApp::new(pool).await; + let r = app.get("/v1/config", None).await; + assert_eq!(r.body["apple_login"], json!({"enabled": true, "client_id": "hu.sorsfonalak.test"})); + let relay = "x7k2p9@privaterelay.appleid.com"; + // The name comes from the page (Apple gives it at the first sign-in only). + let r = app + .post( + "/v1/auth/apple", + None, + json!({"id_token": apple_token("a-1", relay, "hu.sorsfonalak.test"), "name": "Kovács Anna"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + assert_eq!((&r.body["created"], &r.body["user"]["display_name"]), (&json!(true), &json!("Kovács Anna"))); + assert_eq!(r.body["user"]["email"], relay); + let r = + app.post("/v1/auth/apple", None, json!({"id_token": apple_token("a-1", relay, "hu.sorsfonalak.test")})).await; + assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); + assert_eq!(r.body["user"]["display_name"], "Kovács Anna"); + + // the same address as a Google account: both log into one user + let google = app + .post("/v1/auth/google", None, json!({"id_token": google_token("g-9", "bela@example.com", GOOGLE_CLIENT)})) + .await; + let token = google.body["session"]["token"].as_str().unwrap().to_string(); + let r = app + .post( + "/v1/auth/apple", + None, + json!({"id_token": apple_token("a-2", "bela@example.com", "hu.sorsfonalak.test")}), + ) + .await; + assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); + assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["google", "apple"])); + + // a Google token is no Apple token, nor one for another Services ID + let r = app + .post("/v1/auth/apple", None, json!({"id_token": google_token("g-1", "gabor@gmail.com", GOOGLE_CLIENT)})) + .await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); + let r = app.post("/v1/auth/apple", None, json!({"id_token": apple_token("a-3", relay, "other.service")})).await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn apple_login_can_be_off(pool: PgPool) { + let app = TestApp::with_config(pool, |c| c.apple_client_ids.clear()).await; + assert_eq!(app.get("/v1/config", None).await.body["apple_login"]["enabled"], false); + let r = app + .post("/v1/auth/apple", None, json!({"id_token": apple_token("a-1", "a@b.hu", "hu.sorsfonalak.test")})) + .await; + assert_eq!(r.status, StatusCode::FORBIDDEN); +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 051249b..1e2e180 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -57,7 +57,10 @@ export default async function PrivacyPage() { - Google-fiókod neve, e-mail-címe és azonosítója (belépéskor a Google adja át) + + Google- vagy Apple-fiókod neve, e-mail-címe és azonosítója (belépéskor a Google, illetve az Apple adja + át) + Fiókod létrehozása, belépés, kapcsolattartás Szerződés teljesítése (GDPR 6. cikk (1) b) @@ -168,6 +171,13 @@ export default async function PrivacyPage() { {" "} szabályzatnak, beleértve a „Limited Use” (korlátozott felhasználás) követelményeit.

+

+ Belépés Apple-fiókkal: ha az „Apple-bejelentkezést” választod, az Apple a fiókod egyedi + azonosítóját és az e-mail-címedet adja át, az első belépéskor a nevedet is. Ha az e-mail-címedet elrejted, + egy Apple-továbbítócímet kapunk (…@privaterelay.appleid.com): az erre küldött leveleinket az Apple + továbbítja hozzád. Ezeket ugyanarra és ugyanúgy használjuk, mint a Google-adatokat. A hozzáférést az Apple ID + beállításaidban vonhatod vissza (Bejelentkezés és biztonság › Bejelentkezés az Apple-lel). +

diff --git a/services/frontend/src/app/belepes/AppleLogin.tsx b/services/frontend/src/app/belepes/AppleLogin.tsx new file mode 100644 index 0000000..0e5b66f --- /dev/null +++ b/services/frontend/src/app/belepes/AppleLogin.tsx @@ -0,0 +1,152 @@ +"use client"; + +import Script from "next/script"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import { Waitlist } from "@/components/Waitlist"; +import { ApiError, api, errorText } from "@/lib/api"; + +/** The part of Sign in with Apple JS (appleid.auth.js) we use. */ +interface AppleSignInResponse { + authorization: { id_token: string; code: string; state?: string }; + /** Only at the first sign-in of this Apple ID on the site. */ + user?: { email?: string; name?: { firstName?: string; lastName?: string } }; +} + +declare global { + interface Window { + AppleID?: { + auth: { + init(options: { clientId: string; scope: string; redirectURI: string; state?: string; usePopup: boolean }): void; + signIn(): Promise; + }; + }; + } +} + +/** Apple's logo (Sign in with Apple guidelines: the logo left of the label). */ +function AppleMark() { + return ( + + ); +} + +/** The e-mail address inside Apple's ID token (only for the waitlist form; the backend verifies the token). */ +function tokenEmail(idToken: string): string { + try { + const part = idToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"); + const bytes = Uint8Array.from(atob(part), (c) => c.charCodeAt(0)); + const email = JSON.parse(new TextDecoder().decode(bytes)).email; + return typeof email === "string" ? email : ""; + } catch { + return ""; + } +} + +/** + * "Continue with Apple": Apple's sign-in opens in a popup and returns an ID + * token, which the backend verifies. Apple gives the name only at the first + * sign-in, so it is sent along then (Hungarian order: family name first). + */ +export function AppleLogin({ + clientId, + target, + inviteToken = null, +}: { + clientId: string; + target: string; + inviteToken?: string | null; +}) { + const router = useRouter(); + const [ready, setReady] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [uninvited, setUninvited] = useState(null); + + function loaded() { + window.AppleID?.auth.init({ + clientId, + scope: "name email", + redirectURI: `${window.location.origin}/belepes`, + usePopup: true, + }); + setReady(true); + } + + async function signIn() { + const apple = window.AppleID; + if (!apple) return; + setError(null); + setUninvited(null); + let response: AppleSignInResponse; + try { + response = await apple.auth.signIn(); + } catch (e) { + // Closing the popup is not an error worth showing. + const code = (e as { error?: string } | null)?.error; + if (code !== "popup_closed_by_user" && code !== "user_cancelled_authorize") { + setError("Az Apple-belépés nem sikerült. Próbáld újra."); + } + return; + } + setBusy(true); + const name = [response.user?.name?.lastName, response.user?.name?.firstName].filter(Boolean).join(" ") || null; + try { + let referral: string | null = null; + try { + referral = localStorage.getItem("sf_ref"); + } catch { + // storage blocked + } + await api("/auth/apple", { + body: { id_token: response.authorization.id_token, name, invite_token: inviteToken, referral }, + }); + try { + localStorage.removeItem("sf_ref"); + } catch { + // storage blocked + } + router.replace(target); + router.refresh(); + } catch (e) { + if (e instanceof ApiError && e.code === "not_invited") setUninvited(tokenEmail(response.authorization.id_token)); + else setError(errorText(e)); + setBusy(false); + } + } + + return ( +
+