Sign in with Apple
CI / test (push) Successful in 1m35s
CI / build (push) Successful in 5m14s
CI / deploy (push) Skipped

POST /v1/auth/apple verifies the ID token from Sign in with Apple JS
against Apple's keys, the Services IDs in APPLE_CLIENT_IDS and Apple's
issuer, then logs in like Google: the linked identity, else the user
with the same verified address, else a new user (invitations and
referrals as for Google). The Google verifier became a shared ID token
verifier. Apple gives the name only at the first sign-in; the page
sends it along (family name first). The login page shows Apple's white
button under Google's when it is configured; the privacy pages say what
Apple passes on, including the relay addresses.

The deploy compose's MAIL_FROM default is noreply@ like production
(the sender registered for Apple's e-mail relay).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-20 19:40:03 +00:00
co-authored by Claude Opus 5.5
parent 16c40864bb
commit 1b768d558d
17 changed files with 499 additions and 137 deletions
+3 -1
View File
@@ -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 <hello@sorsfonalak.hu>}
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <noreply@sorsfonalak.hu>}
PUBLIC_BASE_URL: https://${DOMAIN}
LOG_DIR: /logs
# On a deploy the e-mails and invoices being sent finish first.
+1
View File
@@ -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:-}
+1 -1
View File
@@ -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 <hello@sorsfonalak.hu>` (ez az alapérték is).
- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak <noreply@sorsfonalak.hu>` (é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:
+1
View File
@@ -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 |
+10
View File
@@ -75,6 +75,12 @@ pub struct Config {
pub google_client_ids: Vec<String>,
/// `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<String>,
/// `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<String>,
@@ -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()],
-107
View File
@@ -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<String>,
#[serde(default)]
pub email_verified: bool,
pub name: Option<String>,
pub locale: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct Jwk {
kid: String,
n: String,
e: String,
}
#[derive(Debug, Deserialize)]
struct JwkSet {
keys: Vec<Jwk>,
}
pub struct GoogleVerifier {
client_ids: Vec<String>,
jwks_url: String,
http: reqwest::Client,
cache: RwLock<Option<(Instant, Vec<Jwk>)>>,
}
impl GoogleVerifier {
pub fn new(client_ids: Vec<String>, 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<Vec<Jwk>, 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<Jwk, ApiError> {
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<GoogleClaims, ApiError> {
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::<GoogleClaims>(id_token, &key, &validation).map_err(invalid)?.claims)
}
}
+7 -4
View File
@@ -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"
);
+139
View File
@@ -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<String>,
/// 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<String>,
pub locale: Option<String>,
}
fn flexible_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
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<Jwk>,
}
pub struct IdTokenVerifier {
/// "Google" or "Apple", for messages.
provider: &'static str,
issuers: &'static [&'static str],
client_ids: Vec<String>,
jwks_url: String,
http: reqwest::Client,
cache: RwLock<Option<(Instant, Vec<Jwk>)>>,
}
impl IdTokenVerifier {
fn new(
provider: &'static str,
issuers: &'static [&'static str],
client_ids: Vec<String>,
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<String>, jwks_url: String) -> Self {
Self::new("Google", GOOGLE_ISSUERS, client_ids, jwks_url)
}
pub fn apple(client_ids: Vec<String>, 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<Vec<Jwk>, 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<Jwk, ApiError> {
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<IdClaims, ApiError> {
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::<IdClaims>(id_token, &key, &validation).map_err(invalid)?.claims)
}
}
+76 -12
View File
@@ -307,20 +307,78 @@ pub async fn google(
WithRejection(Json(req), _): Body<GoogleRequest>,
) -> ApiResult<impl IntoResponse> {
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<String>,
invite_token: Option<String>,
referral: Option<String>,
}
/// 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<AppleRequest>,
) -> ApiResult<impl IntoResponse> {
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<String>,
locale: Option<String>,
invite_token: Option<String>,
referral: Option<String>,
}
/// 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<impl IntoResponse + use<>> {
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())
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 -------------------------------------------------------------------------------
+2
View File
@@ -66,6 +66,7 @@ pub fn router(state: Arc<AppState>) -> 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<Value> {
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"),
+70 -1
View File
@@ -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);
}
+11 -1
View File
@@ -57,7 +57,10 @@ export default async function PrivacyPage() {
</thead>
<tbody>
<tr>
<td>Google-fiókod neve, e-mail-címe és azonosítója (belépéskor a Google adja át)</td>
<td>
Google- vagy Apple-fiókod neve, e-mail-címe és azonosítója (belépéskor a Google, illetve az Apple adja
át)
</td>
<td>Fiókod létrehozása, belépés, kapcsolattartás</td>
<td>Szerződés teljesítése (GDPR 6. cikk (1) b)</td>
</tr>
@@ -168,6 +171,13 @@ export default async function PrivacyPage() {
</a>{" "}
szabályzatnak, beleértve a „Limited Use” (korlátozott felhasználás) követelményeit.
</p>
<p>
<strong>Belépés Apple-fiókkal:</strong> 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 (<code>…@privaterelay.appleid.com</code>): 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).
</p>
</section>
<section>
@@ -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<AppleSignInResponse>;
};
};
}
}
/** Apple's logo (Sign in with Apple guidelines: the logo left of the label). */
function AppleMark() {
return (
<svg width="18" height="20" viewBox="0 0 17 20" aria-hidden="true" fill="currentColor">
<path d="M13.77 10.62c-.02-2.2 1.8-3.26 1.88-3.31-1.03-1.5-2.62-1.7-3.18-1.73-1.35-.14-2.64.8-3.33.8-.69 0-1.74-.78-2.86-.76-1.47.02-2.83.86-3.59 2.17-1.53 2.65-.39 6.57 1.1 8.72.73 1.05 1.6 2.23 2.73 2.19 1.1-.04 1.51-.71 2.84-.71 1.32 0 1.7.71 2.86.69 1.18-.02 1.93-1.07 2.65-2.12.84-1.22 1.18-2.4 1.2-2.46-.03-.01-2.29-.88-2.3-3.48zM11.6 4.17c.6-.73 1.01-1.75.9-2.76-.87.04-1.92.58-2.54 1.31-.56.65-1.05 1.69-.92 2.68.97.08 1.96-.49 2.56-1.23z" />
</svg>
);
}
/** 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<string | null>(null);
const [uninvited, setUninvited] = useState<string | null>(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 (
<div className="field">
<Script
src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/hu_HU/appleid.auth.js"
strategy="afterInteractive"
onReady={loaded}
onError={() => setError("Nem sikerült betölteni az Apple-belépést. Ellenőrizd a hálózatot vagy a reklámblokkolót.")}
/>
<button type="button" className="btn-social btn-apple" onClick={signIn} disabled={!ready || busy}>
<span className="btn-social-icon">
<AppleMark />
</span>
{busy ? "Belépés…" : "Folytatás Apple-fiókkal"}
</button>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{uninvited !== null && (
<>
<p className="msg msg-error" role="alert">
{inviteToken
? "Ez a meghívó már nem érvényes, és ehhez az Apple-fiókhoz sem tartozik másik."
: "A Sorsfonalak jelenleg meghívásos, és ehhez az Apple-fiókhoz nem tartozik meghívó. Ha kaptál meghívót, nyisd meg a levélben kapott linket, vagy lépj be azzal a fiókkal, amelynek a címére a meghívó szólt."}
</p>
<Waitlist email={uninvited.endsWith("@privaterelay.appleid.com") ? "" : uninvited} />
</>
)}
</div>
);
}
+10 -8
View File
@@ -8,6 +8,7 @@ import { BACKEND_URL, getMe } from "@/lib/server";
import { formatDate } from "@/lib/astro";
import type { InvitationLanding, PublicConfig } from "@/lib/types";
import { AppleLogin } from "./AppleLogin";
import { GoogleLogin } from "./GoogleLogin";
export const metadata: Metadata = { title: "Belépés" };
@@ -43,7 +44,7 @@ const CLOSED: Record<string, string> = {
};
/** The invitation the visitor came with: who sent it and what they wrote. */
function InvitationCard({ invitation }: { invitation: InvitationLanding | null }) {
function InvitationCard({ invitation, apple }: { invitation: InvitationLanding | null; apple: boolean }) {
if (!invitation) {
return (
<p className="msg msg-error" role="alert">
@@ -66,7 +67,7 @@ function InvitationCard({ invitation }: { invitation: InvitationLanding | null }
</p>
{invitation.message && <blockquote className="invite-quote">{invitation.message}</blockquote>}
<p className="hint" style={{ margin: 0 }}>
Bármelyik Google-fiókoddal elfogadhatod. Érvényes: {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.
Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"} elfogadhatod. Érvényes: {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.
</p>
</div>
);
@@ -83,6 +84,8 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
inviteToken ? loadInvitation(inviteToken) : Promise.resolve(null),
]);
const clientId = config?.google_login.enabled ? config.google_login.client_id : null;
const appleId = config?.apple_login?.enabled ? config.apple_login.client_id : null;
const pendingInvite = invitation?.status === "pending" ? inviteToken : null;
const inviteOnly = config?.signup_mode === "invite";
return (
@@ -107,17 +110,16 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
<h1 style={{ fontSize: 44 }}>{rawToken ? "Meghívó" : "Belépés"}</h1>
<p className="muted">{rawToken ? "Lépj be, és már kezdheted is." : "Üdv újra! Lépj be a fiókodba."}</p>
</div>
{rawToken && <InvitationCard invitation={inviteToken ? invitation : null} />}
{rawToken && <InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} />}
{config === null ? (
<p className="msg msg-error" role="alert">
A szerver most nem érhető el. Próbáld újra egy kicsit később.
</p>
) : clientId ? (
<GoogleLogin
clientId={clientId}
target={target}
inviteToken={invitation?.status === "pending" ? inviteToken : null}
/>
<div className="field" style={{ gap: 12 }}>
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} />
{appleId && <AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} />}
</div>
) : (
<p className="msg msg-error" role="alert">
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
+5
View File
@@ -210,6 +210,11 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.social-login:hover .btn-social { border-color: #5a6790; background: rgba(255, 255, 255, 0.03); }
.social-login:focus-within .btn-social { outline: 2px solid var(--gold); outline-offset: 2px; }
.social-login[data-ready="false"] .btn-social { opacity: 0.6; }
/* Sign in with Apple: Apple's white button style. */
.btn-apple { background: #fff; border-color: #fff; color: #000; cursor: pointer; }
.btn-apple:hover:not(:disabled) { background: #e8e8ed; border-color: #e8e8ed; }
.btn-apple:focus-visible { outline: 2px solid var(--gold); outline-offset: 2px; }
.btn-apple:disabled { opacity: 0.6; cursor: default; }
.gsi-overlay {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
opacity: 0.001; overflow: hidden; cursor: pointer;
+8 -1
View File
@@ -12,7 +12,7 @@ export const metadata: Metadata = {
const DATA: [string, string, string][] = [
[
"Your Google account's name, e-mail address and ID (passed on by Google when you sign in)",
"Your Google or Apple account's name, e-mail address and ID (passed on by Google or Apple when you sign in)",
"Creating your account, signing you in, contacting you",
"Performance of a contract (GDPR Art. 6(1)(b))",
],
@@ -168,6 +168,13 @@ export default async function PrivacyPolicyPage() {
</a>
, including the Limited Use requirements.
</p>
<p>
<strong>Signing in with Apple:</strong> if you choose “Sign in with Apple”, Apple passes us your account&apos;s
unique ID and your e-mail address, and your name the first time. If you hide your address, we get an Apple
relay address (<code>…@privaterelay.appleid.com</code>) and Apple forwards our e-mails to you. We use these
for the same purposes and in the same way as the Google data. You can revoke access in your Apple ID settings
(Sign-In and Security › Sign in with Apple).
</p>
</section>
<section>
+2
View File
@@ -94,6 +94,8 @@ export interface Question {
export interface PublicConfig {
google_login: { enabled: boolean; client_id: string | null };
/** Sign in with Apple; `client_id` is the Services ID. */
apple_login?: { enabled: boolean; client_id: string | null };
locales: string[];
password_login: boolean;
password_min_length: number;