Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Support secure OIDC authentication https://github.com/siyuan-note/siyuan/issues/18542

Danielbfb776a19ce1
diff --git a/README.md b/README.md
index ebfaf61cc5..a4d5c954a2 100644
--- a/README.md
+++ b/README.md
@@ -216,6 +216,14 @@ docker run -d \
- `accessAuthCode`: Lock screen password (please **be sure to modify**, otherwise anyone can access your data)
- Alternatively, it's possible to set the lock screen password via the `SIYUAN_ACCESS_AUTH_CODE` env variable. The commandline will always have the priority, if both are set
- To disable the lock screen password set the env variable `SIYUAN_ACCESS_AUTH_CODE_BYPASS=true`
+- OIDC can replace the lock screen password as the required Docker access authentication. Set `SIYUAN_OIDC_ENABLED=true`, `SIYUAN_OIDC_PROVIDER` (`custom`, `google`, `microsoft`, or `github`), `SIYUAN_OIDC_CLIENT_ID`, and the provider-specific values below. GitHub uses its OAuth 2.0 user API adapter; the other providers use OpenID Connect discovery and ID Token validation. An invalid enabled configuration stops Docker startup when no lock screen password is available
+ - `SIYUAN_OIDC_ISSUER_URL`: Issuer URL required by the `custom` and `microsoft` providers; Microsoft must use a tenant-specific issuer such as `https://login.microsoftonline.com/<tenant-id>/v2.0`
+ - `SIYUAN_OIDC_CLIENT_SECRET`: Optional client secret for OpenID Connect providers; required by the GitHub OAuth adapter. Every authorization-code flow also uses PKCE
+ - `SIYUAN_OIDC_SCOPES`: Comma- or space-separated scopes; `openid` is always included
+ - `SIYUAN_OIDC_REDIRECT_URL`: Public HTTPS callback URL ending in `/api/system/oidc/callback`, required for remote browser access
+ - `SIYUAN_OIDC_ALLOW_ALL`: Explicitly allow every identity authenticated by the provider
+ - `SIYUAN_OIDC_CLAIM_RULES`: JSON array of claim rules used when allow-all is disabled, for example `[{"claim":"email","operator":"equals","values":["[email protected]"]}]`; values within a rule use OR, while rules use AND
+ - Native mobile apps use the fixed callback URI `siyuan:/oidc-callback`; the identity provider must allow this private-use URI
- `SIYUAN_LANG`: Interface language (optional, defaults to `en` if unset in Docker). Accepts BCP 47 tags like `zh-CN`/`zh-TW`/`en`/`ja`/`pt-BR`; legacy underscore values like `zh_CN`/`en_US` are also accepted for backward compatibility. Omit it if you want the language chosen in **Settings** to persist across restarts; if set, it is applied on every startup and overrides the saved setting
- Alternatively, use the `--lang` command-line parameter. If both are set, the command-line takes priority
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 32991d7a73..cb49c5a460 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "إعداد قواعد مطالبات OIDC غير صالح",
+ "oidcClaimRulesTip": "مصفوفة JSON؛ القيم داخل القاعدة مرتبطة بـ OR والقواعد مرتبطة بـ AND",
+ "oidcClaimRules": "قواعد مطالبات OIDC",
+ "oidcAllowAll": "السماح لجميع المستخدمين المصادق عليهم",
+ "oidcRedirectURL": "عنوان URL لإعادة توجيه OIDC",
+ "oidcScopes": "نطاقات OIDC",
+ "oidcClientSecret": "سر عميل OIDC",
+ "oidcClientID": "معرّف عميل OIDC",
+ "oidcIssuerURL": "عنوان URL لجهة إصدار OIDC",
+ "oidcProvider": "موفر OIDC",
+ "oidcEnabled": "تمكين تسجيل الدخول عبر OIDC",
+ "oidcLoginTip": "تكوين تسجيل الدخول الأحادي من خلال موفر OpenID Connect",
+ "oidcLogin": "تسجيل الدخول عبر OIDC",
"disableAll": "تعطيل الكل",
"bazaarKernelPlugin": "إضافة النواة",
"newItemTemplateDefaultTip": "استخدام مسار الحفظ الافتراضي للمستندات الجديدة في دفتر الملاحظات الحالي",
@@ -2424,6 +2437,8 @@
"360": "تم التصدير إلى [%s]",
"361": "لا يمكن أن يكون اسم مستخدم حساب خدمة النشر فارغًا",
"362": "اسم مستخدم حساب خدمة النشر مكرر",
- "363": "يجب أن تتكون كلمة مرور حساب خدمة النشر من 8 أحرف على الأقل"
+ "363": "يجب أن تتكون كلمة مرور حساب خدمة النشر من 8 أحرف على الأقل",
+ "364": "تسجيل الدخول باستخدام OIDC",
+ "365": "فشل تسجيل الدخول عبر OIDC"
}
}
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index ec9ad87c37..8e96746131 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Ungültige Konfiguration der OIDC-Anspruchsregeln",
+ "oidcClaimRulesTip": "JSON-Array; Werte innerhalb einer Regel sind ODER-verknüpft, Regeln sind UND-verknüpft",
+ "oidcClaimRules": "OIDC-Anspruchsregeln",
+ "oidcAllowAll": "Alle authentifizierten Benutzer zulassen",
+ "oidcRedirectURL": "OIDC-Weiterleitungs-URL",
+ "oidcScopes": "OIDC-Bereiche",
+ "oidcClientSecret": "OIDC-Client-Geheimnis",
+ "oidcClientID": "OIDC-Client-ID",
+ "oidcIssuerURL": "OIDC-Aussteller-URL",
+ "oidcProvider": "OIDC-Anbieter",
+ "oidcEnabled": "OIDC-Anmeldung aktivieren",
+ "oidcLoginTip": "Einmalanmeldung über einen OpenID-Connect-Anbieter konfigurieren",
+ "oidcLogin": "OIDC-Anmeldung",
"disableAll": "Alle deaktivieren",
"bazaarKernelPlugin": "Kernel-Plugin",
"newItemTemplateDefaultTip": "Verwendet den Standardspeicherpfad für neue Dokumente im aktuellen Notizbuch",
@@ -2424,6 +2437,8 @@
"360": "Nach [%s] exportiert",
"361": "Der Benutzername des Veröffentlichungsdienst-Kontos darf nicht leer sein",
"362": "Der Benutzername des Veröffentlichungsdienst-Kontos ist bereits vergeben",
- "363": "Das Passwort des Veröffentlichungsdienst-Kontos muss mindestens 8 Zeichen lang sein"
+ "363": "Das Passwort des Veröffentlichungsdienst-Kontos muss mindestens 8 Zeichen lang sein",
+ "364": "Mit OIDC anmelden",
+ "365": "OIDC-Anmeldung fehlgeschlagen"
}
}
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index f555c16ff6..63dbac7501 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Invalid OIDC claim rule configuration",
+ "oidcClaimRulesTip": "JSON array; values within a rule use OR, while rules use AND",
+ "oidcClaimRules": "OIDC claim rules",
+ "oidcAllowAll": "Allow all authenticated users",
+ "oidcRedirectURL": "OIDC redirect URL",
+ "oidcScopes": "OIDC scopes",
+ "oidcClientSecret": "OIDC client secret",
+ "oidcClientID": "OIDC client ID",
+ "oidcIssuerURL": "OIDC issuer URL",
+ "oidcProvider": "OIDC provider",
+ "oidcEnabled": "Enable OIDC login",
+ "oidcLoginTip": "Configure single sign-on through an OpenID Connect provider",
+ "oidcLogin": "OIDC login",
"disableAll": "Disable all",
"bazaarKernelPlugin": "Kernel plugin",
"newItemTemplateDefaultTip": "Uses the current notebook's default save path for new documents",
@@ -2424,6 +2437,8 @@
"360": "Exported to [%s]",
"361": "The publish service account username cannot be empty",
"362": "The publish service account username is duplicated",
- "363": "The publish service account password must be at least 8 characters"
+ "363": "The publish service account password must be at least 8 characters",
+ "364": "Sign in with OIDC",
+ "365": "OIDC login failed"
}
}
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 4b87b3eb23..2e087d399e 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Configuración de reglas de notificaciones OIDC no válida",
+ "oidcClaimRulesTip": "Matriz JSON; los valores de una regla usan O y las reglas usan Y",
+ "oidcClaimRules": "Reglas de notificaciones OIDC",
+ "oidcAllowAll": "Permitir a todos los usuarios autenticados",
+ "oidcRedirectURL": "URL de redirección OIDC",
+ "oidcScopes": "Ámbitos OIDC",
+ "oidcClientSecret": "Secreto del cliente OIDC",
+ "oidcClientID": "ID de cliente OIDC",
+ "oidcIssuerURL": "URL del emisor OIDC",
+ "oidcProvider": "Proveedor OIDC",
+ "oidcEnabled": "Activar inicio de sesión OIDC",
+ "oidcLoginTip": "Configurar el inicio de sesión único mediante un proveedor OpenID Connect",
+ "oidcLogin": "Inicio de sesión OIDC",
"disableAll": "Desactivar todo",
"bazaarKernelPlugin": "Complemento del núcleo",
"newItemTemplateDefaultTip": "Usa la ruta de guardado predeterminada para documentos nuevos del cuaderno actual",
@@ -2424,6 +2437,8 @@
"360": "Se exportó a [%s]",
"361": "El nombre de usuario de la cuenta del servicio de publicación no puede estar vacío",
"362": "El nombre de usuario de la cuenta del servicio de publicación está duplicado",
- "363": "La contraseña de la cuenta del servicio de publicación debe tener al menos 8 caracteres"
+ "363": "La contraseña de la cuenta del servicio de publicación debe tener al menos 8 caracteres",
+ "364": "Iniciar sesión con OIDC",
+ "365": "Error al iniciar sesión con OIDC"
}
}
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index f527f16f6c..81097eafc7 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Configuration des règles de revendication OIDC non valide",
+ "oidcClaimRulesTip": "Tableau JSON ; les valeurs d’une règle utilisent OU, tandis que les règles utilisent ET",
+ "oidcClaimRules": "Règles de revendication OIDC",
+ "oidcAllowAll": "Autoriser tous les utilisateurs authentifiés",
+ "oidcRedirectURL": "URL de redirection OIDC",
+ "oidcScopes": "Portées OIDC",
+ "oidcClientSecret": "Secret client OIDC",
+ "oidcClientID": "ID client OIDC",
+ "oidcIssuerURL": "URL de l’émetteur OIDC",
+ "oidcProvider": "Fournisseur OIDC",
+ "oidcEnabled": "Activer la connexion OIDC",
+ "oidcLoginTip": "Configurer l’authentification unique via un fournisseur OpenID Connect",
+ "oidcLogin": "Connexion OIDC",
"disableAll": "Tout désactiver",
"bazaarKernelPlugin": "Plugin du noyau",
"newItemTemplateDefaultTip": "Utilise le chemin d’enregistrement par défaut des nouveaux documents du carnet actuel",
@@ -2424,6 +2437,8 @@
"360": "Exporté vers [%s]",
"361": "Le nom d'utilisateur du compte du service de publication ne peut pas être vide",
"362": "Le nom d'utilisateur du compte du service de publication est dupliqué",
- "363": "Le mot de passe du compte du service de publication doit comporter au moins 8 caractères"
+ "363": "Le mot de passe du compte du service de publication doit comporter au moins 8 caractères",
+ "364": "Se connecter avec OIDC",
+ "365": "Échec de la connexion OIDC"
}
}
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 3193845088..eb7350cd7b 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "תצורת כללי תביעות OIDC אינה תקינה",
+ "oidcClaimRulesTip": "מערך JSON; ערכים בתוך כלל משתמשים ב-OR וכללים משתמשים ב-AND",
+ "oidcClaimRules": "כללי תביעות OIDC",
+ "oidcAllowAll": "אפשר לכל המשתמשים המאומתים",
+ "oidcRedirectURL": "כתובת הפניה של OIDC",
+ "oidcScopes": "טווחי OIDC",
+ "oidcClientSecret": "סוד לקוח OIDC",
+ "oidcClientID": "מזהה לקוח OIDC",
+ "oidcIssuerURL": "כתובת מנפיק OIDC",
+ "oidcProvider": "ספק OIDC",
+ "oidcEnabled": "אפשר כניסה באמצעות OIDC",
+ "oidcLoginTip": "הגדר כניסה יחידה באמצעות ספק OpenID Connect",
+ "oidcLogin": "כניסה באמצעות OIDC",
"disableAll": "נטרל הכל",
"bazaarKernelPlugin": "תוסף ליבה",
"newItemTemplateDefaultTip": "שימוש בנתיב ברירת המחדל לשמירת מסמכים חדשים במחברת הנוכחית",
@@ -2424,6 +2437,8 @@
"360": "יוצא אל [%s]",
"361": "שם המשתמש של חשבון שירות הפרסום לא יכול להיות ריק",
"362": "שם המשתמש של חשבון שירות הפרסום כפול",
- "363": "סיסמת חשבון שירות הפרסום חייבת להכיל לפחות 8 תווים"
+ "363": "סיסמת חשבון שירות הפרסום חייבת להכיל לפחות 8 תווים",
+ "364": "כניסה באמצעות OIDC",
+ "365": "הכניסה באמצעות OIDC נכשלה"
}
}
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 01b4d651a4..ba1dce5288 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "OIDC क्लेम नियम कॉन्फ़िगरेशन अमान्य है",
+ "oidcClaimRulesTip": "JSON सरणी; एक नियम के मान OR और अलग नियम AND का उपयोग करते हैं",
+ "oidcClaimRules": "OIDC क्लेम नियम",
+ "oidcAllowAll": "सभी प्रमाणित उपयोगकर्ताओं को अनुमति दें",
+ "oidcRedirectURL": "OIDC रीडायरेक्ट URL",
+ "oidcScopes": "OIDC स्कोप",
+ "oidcClientSecret": "OIDC क्लाइंट सीक्रेट",
+ "oidcClientID": "OIDC क्लाइंट ID",
+ "oidcIssuerURL": "OIDC जारीकर्ता URL",
+ "oidcProvider": "OIDC प्रदाता",
+ "oidcEnabled": "OIDC लॉगिन सक्षम करें",
+ "oidcLoginTip": "OpenID Connect प्रदाता के माध्यम से एकल साइन-ऑन कॉन्फ़िगर करें",
+ "oidcLogin": "OIDC लॉगिन",
"disableAll": "सभी अक्षम करें",
"bazaarKernelPlugin": "कर्नेल प्लगइन",
"newItemTemplateDefaultTip": "वर्तमान नोटबुक के नए दस्तावेज़ों के लिए डिफ़ॉल्ट सहेजने के पथ का उपयोग करता है",
@@ -2424,6 +2437,8 @@
"360": "[%s] में निर्यात किया गया",
"361": "प्रकाशन सेवा खाते का उपयोगकर्ता नाम खाली नहीं हो सकता",
"362": "प्रकाशन सेवा खाते का उपयोगकर्ता नाम दोहराया गया है",
- "363": "प्रकाशन सेवा खाते का पासवर्ड कम से कम 8 अक्षरों का होना चाहिए"
+ "363": "प्रकाशन सेवा खाते का पासवर्ड कम से कम 8 अक्षरों का होना चाहिए",
+ "364": "OIDC से साइन इन करें",
+ "365": "OIDC लॉगिन विफल रहा"
}
}
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index c3cb563a34..da8360e502 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Konfigurasi aturan klaim OIDC tidak valid",
+ "oidcClaimRulesTip": "Larik JSON; nilai dalam satu aturan memakai ATAU, sedangkan antaraturan memakai DAN",
+ "oidcClaimRules": "Aturan klaim OIDC",
+ "oidcAllowAll": "Izinkan semua pengguna terautentikasi",
+ "oidcRedirectURL": "URL pengalihan OIDC",
+ "oidcScopes": "Cakupan OIDC",
+ "oidcClientSecret": "Rahasia klien OIDC",
+ "oidcClientID": "ID klien OIDC",
+ "oidcIssuerURL": "URL penerbit OIDC",
+ "oidcProvider": "Penyedia OIDC",
+ "oidcEnabled": "Aktifkan login OIDC",
+ "oidcLoginTip": "Konfigurasikan akses masuk tunggal melalui penyedia OpenID Connect",
+ "oidcLogin": "Login OIDC",
"disableAll": "Nonaktifkan semua",
"bazaarKernelPlugin": "Plugin kernel",
"newItemTemplateDefaultTip": "Menggunakan jalur penyimpanan bawaan untuk dokumen baru di buku catatan saat ini",
@@ -2424,6 +2437,8 @@
"360": "Diekspor ke [%s]",
"361": "Nama pengguna akun layanan publikasi tidak boleh kosong",
"362": "Nama pengguna akun layanan publikasi duplikat",
- "363": "Kata sandi akun layanan publikasi harus terdiri dari minimal 8 karakter"
+ "363": "Kata sandi akun layanan publikasi harus terdiri dari minimal 8 karakter",
+ "364": "Masuk dengan OIDC",
+ "365": "Login OIDC gagal"
}
}
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index d93502016f..b55d5af6bb 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Configurazione delle regole di attestazione OIDC non valida",
+ "oidcClaimRulesTip": "Array JSON; i valori in una regola usano OR, mentre le regole usano AND",
+ "oidcClaimRules": "Regole di attestazione OIDC",
+ "oidcAllowAll": "Consenti tutti gli utenti autenticati",
+ "oidcRedirectURL": "URL di reindirizzamento OIDC",
+ "oidcScopes": "Ambiti OIDC",
+ "oidcClientSecret": "Segreto client OIDC",
+ "oidcClientID": "ID client OIDC",
+ "oidcIssuerURL": "URL dell'emittente OIDC",
+ "oidcProvider": "Provider OIDC",
+ "oidcEnabled": "Abilita accesso OIDC",
+ "oidcLoginTip": "Configura il Single Sign-On tramite un provider OpenID Connect",
+ "oidcLogin": "Accesso OIDC",
"disableAll": "Disabilita tutto",
"bazaarKernelPlugin": "Plugin del kernel",
"newItemTemplateDefaultTip": "Usa il percorso di salvataggio predefinito per i nuovi documenti del taccuino corrente",
@@ -2424,6 +2437,8 @@
"360": "Esportato in [%s]",
"361": "Il nome utente dell'account del servizio di pubblicazione non può essere vuoto",
"362": "Il nome utente dell'account del servizio di pubblicazione è duplicato",
- "363": "La password dell'account del servizio di pubblicazione deve contenere almeno 8 caratteri"
+ "363": "La password dell'account del servizio di pubblicazione deve contenere almeno 8 caratteri",
+ "364": "Accedi con OIDC",
+ "365": "Accesso OIDC non riuscito"
}
}
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 3cc8672352..410a5197f1 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "OIDC クレームルールの設定が無効です",
+ "oidcClaimRulesTip": "JSON 配列。同一ルール内の値は OR、ルール間は AND として評価されます",
+ "oidcClaimRules": "OIDC クレームルール",
+ "oidcAllowAll": "認証済みのすべてのユーザーを許可",
+ "oidcRedirectURL": "OIDC リダイレクト URL",
+ "oidcScopes": "OIDC スコープ",
+ "oidcClientSecret": "OIDC クライアントシークレット",
+ "oidcClientID": "OIDC クライアント ID",
+ "oidcIssuerURL": "OIDC 発行者 URL",
+ "oidcProvider": "OIDC プロバイダー",
+ "oidcEnabled": "OIDC ログインを有効化",
+ "oidcLoginTip": "OpenID Connect プロバイダーによるシングルサインオンを設定します",
+ "oidcLogin": "OIDC ログイン",
"disableAll": "すべて無効化",
"bazaarKernelPlugin": "カーネルプラグイン",
"newItemTemplateDefaultTip": "現在のノートブックの新規ドキュメントのデフォルト保存先を使用します",
@@ -2424,6 +2437,8 @@
"360": "[%s] にエクスポートしました",
"361": "公開サービスのアカウントのユーザー名は空にできません",
"362": "公開サービスのアカウントのユーザー名が重複しています",
- "363": "公開サービスのアカウントのパスワードは 8 文字以上である必要があります"
+ "363": "公開サービスのアカウントのパスワードは 8 文字以上である必要があります",
+ "364": "OIDC でログイン",
+ "365": "OIDC ログインに失敗しました"
}
}
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 5cc09cde66..43a5581e9b 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "OIDC 클레임 규칙 구성이 올바르지 않습니다",
+ "oidcClaimRulesTip": "JSON 배열이며 한 규칙 안의 값은 OR, 규칙 사이는 AND로 평가됩니다",
+ "oidcClaimRules": "OIDC 클레임 규칙",
+ "oidcAllowAll": "인증된 모든 사용자 허용",
+ "oidcRedirectURL": "OIDC 리디렉션 URL",
+ "oidcScopes": "OIDC 범위",
+ "oidcClientSecret": "OIDC 클라이언트 비밀",
+ "oidcClientID": "OIDC 클라이언트 ID",
+ "oidcIssuerURL": "OIDC 발급자 URL",
+ "oidcProvider": "OIDC 공급자",
+ "oidcEnabled": "OIDC 로그인 사용",
+ "oidcLoginTip": "OpenID Connect 공급자를 통한 통합 로그인을 구성합니다",
+ "oidcLogin": "OIDC 로그인",
"disableAll": "모두 비활성화",
"bazaarKernelPlugin": "커널 플러그인",
"newItemTemplateDefaultTip": "현재 노트북의 새 문서 기본 저장 경로를 사용합니다",
@@ -2424,6 +2437,8 @@
"360": "[%s](으)로 내보내기 완료",
"361": "게시 서비스 계정의 사용자 이름은 비워 둘 수 없습니다",
"362": "게시 서비스 계정의 사용자 이름이 중복되었습니다",
- "363": "게시 서비스 계정의 비밀번호는 8자 이상이어야 합니다"
+ "363": "게시 서비스 계정의 비밀번호는 8자 이상이어야 합니다",
+ "364": "OIDC로 로그인",
+ "365": "OIDC 로그인 실패"
}
}
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index a0b4c2f053..6130dd4ebe 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Ongeldige configuratie van OIDC-claimregels",
+ "oidcClaimRulesTip": "JSON-array; waarden binnen een regel gebruiken OF en regels gebruiken EN",
+ "oidcClaimRules": "OIDC-claimregels",
+ "oidcAllowAll": "Alle geverifieerde gebruikers toestaan",
+ "oidcRedirectURL": "OIDC-omleidings-URL",
+ "oidcScopes": "OIDC-bereiken",
+ "oidcClientSecret": "OIDC-clientgeheim",
+ "oidcClientID": "OIDC-client-ID",
+ "oidcIssuerURL": "OIDC-uitgever-URL",
+ "oidcProvider": "OIDC-provider",
+ "oidcEnabled": "OIDC-aanmelding inschakelen",
+ "oidcLoginTip": "Eenmalige aanmelding configureren via een OpenID Connect-provider",
+ "oidcLogin": "OIDC-aanmelding",
"disableAll": "Alles uitschakelen",
"bazaarKernelPlugin": "Kernelplug-in",
"newItemTemplateDefaultTip": "Gebruikt het standaardopslagpad voor nieuwe documenten van het huidige notitieboek",
@@ -2424,6 +2437,8 @@
"360": "Geëxporteerd naar [%s]",
"361": "De gebruikersnaam van het publicatieservice-account mag niet leeg zijn",
"362": "De gebruikersnaam van het publicatieservice-account is gedupliceerd",
- "363": "Het wachtwoord van het publicatieservice-account moet minimaal 8 tekens bevatten"
+ "363": "Het wachtwoord van het publicatieservice-account moet minimaal 8 tekens bevatten",
+ "364": "Aanmelden met OIDC",
+ "365": "OIDC-aanmelding mislukt"
}
}
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 22df02c643..ff6646abe4 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Nieprawidłowa konfiguracja reguł oświadczeń OIDC",
+ "oidcClaimRulesTip": "Tablica JSON; wartości w regule są łączone operatorem LUB, a reguły operatorem I",
+ "oidcClaimRules": "Reguły oświadczeń OIDC",
+ "oidcAllowAll": "Zezwalaj wszystkim uwierzytelnionym użytkownikom",
+ "oidcRedirectURL": "Adres URL przekierowania OIDC",
+ "oidcScopes": "Zakresy OIDC",
+ "oidcClientSecret": "Sekret klienta OIDC",
+ "oidcClientID": "Identyfikator klienta OIDC",
+ "oidcIssuerURL": "Adres URL wystawcy OIDC",
+ "oidcProvider": "Dostawca OIDC",
+ "oidcEnabled": "Włącz logowanie OIDC",
+ "oidcLoginTip": "Skonfiguruj logowanie jednokrotne za pomocą dostawcy OpenID Connect",
+ "oidcLogin": "Logowanie OIDC",
"disableAll": "Wyłącz wszystko",
"bazaarKernelPlugin": "Wtyczka jądra",
"newItemTemplateDefaultTip": "Używa domyślnej ścieżki zapisu nowych dokumentów z bieżącego notatnika",
@@ -2424,6 +2437,8 @@
"360": "Wyeksportowano do [%s]",
"361": "Nazwa użytkownika konta usługi publikowania nie może być pusta",
"362": "Nazwa użytkownika konta usługi publikowania jest zduplikowana",
- "363": "Hasło konta usługi publikowania musi mieć co najmniej 8 znaków"
+ "363": "Hasło konta usługi publikowania musi mieć co najmniej 8 znaków",
+ "364": "Zaloguj się przez OIDC",
+ "365": "Logowanie OIDC nie powiodło się"
}
}
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 8da10f4123..3012cfb300 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Configuração inválida das regras de declaração OIDC",
+ "oidcClaimRulesTip": "Matriz JSON; os valores de uma regra usam OU, enquanto as regras usam E",
+ "oidcClaimRules": "Regras de declaração OIDC",
+ "oidcAllowAll": "Permitir todos os usuários autenticados",
+ "oidcRedirectURL": "URL de redirecionamento OIDC",
+ "oidcScopes": "Escopos OIDC",
+ "oidcClientSecret": "Segredo do cliente OIDC",
+ "oidcClientID": "ID do cliente OIDC",
+ "oidcIssuerURL": "URL do emissor OIDC",
+ "oidcProvider": "Provedor OIDC",
+ "oidcEnabled": "Ativar login OIDC",
+ "oidcLoginTip": "Configure o login único por meio de um provedor OpenID Connect",
+ "oidcLogin": "Login OIDC",
"disableAll": "Desativar tudo",
"bazaarKernelPlugin": "Plugin do kernel",
"newItemTemplateDefaultTip": "Usa o caminho de salvamento padrão para novos documentos do caderno atual",
@@ -2424,6 +2437,8 @@
"360": "Exportado para [%s]",
"361": "O nome de usuário da conta do serviço de publicação não pode ficar vazio",
"362": "O nome de usuário da conta do serviço de publicação está duplicado",
- "363": "A senha da conta do serviço de publicação deve ter pelo menos 8 caracteres"
+ "363": "A senha da conta do serviço de publicação deve ter pelo menos 8 caracteres",
+ "364": "Entrar com OIDC",
+ "365": "Falha no login OIDC"
}
}
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 07d78c2150..ed3ffff2c9 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Недопустимая конфигурация правил утверждений OIDC",
+ "oidcClaimRulesTip": "Массив JSON; значения внутри правила объединяются ИЛИ, а правила — И",
+ "oidcClaimRules": "Правила утверждений OIDC",
+ "oidcAllowAll": "Разрешить всех прошедших проверку пользователей",
+ "oidcRedirectURL": "URL-адрес перенаправления OIDC",
+ "oidcScopes": "Области OIDC",
+ "oidcClientSecret": "Секрет клиента OIDC",
+ "oidcClientID": "Идентификатор клиента OIDC",
+ "oidcIssuerURL": "URL-адрес издателя OIDC",
+ "oidcProvider": "Поставщик OIDC",
+ "oidcEnabled": "Включить вход через OIDC",
+ "oidcLoginTip": "Настроить единый вход через поставщика OpenID Connect",
+ "oidcLogin": "Вход через OIDC",
"disableAll": "Отключить все",
"bazaarKernelPlugin": "Плагин ядра",
"newItemTemplateDefaultTip": "Используется путь сохранения новых документов по умолчанию из текущего блокнота",
@@ -2424,6 +2437,8 @@
"360": "Экспортировано в [%s]",
"361": "Имя пользователя учетной записи службы публикации не может быть пустым",
"362": "Имя пользователя учетной записи службы публикации уже используется",
- "363": "Пароль учетной записи службы публикации должен содержать не менее 8 символов"
+ "363": "Пароль учетной записи службы публикации должен содержать не менее 8 символов",
+ "364": "Войти через OIDC",
+ "365": "Не удалось войти через OIDC"
}
}
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 9a0b670903..2417a27db5 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Neplatná konfigurácia pravidiel deklarácií OIDC",
+ "oidcClaimRulesTip": "Pole JSON; hodnoty v pravidle používajú ALEBO a pravidlá používajú A",
+ "oidcClaimRules": "Pravidlá deklarácií OIDC",
+ "oidcAllowAll": "Povoliť všetkých overených používateľov",
+ "oidcRedirectURL": "Adresa URL presmerovania OIDC",
+ "oidcScopes": "Rozsahy OIDC",
+ "oidcClientSecret": "Tajomstvo klienta OIDC",
+ "oidcClientID": "ID klienta OIDC",
+ "oidcIssuerURL": "Adresa URL vydavateľa OIDC",
+ "oidcProvider": "Poskytovateľ OIDC",
+ "oidcEnabled": "Povoliť prihlásenie OIDC",
+ "oidcLoginTip": "Nakonfigurujte jednotné prihlásenie cez poskytovateľa OpenID Connect",
+ "oidcLogin": "Prihlásenie OIDC",
"disableAll": "Zakázať všetko",
"bazaarKernelPlugin": "Doplnok jadra",
"newItemTemplateDefaultTip": "Použije predvolenú cestu ukladania nových dokumentov z aktuálneho zápisníka",
@@ -2424,6 +2437,8 @@
"360": "Exportované do [%s]",
"361": "Používateľské meno účtu služby publikovania nemôže byť prázdne",
"362": "Používateľské meno účtu služby publikovania je duplicitné",
- "363": "Heslo účtu služby publikovania musí mať aspoň 8 znakov"
+ "363": "Heslo účtu služby publikovania musí mať aspoň 8 znakov",
+ "364": "Prihlásiť sa cez OIDC",
+ "365": "Prihlásenie OIDC zlyhalo"
}
}
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 0dc30df8d6..aab557f05a 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "การกำหนดค่ากฎเคลม OIDC ไม่ถูกต้อง",
+ "oidcClaimRulesTip": "อาร์เรย์ JSON; ค่าในกฎเดียวกันใช้ OR และระหว่างกฎใช้ AND",
+ "oidcClaimRules": "กฎเคลม OIDC",
+ "oidcAllowAll": "อนุญาตผู้ใช้ที่ยืนยันตัวตนแล้วทั้งหมด",
+ "oidcRedirectURL": "URL เปลี่ยนเส้นทาง OIDC",
+ "oidcScopes": "ขอบเขต OIDC",
+ "oidcClientSecret": "รหัสลับไคลเอนต์ OIDC",
+ "oidcClientID": "ID ไคลเอนต์ OIDC",
+ "oidcIssuerURL": "URL ผู้ออก OIDC",
+ "oidcProvider": "ผู้ให้บริการ OIDC",
+ "oidcEnabled": "เปิดใช้การเข้าสู่ระบบ OIDC",
+ "oidcLoginTip": "กำหนดค่าการลงชื่อเข้าใช้ครั้งเดียวผ่านผู้ให้บริการ OpenID Connect",
+ "oidcLogin": "เข้าสู่ระบบ OIDC",
"disableAll": "ปิดใช้ทั้งหมด",
"bazaarKernelPlugin": "ปลั๊กอินเคอร์เนล",
"newItemTemplateDefaultTip": "ใช้เส้นทางบันทึกเริ่มต้นสำหรับเอกสารใหม่ของสมุดบันทึกปัจจุบัน",
@@ -2424,6 +2437,8 @@
"360": "ส่งออกไปยัง [%s] แล้ว",
"361": "ชื่อผู้ใช้ของบัญชีบริการเผยแพร่ต้องไม่ว่างเปล่า",
"362": "ชื่อผู้ใช้ของบัญชีบริการเผยแพร่ซ้ำกัน",
- "363": "รหัสผ่านของบัญชีบริการเผยแพร่ต้องมีอย่างน้อย 8 ตัวอักษร"
+ "363": "รหัสผ่านของบัญชีบริการเผยแพร่ต้องมีอย่างน้อย 8 ตัวอักษร",
+ "364": "ลงชื่อเข้าใช้ด้วย OIDC",
+ "365": "เข้าสู่ระบบ OIDC ไม่สำเร็จ"
}
}
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index c8eaf65b4a..1b8e76c17e 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Geçersiz OIDC talep kuralı yapılandırması",
+ "oidcClaimRulesTip": "JSON dizisi; bir kural içindeki değerler VEYA, kurallar ise VE kullanır",
+ "oidcClaimRules": "OIDC talep kuralları",
+ "oidcAllowAll": "Kimliği doğrulanmış tüm kullanıcılara izin ver",
+ "oidcRedirectURL": "OIDC yönlendirme URL'si",
+ "oidcScopes": "OIDC kapsamları",
+ "oidcClientSecret": "OIDC istemci gizli anahtarı",
+ "oidcClientID": "OIDC istemci kimliği",
+ "oidcIssuerURL": "OIDC sağlayıcı URL'si",
+ "oidcProvider": "OIDC sağlayıcısı",
+ "oidcEnabled": "OIDC girişini etkinleştir",
+ "oidcLoginTip": "Bir OpenID Connect sağlayıcısı üzerinden tek oturum açmayı yapılandırın",
+ "oidcLogin": "OIDC girişi",
"disableAll": "Tümünü devre dışı bırak",
"bazaarKernelPlugin": "Çekirdek eklentisi",
"newItemTemplateDefaultTip": "Geçerli not defterinin yeni belgeler için varsayılan kaydetme yolunu kullanır",
@@ -2424,6 +2437,8 @@
"360": "[%s] konumuna aktarıldı",
"361": "Yayınlama hizmeti hesabının kullanıcı adı boş olamaz",
"362": "Yayınlama hizmeti hesabının kullanıcı adı yineleniyor",
- "363": "Yayınlama hizmeti hesabının parolası en az 8 karakter olmalıdır"
+ "363": "Yayınlama hizmeti hesabının parolası en az 8 karakter olmalıdır",
+ "364": "OIDC ile giriş yap",
+ "365": "OIDC girişi başarısız oldu"
}
}
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 4664cf79d2..607238687c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "Неприпустима конфігурація правил тверджень OIDC",
+ "oidcClaimRulesTip": "Масив JSON; значення в правилі поєднуються АБО, а правила — І",
+ "oidcClaimRules": "Правила тверджень OIDC",
+ "oidcAllowAll": "Дозволити всіх автентифікованих користувачів",
+ "oidcRedirectURL": "URL-адреса переспрямування OIDC",
+ "oidcScopes": "Області OIDC",
+ "oidcClientSecret": "Секрет клієнта OIDC",
+ "oidcClientID": "Ідентифікатор клієнта OIDC",
+ "oidcIssuerURL": "URL-адреса видавця OIDC",
+ "oidcProvider": "Постачальник OIDC",
+ "oidcEnabled": "Увімкнути вхід через OIDC",
+ "oidcLoginTip": "Налаштуйте єдиний вхід через постачальника OpenID Connect",
+ "oidcLogin": "Вхід через OIDC",
"disableAll": "Вимкнути все",
"bazaarKernelPlugin": "Плагін ядра",
"newItemTemplateDefaultTip": "Використовується стандартний шлях збереження нових документів із поточного блокнота",
@@ -2424,6 +2437,8 @@
"360": "Експортовано до [%s]",
"361": "Ім'я користувача облікового запису служби публікації не може бути порожнім",
"362": "Ім'я користувача облікового запису служби публікації дублюється",
- "363": "Пароль облікового запису служби публікації має містити щонайменше 8 символів"
+ "363": "Пароль облікового запису служби публікації має містити щонайменше 8 символів",
+ "364": "Увійти через OIDC",
+ "365": "Не вдалося ввійти через OIDC"
}
}
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index b1bd0ee6df..ee4fbb0482 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "OIDC 声明规则配置无效",
+ "oidcClaimRulesTip": "JSON 数组;同一规则内的值为或关系,不同规则之间为与关系",
+ "oidcClaimRules": "OIDC 声明规则",
+ "oidcAllowAll": "允许所有已认证用户",
+ "oidcRedirectURL": "OIDC 回调地址",
+ "oidcScopes": "OIDC 授权范围",
+ "oidcClientSecret": "OIDC 客户端密钥",
+ "oidcClientID": "OIDC 客户端 ID",
+ "oidcIssuerURL": "OIDC 签发者地址",
+ "oidcProvider": "OIDC 提供商",
+ "oidcEnabled": "启用 OIDC 登录",
+ "oidcLoginTip": "通过 OpenID Connect 提供商配置单点登录",
+ "oidcLogin": "OIDC 登录",
"disableAll": "全部禁用",
"bazaarKernelPlugin": "内核插件",
"newItemTemplateDefaultTip": "使用当前笔记本的新建文档默认存放路径",
@@ -2424,6 +2437,8 @@
"360": "已导出到 [%s]",
"361": "发布服务账户用户名不能为空",
"362": "发布服务账户用户名重复",
- "363": "发布服务账户密码长度不能少于 8 个字符"
+ "363": "发布服务账户密码长度不能少于 8 个字符",
+ "364": "使用 OIDC 登录",
+ "365": "OIDC 登录失败"
}
}
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 01ba9d6a46..21d01ac697 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,17 @@
{
+ "oidcConfigInvalid": "OIDC 宣告規則設定無效",
+ "oidcClaimRulesTip": "JSON 陣列;同一規則內的值為或關係,不同規則之間為與關係",
+ "oidcClaimRules": "OIDC 宣告規則",
+ "oidcAllowAll": "允許所有已驗證使用者",
+ "oidcRedirectURL": "OIDC 回呼位址",
+ "oidcScopes": "OIDC 授權範圍",
+ "oidcClientSecret": "OIDC 用戶端密鑰",
+ "oidcClientID": "OIDC 用戶端 ID",
+ "oidcIssuerURL": "OIDC 簽發者位址",
+ "oidcProvider": "OIDC 提供者",
+ "oidcEnabled": "啟用 OIDC 登入",
+ "oidcLoginTip": "透過 OpenID Connect 提供者設定單一登入",
+ "oidcLogin": "OIDC 登入",
"disableAll": "全部禁用",
"bazaarKernelPlugin": "Kernel 插件",
"newItemTemplateDefaultTip": "使用目前筆記本的新建文檔預設存放路徑",
@@ -2424,6 +2437,8 @@
"360": "已匯出至 [%s]",
"361": "發佈服務帳戶用戶名不能為空",
"362": "發佈服務帳戶用戶名重複",
- "363": "發佈服務帳戶密碼長度不能少於 8 個字元"
+ "363": "發佈服務帳戶密碼長度不能少於 8 個字元",
+ "364": "使用 OIDC 登入",
+ "365": "OIDC 登入失敗"
}
}
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index b46f8e7852..8ee789bd03 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -66,6 +66,16 @@ const registerAccessAuthGroup = (tab: SettingTabBuilder) => {
save: (value) => sendAppSetting("system.lockScreenMode", value),
});
}
+ if (!window.siyuan.config.readonly && !onWeb) {
+ group.button({
+ id: "oidcConfig",
+ title: window.siyuan.languages.oidcLogin,
+ desc: window.siyuan.languages.oidcLoginTip,
+ label: window.siyuan.languages.config,
+ icon: "iconKey",
+ afterMount: mountOIDCButton,
+ });
+ }
group.text("api.token", {
title: window.siyuan.languages.about13,
desc: window.siyuan.languages.about14.replace("${token}", window.siyuan.config.api.token),
@@ -74,6 +84,58 @@ const registerAccessAuthGroup = (tab: SettingTabBuilder) => {
});
};
+const mountOIDCButton = (root: HTMLElement) => {
+ root.querySelector("#oidcConfig")?.addEventListener("click", () => {
+ const config = window.siyuan.config.oidc;
+ const escape = (value: string) => Lute.EscapeHTMLStr(value);
+ const dialog = new Dialog({
+ title: window.siyuan.languages.oidcLogin,
+ content: `<div class="b3-dialog__content" id="oidcConfigForm">
+ <label class="fn__flex b3-label"><span class="fn__flex-1">${window.siyuan.languages.oidcEnabled}</span><input type="checkbox" data-field="enabled" class="b3-switch"${config.enabled ? " checked" : ""}></label>
+ <label class="b3-label">${window.siyuan.languages.oidcProvider}<select data-field="provider" class="b3-select fn__block"><option value="custom"${config.provider === "custom" ? " selected" : ""}>${window.siyuan.languages.custom}</option><option value="google"${config.provider === "google" ? " selected" : ""}>Google</option><option value="microsoft"${config.provider === "microsoft" ? " selected" : ""}>Microsoft</option><option value="github"${config.provider === "github" ? " selected" : ""}>GitHub</option></select></label>
+ <label class="b3-label">${window.siyuan.languages.oidcIssuerURL}<input data-field="issuerURL" class="b3-text-field fn__block" value="${escape(config.issuerURL)}"></label>
+ <label class="b3-label">${window.siyuan.languages.oidcClientID}<input data-field="clientID" class="b3-text-field fn__block" value="${escape(config.clientID)}"></label>
+ <label class="b3-label">${window.siyuan.languages.oidcClientSecret}<input data-field="clientSecret" type="password" class="b3-text-field fn__block" placeholder="${config.clientSecretConfigured ? "********" : ""}"></label>
+ <label class="fn__flex b3-label"><span class="fn__flex-1">${window.siyuan.languages.clear}</span><input type="checkbox" data-field="clearClientSecret" class="b3-switch"></label>
+ <label class="b3-label">${window.siyuan.languages.oidcScopes}<input data-field="scopes" class="b3-text-field fn__block" value="${escape(config.scopes.join(", "))}"></label>
+ <label class="b3-label">${window.siyuan.languages.oidcRedirectURL}<input data-field="redirectURL" class="b3-text-field fn__block" value="${escape(config.redirectURL)}"></label>
+ <label class="fn__flex b3-label"><span class="fn__flex-1">${window.siyuan.languages.oidcAllowAll}</span><input type="checkbox" data-field="allowAll" class="b3-switch"${config.allowAll ? " checked" : ""}></label>
+ <label class="b3-label">${window.siyuan.languages.oidcClaimRules}<textarea data-field="claimRules" class="b3-text-field fn__block" rows="6">${escape(JSON.stringify(config.claimRules, null, 2))}</textarea><div class="b3-label__text">${window.siyuan.languages.oidcClaimRulesTip}</div></label>
+</div>
+<div class="b3-dialog__action"><button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div><button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button></div>`,
+ width: isMobile() ? "92vw" : "620px",
+ });
+ const form = dialog.element.querySelector<HTMLElement>("#oidcConfigForm");
+ const buttons = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-dialog__action .b3-button");
+ buttons[0].addEventListener("click", () => dialog.destroy());
+ buttons[1].addEventListener("click", () => {
+ try {
+ const field = <T extends HTMLElement>(name: string) => form.querySelector<T>(`[data-field="${name}"]`);
+ const claimRules = JSON.parse(field<HTMLTextAreaElement>("claimRules").value) as Config.IOIDCClaimRule[];
+ const nextConfig: Config.IOIDC = {
+ enabled: field<HTMLInputElement>("enabled").checked,
+ provider: field<HTMLSelectElement>("provider").value as Config.IOIDC["provider"],
+ issuerURL: field<HTMLInputElement>("issuerURL").value,
+ clientID: field<HTMLInputElement>("clientID").value,
+ clientSecret: field<HTMLInputElement>("clientSecret").value,
+ clientSecretConfigured: Boolean(field<HTMLInputElement>("clientSecret").value) ||
+ config.clientSecretConfigured && !field<HTMLInputElement>("clearClientSecret").checked,
+ scopes: field<HTMLInputElement>("scopes").value.split(/[ ,]+/).filter(Boolean),
+ redirectURL: field<HTMLInputElement>("redirectURL").value,
+ allowAll: field<HTMLInputElement>("allowAll").checked,
+ claimRules,
+ };
+ fetchPost("/api/system/setOIDC", nextConfig, (response) => {
+ window.siyuan.config.oidc = response.data;
+ dialog.destroy();
+ });
+ } catch (error) {
+ showMessage(window.siyuan.languages.oidcConfigInvalid, 6000, "error");
+ }
+ });
+ });
+};
+
const mountAuthCodeButton = (root: HTMLElement) => {
root.querySelector("#authCode")?.addEventListener("click", () => {
const dialog = new Dialog({
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 3bfa28c0df..6bc92b3dcc 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -25,6 +25,7 @@ declare namespace Config {
* Access authorization code
*/
accessAuthCode: TAccessAuthCode;
+ oidc: IOIDC;
account: IAccount;
ai: IAI;
api: IAPI;
@@ -114,6 +115,25 @@ declare namespace Config {
*/
export type TAccessAuthCode = "" | "*******";
+ export interface IOIDCClaimRule {
+ claim: string;
+ operator: "equals" | "contains";
+ values: string[];
+ }
+
+ export interface IOIDC {
+ enabled: boolean;
+ provider: "custom" | "google" | "microsoft" | "github";
+ issuerURL: string;
+ clientID: string;
+ clientSecret: string;
+ clientSecretConfigured: boolean;
+ scopes: string[];
+ redirectURL: string;
+ allowAll: boolean;
+ claimRules: IOIDCClaimRule[];
+ }
+
/**
* Account configuration
*/
diff --git a/app/stage/auth.html b/app/stage/auth.html
index 15e702e5a4..47c5a41f49 100644
--- a/app/stage/auth.html
+++ b/app/stage/auth.html
@@ -180,16 +180,19 @@
<div style="-webkit-app-region: drag;height: 32px;width: 100%;position: absolute;top: 0;"></div>
<div style="position: relative;z-index: 2;text-align: center">
<h1 style="margin-bottom: 48px;color:var(--b3-theme-on-background)">{{.workspace}}</h1>
- <input class="b3-text-field" id="authCode" type="password" placeholder="{{.l0}}"/><br>
- <div style="position: relative;width: 240px;margin: 8px auto 0;display: none">
- <img id="captchaImg" style="top: 1px;position: absolute;height: 26px;right: 1px;cursor: pointer">
- <input id="captcha" class="b3-text-field" placeholder="{{.l3}}">
+ <div id="authCodePanel"{{if not .accessAuthCodeEnabled}} style="display: none"{{end}}>
+ <input class="b3-text-field" id="authCode" type="password" placeholder="{{.l0}}"/><br>
+ <div style="position: relative;width: 240px;margin: 8px auto 0;display: none">
+ <img id="captchaImg" style="top: 1px;position: absolute;height: 26px;right: 1px;cursor: pointer">
+ <input id="captcha" class="b3-text-field" placeholder="{{.l3}}">
+ </div>
</div>
<div style="width: 240px; margin: 8px auto; text-align: left; display: flex; align-items: center;">
<input type="checkbox" id="rememberMe" style="margin-right: 8px;">
<label for="rememberMe" style="color: var(--b3-theme-on-surface); font-size: 14px;">{{.l10}}</label>
</div>
- <button class="b3-button" onclick="submitAuth()">{{.l1}}</button>
+ {{if .accessAuthCodeEnabled}}<button class="b3-button" onclick="submitAuth()">{{.l1}}</button>{{end}}
+ {{if .oidcEnabled}}<button class="b3-button" id="oidcLogin" onclick="startOIDC()">{{.l12}}</button>{{end}}
<div class="ft__on-surface">
{{.l2}}
</div>
@@ -497,6 +500,102 @@
}, 6000)
}
+ const showOIDCError = (message) => {
+ const messageElement = document.querySelector('#message')
+ messageElement.classList.add('b3-snackbar--show')
+ messageElement.firstElementChild.textContent = String(message || '{{.l13}}')
+ setTimeout(() => {
+ messageElement.classList.remove('b3-snackbar--show')
+ messageElement.firstElementChild.textContent = ''
+ }, 6000)
+ }
+ window.handleOIDCAuthError = showOIDCError
+
+ let oidcPollTimer
+ const pollOIDC = (pollToken) => {
+ clearInterval(oidcPollTimer)
+ oidcPollTimer = setInterval(() => {
+ fetch('/api/system/oidc/poll', {
+ method: 'POST',
+ body: JSON.stringify({pollToken}),
+ }).then((response) => response.json()).then((response) => {
+ if (response.code !== 0) {
+ clearInterval(oidcPollTimer)
+ showOIDCError(response.msg)
+ return
+ }
+ if (response.data.status === 'completed') {
+ clearInterval(oidcPollTimer)
+ window.location.href = response.data.to || toPath
+ }
+ }).catch(() => {
+ clearInterval(oidcPollTimer)
+ showOIDCError('{{.l13}}')
+ })
+ }, 1000)
+ }
+
+ const handleOIDCCallback = (callbackURL) => {
+ fetch('/api/system/oidc/mobileCallback', {
+ method: 'POST',
+ body: JSON.stringify({callbackURL}),
+ }).then((response) => response.json()).then((response) => {
+ if (response.code === 0) {
+ window.location.href = response.data.to || toPath
+ } else {
+ showOIDCError(response.msg)
+ }
+ }).catch(() => showOIDCError('{{.l13}}'))
+ }
+ window.handleOIDCCallback = handleOIDCCallback
+ window.handleOidcCallbackLink = handleOIDCCallback
+
+ const startOIDC = () => {
+ let flow = 'web'
+ if (window.JSAndroid || window.JSHarmony || window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.openAuthURL) {
+ flow = 'mobile'
+ } else {
+ try {
+ if (require('electron')) {
+ flow = 'desktop'
+ }
+ } catch (e) {
+ // 浏览器使用当前页面完成回调
+ }
+ }
+ const button = document.getElementById('oidcLogin')
+ button.disabled = true
+ fetch('/api/system/oidc/start', {
+ method: 'POST',
+ body: JSON.stringify({flow, to: toPath, rememberMe: document.getElementById('rememberMe').checked}),
+ }).then((response) => response.json()).then((response) => {
+ button.disabled = false
+ if (response.code !== 0) {
+ showOIDCError(response.msg)
+ return
+ }
+ if (flow === 'mobile') {
+ if (window.JSAndroid) {
+ window.JSAndroid.openAuthURL(response.data.authURL)
+ } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.openAuthURL) {
+ window.webkit.messageHandlers.openAuthURL.postMessage(response.data.authURL)
+ } else {
+ window.JSHarmony.openAuthURL(response.data.authURL)
+ }
+ return
+ }
+ if (flow === 'desktop') {
+ require('electron').shell.openExternal(response.data.authURL)
+ pollOIDC(response.data.pollToken)
+ return
+ }
+ window.location.href = response.data.authURL
+ }).catch(() => {
+ button.disabled = false
+ showOIDCError('{{.l13}}')
+ })
+ }
+
const submitAuth = () => {
const inputElement = document.getElementById('authCode')
const captchaElement = document.getElementById('captcha')
@@ -574,6 +673,18 @@
} catch (e) {
// console.log(e)
}
+ if (window.JSAndroid && window.JSAndroid.getOIDCCallback) {
+ const callbackURL = window.JSAndroid.getOIDCCallback()
+ if (callbackURL) {
+ handleOIDCCallback(callbackURL)
+ }
+ }
+ if (window.JSHarmony && window.JSHarmony.getOIDCCallback) {
+ const callbackURL = window.JSHarmony.getOIDCCallback()
+ if (callbackURL) {
+ handleOIDCCallback(callbackURL)
+ }
+ }
const inputElement = document.getElementById('authCode')
const captchaElement = document.getElementById('captcha')
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 35f5130168..1334c069b6 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -41,6 +41,10 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/system/loginAuth", model.LoginAuth)
ginServer.Handle("POST", "/api/system/logoutAuth", model.LogoutAuth)
ginServer.Handle("GET", "/api/system/getCaptcha", model.GetCaptcha)
+ ginServer.Handle("POST", "/api/system/oidc/start", model.OIDCStart)
+ ginServer.Handle("GET", "/api/system/oidc/callback", model.OIDCCallback)
+ ginServer.Handle("POST", "/api/system/oidc/mobileCallback", model.OIDCMobileCallback)
+ ginServer.Handle("POST", "/api/system/oidc/poll", model.OIDCPoll)
ginServer.Handle("GET", "/api/ai/mcp/oauth/callback/:flowID", mcpOAuthCallback)
// 需要鉴权
@@ -50,6 +54,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/system/addCustomEmoji", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, addCustomEmoji)
ginServer.Handle("POST", "/api/system/setAPIToken", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAPIToken)
ginServer.Handle("POST", "/api/system/setAccessAuthCode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAccessAuthCode)
+ ginServer.Handle("POST", "/api/system/setOIDC", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setOIDC)
ginServer.Handle("POST", "/api/system/setFollowSystemLockScreen", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setFollowSystemLockScreen)
ginServer.Handle("POST", "/api/system/setNetworkServe", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNetworkServe)
ginServer.Handle("POST", "/api/system/setNetworkServeTLS", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNetworkServeTLS)
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 07d06878ab..8a75780696 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -891,6 +891,38 @@ func setAccessAuthCode(c *gin.Context) {
return
}
+func setOIDC(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ config := conf.NewOIDC()
+ if err := c.ShouldBindJSON(config); err != nil {
+ ret.Code = -1
+ ret.Msg = "invalid OIDC configuration"
+ return
+ }
+ currentConfig := model.Conf.GetOIDC()
+ if config.ClientSecret == "" && config.ClientSecretConfigured {
+ config.ClientSecret = currentConfig.ClientSecret
+ }
+ config.Normalize()
+ if config.Enabled {
+ if err := model.ValidateOIDCConfiguration(config); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ }
+ model.Conf.SetOIDC(config)
+ masked, err := model.GetMaskedConf()
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = masked.OIDC
+}
+
func setFollowSystemLockScreen(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/conf/oidc.go b/kernel/conf/oidc.go
new file mode 100644
index 0000000000..c3504331b6
--- /dev/null
+++ b/kernel/conf/oidc.go
@@ -0,0 +1,114 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package conf
+
+import (
+ "encoding/hex"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ OIDCProviderCustom = "custom"
+ OIDCProviderGoogle = "google"
+ OIDCProviderMicrosoft = "microsoft"
+ OIDCProviderGitHub = "github"
+
+ OIDCClaimOperatorEquals = "equals"
+ OIDCClaimOperatorContains = "contains"
+)
+
+// OIDC 保存工作空间的 OpenID Connect 登录配置。
+type OIDC struct {
+ Enabled bool `json:"enabled"`
+ Provider string `json:"provider"`
+ IssuerURL string `json:"issuerURL"`
+ ClientID string `json:"clientID"`
+ ClientSecret string `json:"clientSecret"`
+ ClientSecretConfigured bool `json:"clientSecretConfigured"`
+ Scopes []string `json:"scopes"`
+ RedirectURL string `json:"redirectURL"`
+ AllowAll bool `json:"allowAll"`
+ ClaimRules []*OIDCClaimRule `json:"claimRules"`
+}
+
+// OIDCClaimRule 描述一条身份声明准入规则。同一规则的 Values 为或关系,不同规则之间为与关系。
+type OIDCClaimRule struct {
+ Claim string `json:"claim"`
+ Operator string `json:"operator"`
+ Values []string `json:"values"`
+}
+
+func NewOIDC() *OIDC {
+ return &OIDC{
+ Provider: OIDCProviderCustom,
+ Scopes: []string{"openid", "profile", "email"},
+ ClaimRules: []*OIDCClaimRule{},
+ }
+}
+
+func (o *OIDC) Normalize() {
+ if o == nil {
+ return
+ }
+ o.Provider = strings.ToLower(strings.TrimSpace(o.Provider))
+ o.IssuerURL = strings.TrimRight(strings.TrimSpace(o.IssuerURL), "/")
+ o.ClientID = strings.TrimSpace(o.ClientID)
+ if o.ClientSecret != "" {
+ o.ClientSecretConfigured = true
+ }
+ o.RedirectURL = strings.TrimSpace(o.RedirectURL)
+ if len(o.Scopes) == 0 {
+ o.Scopes = []string{"openid", "profile", "email"}
+ }
+ for i, scope := range o.Scopes {
+ o.Scopes[i] = strings.TrimSpace(scope)
+ }
+ for _, rule := range o.ClaimRules {
+ if rule == nil {
+ continue
+ }
+ rule.Claim = strings.TrimSpace(rule.Claim)
+ rule.Operator = strings.ToLower(strings.TrimSpace(rule.Operator))
+ for i, value := range rule.Values {
+ rule.Values[i] = strings.TrimSpace(value)
+ }
+ }
+}
+
+func (o *OIDC) EncryptClientSecret() {
+ if o == nil || o.ClientSecret == "" {
+ return
+ }
+ o.ClientSecret = util.AESEncrypt(o.ClientSecret)
+}
+
+func (o *OIDC) DecryptClientSecret() {
+ if o == nil || o.ClientSecret == "" {
+ return
+ }
+ original := o.ClientSecret
+ encrypted, err := hex.DecodeString(original)
+ if err != nil || len(encrypted) == 0 || len(encrypted)%16 != 0 {
+ return
+ }
+ defer func() {
+ if recover() != nil {
+ o.ClientSecret = original
+ }
+ }()
+ decrypted := util.AESDecrypt(o.ClientSecret)
+ if decrypted == nil {
+ return
+ }
+ if plain, err := hex.DecodeString(string(decrypted)); err == nil {
+ o.ClientSecret = string(plain)
+ }
+}
diff --git a/kernel/conf/oidc_test.go b/kernel/conf/oidc_test.go
new file mode 100644
index 0000000000..db03f31463
--- /dev/null
+++ b/kernel/conf/oidc_test.go
@@ -0,0 +1,33 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package conf
+
+import "testing"
+
+func TestOIDCClientSecretEncryption(t *testing.T) {
+ config := &OIDC{ClientSecret: "client-secret"}
+ config.EncryptClientSecret()
+ if config.ClientSecret == "" || config.ClientSecret == "client-secret" {
+ t.Fatal("OIDC client secret was not encrypted")
+ }
+ config.DecryptClientSecret()
+ if config.ClientSecret != "client-secret" {
+ t.Fatalf("OIDC client secret did not round trip: %q", config.ClientSecret)
+ }
+}
+
+func TestOIDCClientSecretDecryptPreservesPlaintextAndMalformedValues(t *testing.T) {
+ for _, value := range []string{"plain-client-secret", "00000000000000000000000000000000"} {
+ config := &OIDC{ClientSecret: value}
+ config.DecryptClientSecret()
+ if config.ClientSecret != value {
+ t.Fatalf("malformed or plaintext client secret was changed: %q", config.ClientSecret)
+ }
+ }
+}
diff --git a/kernel/go.mod b/kernel/go.mod
index 2d014f4311..c292f9626e 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -18,6 +18,7 @@ require (
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be
+ github.com/coreos/go-oidc/v3 v3.16.0
github.com/denisbrodbeck/machineid v1.0.1
github.com/dgraph-io/ristretto v0.2.0
github.com/disintegration/imaging v1.6.2
@@ -142,6 +143,7 @@ require (
github.com/ebitengine/purego v0.10.2 // indirect
github.com/fatih/set v0.2.1 // indirect
github.com/gigawattio/window v0.0.0-20180317192513-0f5467e35573 // indirect
+ github.com/go-jose/go-jose/v4 v4.1.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.28.0 // indirect
diff --git a/kernel/go.sum b/kernel/go.sum
index b86fe0a6c2..5431b975f8 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -107,6 +107,8 @@ github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be h1:J5BL2kskAlV9ckgEsNQXscjIaLiOYiZ75d4e94E6dcQ=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be/go.mod h1:mk5IQ+Y0ZeO87b858TlA645sVcEcbiX6YqP98kt+7+w=
+github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow=
+github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -173,6 +175,8 @@ github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko
github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
+github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
+github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
diff --git a/kernel/model/auth_session.go b/kernel/model/auth_session.go
new file mode 100644
index 0000000000..317c7bded0
--- /dev/null
+++ b/kernel/model/auth_session.go
@@ -0,0 +1,68 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package model
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "net/http"
+
+ "github.com/88250/gulu"
+ ginSessions "github.com/gin-contrib/sessions"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func IsAccessAuthRequired() bool {
+ return Conf.AccessAuthCode != "" || Conf.GetOIDC().Enabled
+}
+
+func IsWorkspaceSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool {
+ if workspaceSession == nil {
+ return false
+ }
+ if Conf.AccessAuthCode != "" && util.AuthCodeEquals(Conf.AccessAuthCode, workspaceSession.AccessAuthCode) {
+ return true
+ }
+ return Conf.GetOIDC().Enabled && workspaceSession.OIDCSessionVersion != "" &&
+ hmac.Equal([]byte(workspaceSession.OIDCSessionVersion), []byte(oidcSessionVersion()))
+}
+
+func applyAuthenticatedSession(c *gin.Context, workspaceSession *util.WorkspaceSession, rememberMe bool) {
+ workspaceSession.OIDCSessionVersion = oidcSessionVersion()
+ maxAge := 0
+ if rememberMe {
+ maxAge = 60 * 60 * 24 * 30
+ }
+ ginSessions.Default(c).Options(ginSessions.Options{
+ Path: "/",
+ Secure: util.SSL,
+ MaxAge: maxAge,
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ })
+}
+
+func oidcSessionVersion() string {
+ if Conf == nil || Conf.CookieKey == "" {
+ return ""
+ }
+ config := Conf.GetOIDC()
+ if !config.Enabled {
+ return ""
+ }
+ data, err := gulu.JSON.MarshalJSON(config)
+ if err != nil {
+ return ""
+ }
+ mac := hmac.New(sha256.New, []byte(Conf.CookieKey))
+ _, _ = mac.Write(data)
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 01043bed26..219a0754ed 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -64,6 +64,7 @@ type AppConf struct {
ReadOnly bool `json:"readonly"` // 是否是以只读模式运行
ServerAddrs []string `json:"serverAddrs"` // 本地服务器地址列表
AccessAuthCode string `json:"accessAuthCode"` // 锁屏密码
+ OIDC *conf.OIDC `json:"oidc"` // OpenID Connect 登录
System *conf.System `json:"system"` // 系统配置
Keymap *conf.Keymap `json:"keymap"` // 快捷键配置
Sync *conf.Sync `json:"sync"` // 同步配置
@@ -94,11 +95,51 @@ type AppConf struct {
func NewAppConf() *AppConf {
return &AppConf{
LogLevel: "debug",
+ OIDC: conf.NewOIDC(),
m: &sync.RWMutex{},
userLock: &sync.RWMutex{},
}
}
+func applyOIDCEnvironment(config *conf.OIDC) {
+ if config == nil {
+ return
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_ENABLED"); ok {
+ config.Enabled, _ = strconv.ParseBool(value)
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_PROVIDER"); ok {
+ config.Provider = value
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_ISSUER_URL"); ok {
+ config.IssuerURL = value
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_CLIENT_ID"); ok {
+ config.ClientID = value
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_CLIENT_SECRET"); ok {
+ config.ClientSecret = value
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_SCOPES"); ok {
+ config.Scopes = strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ' ' })
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_REDIRECT_URL"); ok {
+ config.RedirectURL = value
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_ALLOW_ALL"); ok {
+ config.AllowAll, _ = strconv.ParseBool(value)
+ }
+ if value, ok := os.LookupEnv("SIYUAN_OIDC_CLAIM_RULES"); ok {
+ rules := []*conf.OIDCClaimRule{}
+ if err := gulu.JSON.UnmarshalJSON([]byte(value), &rules); err != nil {
+ config.ClaimRules = nil
+ logging.LogErrorf("parse SIYUAN_OIDC_CLAIM_RULES failed: %s", err)
+ } else {
+ config.ClaimRules = rules
+ }
+ }
+}
+
func (conf *AppConf) GetMCPOAuth() string {
conf.m.RLock()
defer conf.m.RUnlock()
@@ -112,6 +153,34 @@ func (conf *AppConf) SetMCPOAuth(value string) {
conf.Save()
}
+func (appConf *AppConf) GetOIDC() *conf.OIDC {
+ appConf.m.RLock()
+ defer appConf.m.RUnlock()
+ if appConf.OIDC == nil {
+ return conf.NewOIDC()
+ }
+ ret := *appConf.OIDC
+ ret.Scopes = append([]string{}, appConf.OIDC.Scopes...)
+ ret.ClaimRules = make([]*conf.OIDCClaimRule, 0, len(appConf.OIDC.ClaimRules))
+ for _, rule := range appConf.OIDC.ClaimRules {
+ if rule == nil {
+ ret.ClaimRules = append(ret.ClaimRules, nil)
+ continue
+ }
+ clonedRule := *rule
+ clonedRule.Values = append([]string{}, rule.Values...)
+ ret.ClaimRules = append(ret.ClaimRules, &clonedRule)
+ }
+ return &ret
+}
+
+func (appConf *AppConf) SetOIDC(config *conf.OIDC) {
+ appConf.m.Lock()
+ appConf.OIDC = config
+ appConf.m.Unlock()
+ appConf.Save()
+}
+
func (conf *AppConf) SetAI(ai *conf.AI) {
conf.m.Lock()
conf.AI = ai
@@ -670,6 +739,14 @@ func InitConf() {
Conf.AI.Normalize()
Conf.AI.ReconcileModelIDs()
+ if nil == Conf.OIDC {
+ Conf.OIDC = conf.NewOIDC()
+ } else {
+ Conf.OIDC.DecryptClientSecret()
+ }
+ applyOIDCEnvironment(Conf.OIDC)
+ Conf.OIDC.Normalize()
+
if nil == Conf.Secrets {
Conf.Secrets = conf.NewSecrets()
} else {
@@ -736,6 +813,19 @@ func InitConf() {
writeCookieKey(Conf.CookieKey)
}
+ if util.ContainerDocker == util.Container && Conf.AccessAuthCode == "" && !util.SiYuanAccessAuthCodeBypass {
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err != nil {
+ fmt.Println("the access authorization code or a valid OIDC configuration must be set when deploying via Docker")
+ fmt.Println("set SIYUAN_ACCESS_AUTH_CODE, configure OIDC, or explicitly set SIYUAN_ACCESS_AUTH_CODE_BYPASS=true")
+ logging.LogErrorf("Docker access authentication configuration is invalid: %s", err)
+ os.Exit(logging.ExitCodeSecurityRisk)
+ }
+ if _, err := validatePublicOIDCRedirectURL(Conf.OIDC.RedirectURL); err != nil {
+ logging.LogErrorf("Docker OIDC redirect configuration is invalid: %s", err)
+ os.Exit(logging.ExitCodeSecurityRisk)
+ }
+ }
+
Conf.Save()
// 安全模式:渲染进程崩溃恢复后由桌面端主进程通过 --safe-mode 注入。
@@ -1042,6 +1132,9 @@ func (conf *AppConf) Save() {
if snapshot.AI != nil {
snapshot.AI.EncryptAPIKeys()
}
+ if snapshot.OIDC != nil {
+ snapshot.OIDC.EncryptClientSecret()
+ }
if snapshot.Secrets != nil {
snapshot.Secrets.Encrypt()
}
@@ -1241,6 +1334,10 @@ func GetMaskedConf() (ret *AppConf, err error) {
if "" != ret.AccessAuthCode {
ret.AccessAuthCode = MaskedAccessAuthCode
}
+ if ret.OIDC != nil {
+ ret.OIDC.ClientSecretConfigured = ret.OIDC.ClientSecret != ""
+ ret.OIDC.ClientSecret = ""
+ }
return
}
@@ -1248,6 +1345,7 @@ func GetMaskedConf() (ret *AppConf, err error) {
// REF: https://github.com/siyuan-note/siyuan/issues/11364
func HideConfSecret(c *AppConf) {
c.AI = &conf.AI{}
+ c.OIDC = &conf.OIDC{}
c.MCPOAuth = ""
c.CookieKey = ""
c.Api = &conf.API{}
diff --git a/kernel/model/conf_secret_test.go b/kernel/model/conf_secret_test.go
index 678b51b15b..3ba2b749fa 100644
--- a/kernel/model/conf_secret_test.go
+++ b/kernel/model/conf_secret_test.go
@@ -34,6 +34,7 @@ func TestGetMaskedConfHidesCookieKey(t *testing.T) {
Conf = NewAppConf()
Conf.CookieKey = cookieKey
+ Conf.OIDC.ClientSecret = "oidc-client-secret"
maskedConf, err := GetMaskedConf()
if err != nil {
@@ -45,6 +46,12 @@ func TestGetMaskedConfHidesCookieKey(t *testing.T) {
if cookieKey != Conf.CookieKey {
t.Fatalf("cookie key in the runtime configuration was changed: %q", Conf.CookieKey)
}
+ if maskedConf.OIDC.ClientSecret != "" || !maskedConf.OIDC.ClientSecretConfigured {
+ t.Fatalf("OIDC client secret state was not safely represented: %#v", maskedConf.OIDC)
+ }
+ if Conf.OIDC.ClientSecret != "oidc-client-secret" {
+ t.Fatalf("OIDC client secret in runtime configuration was changed: %q", Conf.OIDC.ClientSecret)
+ }
}
func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {
diff --git a/kernel/model/oidc.go b/kernel/model/oidc.go
new file mode 100644
index 0000000000..fe1c496dd9
--- /dev/null
+++ b/kernel/model/oidc.go
@@ -0,0 +1,642 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package model
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/88250/gulu"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model/oidc_provider"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ oidcFlowWeb = "web"
+ oidcFlowDesktop = "desktop"
+ oidcFlowMobile = "mobile"
+
+ oidcMobileRedirectURL = "siyuan:/oidc-callback"
+ oidcTransactionMax = 512
+ oidcTransactionTimeout = 10 * time.Minute
+ oidcProviderCacheMax = 8
+)
+
+type oidcTransaction struct {
+ State string
+ Nonce string
+ CodeVerifier string
+ PollToken string
+ Binding string
+ Flow string
+ RedirectURL string
+ To string
+ ConfigVersion string
+ RememberMe bool
+ Claimed bool
+ Completed bool
+ Success bool
+ Message string
+ ExpiresAt time.Time
+}
+
+var oidcTransactions = struct {
+ sync.Mutex
+ byState map[string]*oidcTransaction
+ byPoll map[string]string
+}{byState: map[string]*oidcTransaction{}, byPoll: map[string]string{}}
+
+var oidcProviders = struct {
+ sync.Mutex
+ version string
+ items map[string]*oidc_provider.Provider
+}{items: map[string]*oidc_provider.Provider{}}
+
+type oidcStartInput struct {
+ Flow string `json:"flow"`
+ To string `json:"to"`
+ RememberMe bool `json:"rememberMe"`
+}
+
+type oidcMobileCallbackInput struct {
+ CallbackURL string `json:"callbackURL"`
+}
+
+type oidcPollInput struct {
+ PollToken string `json:"pollToken"`
+}
+
+func OIDCStart(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ if err := validateOIDCConfiguration(); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ input := &oidcStartInput{}
+ if err := c.ShouldBindJSON(input); err != nil {
+ ret.Code = -1
+ ret.Msg = "Invalid OIDC login request"
+ return
+ }
+ if input.Flow == "" {
+ input.Flow = oidcFlowWeb
+ }
+ if input.Flow != oidcFlowWeb && input.Flow != oidcFlowDesktop && input.Flow != oidcFlowMobile {
+ ret.Code = -1
+ ret.Msg = "Invalid OIDC login flow"
+ return
+ }
+
+ session := util.GetSession(c)
+ workspaceSession := util.GetWorkspaceSession(session)
+ if workspaceSession.OIDCBinding == "" {
+ var err error
+ workspaceSession.OIDCBinding, err = secureRandomToken(32)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = "Create OIDC login binding failed"
+ return
+ }
+ }
+ redirectURL, err := effectiveOIDCRedirectURL(c, input.Flow)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ transaction, err := newOIDCTransaction(input, workspaceSession.OIDCBinding, redirectURL)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = "Create OIDC login transaction failed"
+ return
+ }
+ provider, err := getOIDCProvider(c.Request.Context(), redirectURL)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = session.Save(c); err != nil {
+ ret.Code = -1
+ ret.Msg = Conf.Language(258)
+ return
+ }
+ storeOIDCTransaction(transaction)
+ authURL := provider.AuthURL(transaction.State, transaction.Nonce, pkceChallenge(transaction.CodeVerifier))
+ ret.Data = map[string]any{"authURL": authURL, "expiresIn": int(oidcTransactionTimeout.Seconds())}
+ if input.Flow == oidcFlowDesktop {
+ ret.Data.(map[string]any)["pollToken"] = transaction.PollToken
+ }
+}
+
+func OIDCCallback(c *gin.Context) {
+ state := c.Query("state")
+ workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
+ transaction, err := claimOIDCTransaction(state, workspaceSession.OIDCBinding, true)
+ if err != nil {
+ writeOIDCCallbackPage(c, false, err.Error())
+ return
+ }
+ if transaction.Flow == oidcFlowMobile {
+ completeOIDCTransaction(transaction.State, false, "The mobile OIDC callback must be returned to the SiYuan app")
+ writeOIDCCallbackPage(c, false, "The mobile OIDC callback must be returned to the SiYuan app")
+ return
+ }
+ if transaction.Flow == oidcFlowWeb {
+ if workspaceSession.OIDCBinding == "" || workspaceSession.OIDCBinding != transaction.Binding {
+ completeOIDCTransaction(transaction.State, false, "OIDC login binding does not match")
+ writeOIDCCallbackPage(c, false, "OIDC login binding does not match")
+ return
+ }
+ }
+ if providerError := c.Query("error"); providerError != "" {
+ message := "OIDC provider rejected the login: " + providerError
+ completeOIDCTransaction(transaction.State, false, message)
+ writeOIDCCallbackPage(c, false, message)
+ return
+ }
+ if err = finishOIDCExchange(c, transaction, c.Query("code")); err != nil {
+ completeOIDCTransaction(transaction.State, false, err.Error())
+ writeOIDCCallbackPage(c, false, err.Error())
+ return
+ }
+ if transaction.Flow == oidcFlowDesktop {
+ completeOIDCTransaction(transaction.State, true, "")
+ writeOIDCCallbackPage(c, true, "You can close this window and return to SiYuan")
+ return
+ }
+ if err = authenticateOIDCSession(c, transaction.RememberMe); err != nil {
+ completeOIDCTransaction(transaction.State, false, err.Error())
+ writeOIDCCallbackPage(c, false, err.Error())
+ return
+ }
+ completeOIDCTransaction(transaction.State, true, "")
+ c.Redirect(http.StatusFound, safeOIDCRedirectTarget(transaction.To))
+}
+
+func OIDCMobileCallback(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+ input := &oidcMobileCallbackInput{}
+ if err := c.ShouldBindJSON(input); err != nil {
+ ret.Code = -1
+ ret.Msg = "Invalid OIDC callback request"
+ return
+ }
+ callbackURL, err := url.Parse(input.CallbackURL)
+ if err != nil || callbackURL.Scheme != "siyuan" || callbackURL.Host != "" || callbackURL.Path != "/oidc-callback" {
+ ret.Code = -1
+ ret.Msg = "Invalid mobile OIDC callback URL"
+ return
+ }
+ workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
+ transaction, err := claimOIDCTransaction(callbackURL.Query().Get("state"), workspaceSession.OIDCBinding, false)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if transaction.Flow != oidcFlowMobile {
+ ret.Code = -1
+ ret.Msg = "OIDC login flow does not match"
+ return
+ }
+ if providerError := callbackURL.Query().Get("error"); providerError != "" {
+ ret.Code = -1
+ ret.Msg = "OIDC provider rejected the login: " + providerError
+ completeOIDCTransaction(transaction.State, false, ret.Msg)
+ return
+ }
+ if err = finishOIDCExchange(c, transaction, callbackURL.Query().Get("code")); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ completeOIDCTransaction(transaction.State, false, ret.Msg)
+ return
+ }
+ if err = authenticateOIDCSession(c, transaction.RememberMe); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ completeOIDCTransaction(transaction.State, false, ret.Msg)
+ return
+ }
+ completeOIDCTransaction(transaction.State, true, "")
+ ret.Data = map[string]any{"to": safeOIDCRedirectTarget(transaction.To)}
+}
+
+func OIDCPoll(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+ input := &oidcPollInput{}
+ if err := c.ShouldBindJSON(input); err != nil || input.PollToken == "" {
+ ret.Code = -1
+ ret.Msg = "Invalid OIDC poll request"
+ return
+ }
+ workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
+ transaction, found := pollOIDCTransaction(input.PollToken, workspaceSession.OIDCBinding)
+ if !found {
+ ret.Code = -1
+ ret.Msg = "OIDC login transaction was not found or has expired"
+ return
+ }
+ if !transaction.Completed {
+ ret.Data = map[string]any{"status": "pending"}
+ return
+ }
+ if !transaction.Success {
+ ret.Code = -1
+ ret.Msg = transaction.Message
+ deleteOIDCTransaction(transaction.State)
+ return
+ }
+ if err := authenticateOIDCSession(c, transaction.RememberMe); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = map[string]any{"status": "completed", "to": safeOIDCRedirectTarget(transaction.To)}
+ deleteOIDCTransaction(transaction.State)
+}
+
+func validateOIDCConfiguration() error {
+ return ValidateOIDCConfiguration(Conf.GetOIDC())
+}
+
+func ValidateOIDCConfiguration(config *conf.OIDC) error {
+ if config == nil || !config.Enabled {
+ return errors.New("OIDC login is not enabled")
+ }
+ if config.ClientID == "" {
+ return errors.New("OIDC client ID is required")
+ }
+ if config.Provider == conf.OIDCProviderGitHub && config.ClientSecret == "" {
+ return errors.New("GitHub OAuth client secret is required")
+ }
+ if (config.Provider == conf.OIDCProviderCustom || config.Provider == conf.OIDCProviderMicrosoft) && config.IssuerURL == "" {
+ return errors.New("OIDC issuer URL is required")
+ }
+ if (config.Provider == conf.OIDCProviderCustom || config.Provider == conf.OIDCProviderMicrosoft) && config.IssuerURL != "" {
+ issuer, err := url.Parse(config.IssuerURL)
+ if err != nil || issuer.Host == "" || issuer.User != nil || issuer.RawQuery != "" || issuer.Fragment != "" ||
+ (issuer.Scheme != "https" && !util.IsLocalHostname(issuer.Hostname())) {
+ return errors.New("OIDC issuer URL must use HTTPS unless it is a loopback address")
+ }
+ }
+ if config.Provider != conf.OIDCProviderCustom && config.Provider != conf.OIDCProviderGoogle &&
+ config.Provider != conf.OIDCProviderMicrosoft && config.Provider != conf.OIDCProviderGitHub {
+ return errors.New("Unsupported OIDC provider")
+ }
+ if !config.AllowAll && len(config.ClaimRules) == 0 {
+ return errors.New("OIDC login requires at least one claim rule when Allow all users is disabled")
+ }
+ for _, rule := range config.ClaimRules {
+ if rule == nil || rule.Claim == "" || len(rule.Values) == 0 {
+ return errors.New("OIDC claim rules must include a claim and at least one value")
+ }
+ if rule.Operator != conf.OIDCClaimOperatorEquals && rule.Operator != conf.OIDCClaimOperatorContains {
+ return errors.New("Unsupported OIDC claim rule operator")
+ }
+ for _, value := range rule.Values {
+ if value == "" {
+ return errors.New("OIDC claim rule values cannot be empty")
+ }
+ }
+ }
+ return nil
+}
+
+func effectiveOIDCRedirectURL(c *gin.Context, flow string) (string, error) {
+ if flow == oidcFlowMobile {
+ return oidcMobileRedirectURL, nil
+ }
+ if flow == oidcFlowWeb && !IsLocalRequest(c) {
+ return validatePublicOIDCRedirectURL(Conf.GetOIDC().RedirectURL)
+ }
+ if !IsLocalRequest(c) {
+ return "", errors.New("Desktop OIDC login requires a loopback listener")
+ }
+ scheme := "http"
+ if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
+ scheme = "https"
+ }
+ host := c.Request.Host
+ if !util.IsLocalHost(host) {
+ return "", errors.New("A loopback OIDC redirect URL is required for local access")
+ }
+ return scheme + "://" + host + "/api/system/oidc/callback", nil
+}
+
+func validatePublicOIDCRedirectURL(redirectURL string) (string, error) {
+ if redirectURL == "" {
+ return "", errors.New("A public HTTPS OIDC redirect URL is required for remote access")
+ }
+ parsed, err := url.Parse(redirectURL)
+ if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.Path != "/api/system/oidc/callback" ||
+ parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
+ return "", errors.New("OIDC redirect URL must end with /api/system/oidc/callback")
+ }
+ if parsed.Scheme != "https" {
+ return "", errors.New("Public OIDC redirect URL must use HTTPS")
+ }
+ return parsed.String(), nil
+}
+
+func getOIDCProvider(ctx context.Context, redirectURL string) (*oidc_provider.Provider, error) {
+ version := oidcSessionVersion()
+ key := version + "\x00" + redirectURL
+ oidcProviders.Lock()
+ if oidcProviders.version != version {
+ oidcProviders.version = version
+ oidcProviders.items = map[string]*oidc_provider.Provider{}
+ }
+ if provider := oidcProviders.items[key]; provider != nil {
+ oidcProviders.Unlock()
+ return provider, nil
+ }
+ oidcProviders.Unlock()
+ provider, err := oidc_provider.New(ctx, Conf.GetOIDC(), redirectURL)
+ if err != nil {
+ return nil, err
+ }
+ oidcProviders.Lock()
+ defer oidcProviders.Unlock()
+ if oidcProviders.version != version || oidcSessionVersion() != version {
+ return nil, errors.New("OIDC configuration changed during provider discovery")
+ }
+ if existing := oidcProviders.items[key]; existing != nil {
+ return existing, nil
+ }
+ if len(oidcProviders.items) >= oidcProviderCacheMax {
+ oidcProviders.items = map[string]*oidc_provider.Provider{}
+ }
+ oidcProviders.items[key] = provider
+ return provider, nil
+}
+
+func newOIDCTransaction(input *oidcStartInput, binding, redirectURL string) (*oidcTransaction, error) {
+ state, err := secureRandomToken(32)
+ if err != nil {
+ return nil, err
+ }
+ nonce, err := secureRandomToken(32)
+ if err != nil {
+ return nil, err
+ }
+ verifier, err := secureRandomToken(32)
+ if err != nil {
+ return nil, err
+ }
+ pollToken := ""
+ if input.Flow == oidcFlowDesktop {
+ pollToken, err = secureRandomToken(32)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return &oidcTransaction{State: state, Nonce: nonce, CodeVerifier: verifier, PollToken: pollToken, Binding: binding,
+ Flow: input.Flow, RedirectURL: redirectURL, To: input.To, ConfigVersion: oidcSessionVersion(), RememberMe: input.RememberMe,
+ ExpiresAt: time.Now().Add(oidcTransactionTimeout)}, nil
+}
+
+func storeOIDCTransaction(transaction *oidcTransaction) {
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ cleanupOIDCTransactionsLocked()
+ if len(oidcTransactions.byState) >= oidcTransactionMax {
+ var oldest *oidcTransaction
+ for _, candidate := range oidcTransactions.byState {
+ if oldest == nil || candidate.ExpiresAt.Before(oldest.ExpiresAt) {
+ oldest = candidate
+ }
+ }
+ if oldest != nil {
+ deleteOIDCTransactionLocked(oldest.State)
+ }
+ }
+ oidcTransactions.byState[transaction.State] = transaction
+ if transaction.PollToken != "" {
+ oidcTransactions.byPoll[transaction.PollToken] = transaction.State
+ }
+}
+
+func claimOIDCTransaction(state, binding string, allowDesktopWithoutBinding bool) (*oidcTransaction, error) {
+ if state == "" {
+ return nil, errors.New("OIDC state is missing")
+ }
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ cleanupOIDCTransactionsLocked()
+ transaction := oidcTransactions.byState[state]
+ if transaction == nil {
+ return nil, errors.New("OIDC login transaction was not found or has expired")
+ }
+ if transaction.Claimed {
+ return nil, errors.New("OIDC login transaction has already been used")
+ }
+ if transaction.ConfigVersion != oidcSessionVersion() {
+ deleteOIDCTransactionLocked(state)
+ return nil, errors.New("OIDC configuration changed during login")
+ }
+ if !(allowDesktopWithoutBinding && transaction.Flow == oidcFlowDesktop) &&
+ (binding == "" || binding != transaction.Binding) {
+ return nil, errors.New("OIDC login binding does not match")
+ }
+ transaction.Claimed = true
+ copy := *transaction
+ return &copy, nil
+}
+
+func completeOIDCTransaction(state string, success bool, message string) {
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ transaction := oidcTransactions.byState[state]
+ if transaction == nil {
+ return
+ }
+ transaction.Completed = true
+ transaction.Success = success
+ transaction.Message = message
+ if transaction.Flow != oidcFlowDesktop {
+ deleteOIDCTransactionLocked(state)
+ }
+}
+
+func pollOIDCTransaction(pollToken, binding string) (*oidcTransaction, bool) {
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ cleanupOIDCTransactionsLocked()
+ state := oidcTransactions.byPoll[pollToken]
+ transaction := oidcTransactions.byState[state]
+ if transaction == nil || transaction.Flow != oidcFlowDesktop || binding == "" || binding != transaction.Binding {
+ return nil, false
+ }
+ copy := *transaction
+ return &copy, true
+}
+
+func deleteOIDCTransaction(state string) {
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ deleteOIDCTransactionLocked(state)
+}
+
+func deleteOIDCTransactionLocked(state string) {
+ if transaction := oidcTransactions.byState[state]; transaction != nil {
+ delete(oidcTransactions.byPoll, transaction.PollToken)
+ }
+ delete(oidcTransactions.byState, state)
+}
+
+func cleanupOIDCTransactionsLocked() {
+ now := time.Now()
+ for state, transaction := range oidcTransactions.byState {
+ if now.After(transaction.ExpiresAt) {
+ deleteOIDCTransactionLocked(state)
+ }
+ }
+}
+
+func finishOIDCExchange(c *gin.Context, transaction *oidcTransaction, code string) error {
+ if code == "" {
+ return errors.New("OIDC authorization code is missing")
+ }
+ provider, err := getOIDCProvider(c.Request.Context(), transaction.RedirectURL)
+ if err != nil {
+ return err
+ }
+ claims, err := provider.Exchange(c.Request.Context(), code, transaction.CodeVerifier, transaction.Nonce)
+ if err != nil {
+ return err
+ }
+ if err = authorizeOIDCClaims(claims); err != nil {
+ return err
+ }
+ return nil
+}
+
+func authorizeOIDCClaims(claims map[string]any) error {
+ config := Conf.GetOIDC()
+ if config.AllowAll {
+ return nil
+ }
+ for _, rule := range config.ClaimRules {
+ claimValues := oidcClaimValues(claims[rule.Claim])
+ matched := false
+ for _, claimValue := range claimValues {
+ for _, allowedValue := range rule.Values {
+ switch rule.Operator {
+ case conf.OIDCClaimOperatorEquals:
+ matched = claimValue == allowedValue
+ case conf.OIDCClaimOperatorContains:
+ matched = strings.Contains(claimValue, allowedValue)
+ }
+ if matched {
+ break
+ }
+ }
+ if matched {
+ break
+ }
+ }
+ if !matched {
+ return fmt.Errorf("OIDC claim [%s] is not allowed", rule.Claim)
+ }
+ }
+ return nil
+}
+
+func oidcClaimValues(value any) []string {
+ switch typed := value.(type) {
+ case string:
+ return []string{typed}
+ case bool, float64, float32, int, int64, json.Number:
+ return []string{fmt.Sprint(typed)}
+ case []string:
+ return typed
+ case []any:
+ ret := make([]string, 0, len(typed))
+ for _, item := range typed {
+ values := oidcClaimValues(item)
+ if len(values) == 1 {
+ ret = append(ret, values[0])
+ }
+ }
+ return ret
+ default:
+ return nil
+ }
+}
+
+func authenticateOIDCSession(c *gin.Context, rememberMe bool) error {
+ session := util.GetSession(c)
+ workspaceSession := util.GetWorkspaceSession(session)
+ workspaceSession.AccessAuthCode = ""
+ applyAuthenticatedSession(c, workspaceSession, rememberMe)
+ util.WrongAuthCount = 0
+ util.AuthThrottleReset(c.ClientIP())
+ if err := session.Save(c); err != nil {
+ logging.LogErrorf("save OIDC session failed: %s", err)
+ return errors.New("Save OIDC login session failed")
+ }
+ util.BroadcastByType("auth", "loginAuth", 0, "", nil)
+ return nil
+}
+
+func secureRandomToken(size int) (string, error) {
+ buffer := make([]byte, size)
+ if _, err := rand.Read(buffer); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buffer), nil
+}
+
+func pkceChallenge(verifier string) string {
+ digest := sha256.Sum256([]byte(verifier))
+ return base64.RawURLEncoding.EncodeToString(digest[:])
+}
+
+func safeOIDCRedirectTarget(target string) string {
+ parsed, err := url.Parse(target)
+ if err != nil || parsed.IsAbs() || strings.HasPrefix(target, "//") || !strings.HasPrefix(target, "/") ||
+ strings.Contains(target, "\\") {
+ return "/"
+ }
+ return target
+}
+
+func writeOIDCCallbackPage(c *gin.Context, success bool, message string) {
+ title := "OIDC login failed"
+ if success {
+ title = "OIDC login completed"
+ }
+ c.Header("Content-Type", "text/html; charset=utf-8")
+ c.Header("Cache-Control", "no-store")
+ c.Header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'")
+ c.Header("X-Content-Type-Options", "nosniff")
+ c.String(http.StatusOK, "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" "+
+ "content=\"width=device-width,initial-scale=1\"><title>%s</title></head><body><main><h1>%s</h1><p>%s</p></main></body></html>",
+ html.EscapeString(title), html.EscapeString(title), html.EscapeString(message))
+}
diff --git a/kernel/model/oidc_provider/provider.go b/kernel/model/oidc_provider/provider.go
new file mode 100644
index 0000000000..4ec4878875
--- /dev/null
+++ b/kernel/model/oidc_provider/provider.go
@@ -0,0 +1,197 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package oidc_provider
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/coreos/go-oidc/v3/oidc"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "golang.org/x/oauth2"
+)
+
+const (
+ googleIssuer = "https://accounts.google.com"
+)
+
+type Provider struct {
+ kind string
+ oauth2Config *oauth2.Config
+ verifier *oidc.IDTokenVerifier
+}
+
+func New(ctx context.Context, config *conf.OIDC, redirectURL string) (*Provider, error) {
+ if config == nil {
+ return nil, errors.New("OIDC configuration is missing")
+ }
+ if config.ClientID == "" {
+ return nil, errors.New("OIDC client ID is required")
+ }
+ if redirectURL == "" {
+ return nil, errors.New("OIDC redirect URL is required")
+ }
+ if config.Provider == conf.OIDCProviderGitHub && config.ClientSecret == "" {
+ return nil, errors.New("GitHub OAuth client secret is required")
+ }
+ issuerURL := strings.TrimSpace(config.IssuerURL)
+ switch config.Provider {
+ case conf.OIDCProviderGoogle:
+ issuerURL = googleIssuer
+ case conf.OIDCProviderMicrosoft:
+ // Microsoft 多租户端点的 issuer 会随租户变化,必须使用租户专属 issuer。
+ case conf.OIDCProviderCustom:
+ case conf.OIDCProviderGitHub:
+ return newGitHub(config, redirectURL), nil
+ default:
+ return nil, fmt.Errorf("unsupported OIDC provider [%s]", config.Provider)
+ }
+ if issuerURL == "" {
+ return nil, errors.New("OIDC issuer URL is required")
+ }
+ discovered, err := oidc.NewProvider(ctx, issuerURL)
+ if err != nil {
+ return nil, fmt.Errorf("discover OIDC provider failed: %w", err)
+ }
+ scopes := append([]string{}, config.Scopes...)
+ if !contains(scopes, oidc.ScopeOpenID) {
+ scopes = append([]string{oidc.ScopeOpenID}, scopes...)
+ }
+ return &Provider{
+ kind: conf.OIDCProviderCustom,
+ oauth2Config: &oauth2.Config{
+ ClientID: config.ClientID,
+ ClientSecret: config.ClientSecret,
+ Endpoint: discovered.Endpoint(),
+ RedirectURL: redirectURL,
+ Scopes: scopes,
+ },
+ verifier: discovered.Verifier(&oidc.Config{ClientID: config.ClientID}),
+ }, nil
+}
+
+func (p *Provider) AuthURL(state, nonce, codeChallenge string) string {
+ if p.kind == conf.OIDCProviderGitHub {
+ return p.oauth2Config.AuthCodeURL(state, oauth2.S256ChallengeOption(codeChallenge))
+ }
+ return p.oauth2Config.AuthCodeURL(state, oidc.Nonce(nonce), oauth2.S256ChallengeOption(codeChallenge))
+}
+
+func (p *Provider) Exchange(ctx context.Context, code, codeVerifier, nonce string) (map[string]any, error) {
+ token, err := p.oauth2Config.Exchange(ctx, code, oauth2.VerifierOption(codeVerifier))
+ if err != nil {
+ return nil, fmt.Errorf("exchange OIDC authorization code failed: %w", err)
+ }
+ if p.kind == conf.OIDCProviderGitHub {
+ return exchangeGitHubClaims(ctx, token)
+ }
+ rawIDToken, ok := token.Extra("id_token").(string)
+ if !ok || rawIDToken == "" {
+ return nil, errors.New("OIDC response does not contain an ID token")
+ }
+ idToken, err := p.verifier.Verify(ctx, rawIDToken)
+ if err != nil {
+ return nil, fmt.Errorf("verify OIDC ID token failed: %w", err)
+ }
+ if idToken.Nonce != nonce {
+ return nil, errors.New("OIDC nonce does not match")
+ }
+ claims := map[string]any{}
+ if err = idToken.Claims(&claims); err != nil {
+ return nil, fmt.Errorf("decode OIDC claims failed: %w", err)
+ }
+ return claims, nil
+}
+
+func newGitHub(config *conf.OIDC, redirectURL string) *Provider {
+ scopes := append([]string{}, config.Scopes...)
+ if len(scopes) == 0 || contains(scopes, oidc.ScopeOpenID) {
+ scopes = []string{"read:user", "user:email"}
+ }
+ return &Provider{
+ kind: conf.OIDCProviderGitHub,
+ oauth2Config: &oauth2.Config{
+ ClientID: config.ClientID,
+ ClientSecret: config.ClientSecret,
+ Endpoint: oauth2.Endpoint{
+ AuthURL: "https://github.com/login/oauth/authorize",
+ TokenURL: "https://github.com/login/oauth/access_token",
+ },
+ RedirectURL: redirectURL,
+ Scopes: scopes,
+ },
+ }
+}
+
+func exchangeGitHubClaims(ctx context.Context, token *oauth2.Token) (map[string]any, error) {
+ client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(token))
+ user := map[string]any{}
+ if err := getGitHubJSON(ctx, client, "https://api.github.com/user", &user); err != nil {
+ return nil, fmt.Errorf("load GitHub user failed: %w", err)
+ }
+ delete(user, "email")
+ if id, ok := user["id"]; ok {
+ user["sub"] = fmt.Sprint(id)
+ }
+ emails := []struct {
+ Email string `json:"email"`
+ Primary bool `json:"primary"`
+ Verified bool `json:"verified"`
+ }{}
+ if err := getGitHubJSON(ctx, client, "https://api.github.com/user/emails", &emails); err == nil {
+ all := make([]string, 0, len(emails))
+ for _, email := range emails {
+ if !email.Verified {
+ continue
+ }
+ all = append(all, email.Email)
+ if email.Primary {
+ user["email"] = email.Email
+ user["email_verified"] = true
+ }
+ }
+ user["emails"] = all
+ }
+ return user, nil
+}
+
+func getGitHubJSON(ctx context.Context, client *http.Client, endpoint string, target any) error {
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return err
+ }
+ request.Header.Set("Accept", "application/vnd.github+json")
+ request.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+ request.Header.Set("User-Agent", "SiYuan")
+ response, err := client.Do(request)
+ if err != nil {
+ return err
+ }
+ defer response.Body.Close()
+ if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
+ return fmt.Errorf("GitHub API returned status %d", response.StatusCode)
+ }
+ decoder := json.NewDecoder(io.LimitReader(response.Body, 1024*1024))
+ decoder.UseNumber()
+ return decoder.Decode(target)
+}
+
+func contains(values []string, target string) bool {
+ for _, value := range values {
+ if value == target {
+ return true
+ }
+ }
+ return false
+}
diff --git a/kernel/model/oidc_provider/provider_test.go b/kernel/model/oidc_provider/provider_test.go
new file mode 100644
index 0000000000..72f9a98746
--- /dev/null
+++ b/kernel/model/oidc_provider/provider_test.go
@@ -0,0 +1,124 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package oidc_provider
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/go-jose/go-jose/v4"
+ "github.com/go-jose/go-jose/v4/jwt"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+)
+
+func TestGitHubAuthURLUsesPKCEAndSeparateState(t *testing.T) {
+ provider := newGitHub(&conf.OIDC{
+ Provider: conf.OIDCProviderGitHub,
+ ClientID: "client-id",
+ Scopes: []string{"openid", "profile", "email"},
+ }, "siyuan:/oidc-callback")
+ authURL, err := url.Parse(provider.AuthURL("state-value", "nonce-must-not-be-sent", "pkce-challenge"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := authURL.Query()
+ if query.Get("state") != "state-value" || query.Get("code_challenge") != "pkce-challenge" ||
+ query.Get("code_challenge_method") != "S256" {
+ t.Fatalf("GitHub authorization URL is missing state or PKCE: %s", authURL.String())
+ }
+ if query.Get("nonce") != "" {
+ t.Fatalf("GitHub OAuth authorization URL unexpectedly contains an OIDC nonce: %s", authURL.String())
+ }
+ if query.Get("scope") != "read:user user:email" {
+ t.Fatalf("GitHub preset scopes were not applied: %q", query.Get("scope"))
+ }
+}
+
+func TestOIDCProviderVerifiesNonceAndPKCE(t *testing.T) {
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+ signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: privateKey},
+ (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "test-key"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ const verifier = "0123456789012345678901234567890123456789012"
+ const nonce = "test-nonce"
+ var server *httptest.Server
+ server = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ writer.Header().Set("Content-Type", "application/json")
+ switch request.URL.Path {
+ case "/.well-known/openid-configuration":
+ _ = json.NewEncoder(writer).Encode(map[string]any{
+ "issuer": server.URL, "authorization_endpoint": server.URL + "/authorize",
+ "token_endpoint": server.URL + "/token", "jwks_uri": server.URL + "/jwks",
+ "response_types_supported": []string{"code"}, "subject_types_supported": []string{"public"},
+ "id_token_signing_alg_values_supported": []string{"RS256"},
+ })
+ case "/jwks":
+ _ = json.NewEncoder(writer).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{
+ Key: &privateKey.PublicKey, KeyID: "test-key", Algorithm: string(jose.RS256), Use: "sig",
+ }}})
+ case "/token":
+ if err := request.ParseForm(); err != nil || request.Form.Get("code_verifier") != verifier {
+ http.Error(writer, "invalid PKCE verifier", http.StatusBadRequest)
+ return
+ }
+ idToken, signErr := jwt.Signed(signer).Claims(jwt.Claims{
+ Issuer: server.URL, Subject: "subject", Audience: jwt.Audience{"client-id"},
+ Expiry: jwt.NewNumericDate(time.Now().Add(time.Minute)), IssuedAt: jwt.NewNumericDate(time.Now()),
+ }).Claims(map[string]any{"nonce": nonce, "email": "[email protected]"}).Serialize()
+ if signErr != nil {
+ http.Error(writer, signErr.Error(), http.StatusInternalServerError)
+ return
+ }
+ _ = json.NewEncoder(writer).Encode(map[string]any{
+ "access_token": "access-token", "token_type": "Bearer", "id_token": idToken,
+ })
+ default:
+ http.NotFound(writer, request)
+ }
+ }))
+ defer server.Close()
+
+ provider, err := New(context.Background(), &conf.OIDC{
+ Provider: conf.OIDCProviderCustom, IssuerURL: server.URL, ClientID: "client-id", ClientSecret: "secret",
+ Scopes: []string{"openid", "email"},
+ }, "http://127.0.0.1:6806/api/system/oidc/callback")
+ if err != nil {
+ t.Fatalf("create test provider failed: %s", err)
+ }
+ authURL, err := url.Parse(provider.AuthURL("test-state", nonce, "test-challenge"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if authURL.Query().Get("state") != "test-state" || authURL.Query().Get("nonce") != nonce ||
+ authURL.Query().Get("code_challenge_method") != "S256" {
+ t.Fatalf("OIDC authorization URL is missing security parameters: %s", authURL.String())
+ }
+ claims, err := provider.Exchange(context.Background(), "authorization-code", verifier, nonce)
+ if err != nil {
+ t.Fatalf("OIDC exchange failed: %s", err)
+ }
+ if claims["email"] != "[email protected]" {
+ t.Fatalf("unexpected OIDC claims: %#v", claims)
+ }
+ if _, err = provider.Exchange(context.Background(), "authorization-code", verifier, "wrong-nonce"); err == nil {
+ t.Fatal("OIDC exchange accepted a mismatched nonce")
+ }
+}
diff --git a/kernel/model/oidc_test.go b/kernel/model/oidc_test.go
new file mode 100644
index 0000000000..023709dcaf
--- /dev/null
+++ b/kernel/model/oidc_test.go
@@ -0,0 +1,182 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package model
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func setupOIDCTest(t *testing.T) {
+ t.Helper()
+ previousConf := Conf
+ Conf = NewAppConf()
+ Conf.CookieKey = "oidc-test-cookie-key"
+ Conf.OIDC = &conf.OIDC{
+ Enabled: true,
+ Provider: conf.OIDCProviderCustom,
+ IssuerURL: "https://issuer.example.com",
+ ClientID: "client-id",
+ Scopes: []string{"openid", "email"},
+ AllowAll: true,
+ ClaimRules: []*conf.OIDCClaimRule{},
+ }
+ oidcTransactions.Lock()
+ oidcTransactions.byState = map[string]*oidcTransaction{}
+ oidcTransactions.byPoll = map[string]string{}
+ oidcTransactions.Unlock()
+ t.Cleanup(func() {
+ Conf = previousConf
+ oidcTransactions.Lock()
+ oidcTransactions.byState = map[string]*oidcTransaction{}
+ oidcTransactions.byPoll = map[string]string{}
+ oidcTransactions.Unlock()
+ })
+}
+
+func TestValidateOIDCConfigurationRequiresExplicitPolicy(t *testing.T) {
+ setupOIDCTest(t)
+ Conf.OIDC.AllowAll = false
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err == nil {
+ t.Fatal("expected an error when OIDC has neither AllowAll nor claim rules")
+ }
+ Conf.OIDC.ClaimRules = []*conf.OIDCClaimRule{{
+ Claim: "email", Operator: conf.OIDCClaimOperatorEquals, Values: []string{"[email protected]"},
+ }}
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err != nil {
+ t.Fatalf("valid OIDC configuration was rejected: %s", err)
+ }
+ Conf.OIDC.ClaimRules[0].Values = []string{""}
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err == nil {
+ t.Fatal("expected an empty claim rule value to be rejected")
+ }
+}
+
+func TestValidateOIDCConfigurationRejectsInsecureIssuer(t *testing.T) {
+ setupOIDCTest(t)
+ Conf.OIDC.IssuerURL = "http://issuer.example.com"
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err == nil {
+ t.Fatal("expected an insecure non-loopback issuer to be rejected")
+ }
+ Conf.OIDC.IssuerURL = "http://127.0.0.1:5556"
+ if err := ValidateOIDCConfiguration(Conf.OIDC); err != nil {
+ t.Fatalf("loopback issuer was rejected: %s", err)
+ }
+}
+
+func TestValidatePublicOIDCRedirectURL(t *testing.T) {
+ valid := "https://notes.example.com/api/system/oidc/callback"
+ if redirect, err := validatePublicOIDCRedirectURL(valid); err != nil || redirect != valid {
+ t.Fatalf("valid public redirect URL was rejected: %s", err)
+ }
+ for _, invalid := range []string{"", "http://notes.example.com/api/system/oidc/callback", "https://notes.example.com/other",
+ "https://notes.example.com/api/system/oidc/callback?next=/"} {
+ if _, err := validatePublicOIDCRedirectURL(invalid); err == nil {
+ t.Fatalf("invalid public redirect URL was accepted: %s", invalid)
+ }
+ }
+}
+
+func TestAuthorizeOIDCClaimsCombinesRulesWithAnd(t *testing.T) {
+ setupOIDCTest(t)
+ Conf.OIDC.AllowAll = false
+ Conf.OIDC.ClaimRules = []*conf.OIDCClaimRule{
+ {Claim: "email", Operator: conf.OIDCClaimOperatorEquals, Values: []string{"[email protected]", "[email protected]"}},
+ {Claim: "groups", Operator: conf.OIDCClaimOperatorContains, Values: []string{"siyuan-admin"}},
+ {Claim: "email_verified", Operator: conf.OIDCClaimOperatorEquals, Values: []string{"true"}},
+ }
+ claims := map[string]any{"email": "[email protected]", "groups": []any{"users", "siyuan-admins"}, "email_verified": true}
+ if err := authorizeOIDCClaims(claims); err != nil {
+ t.Fatalf("allowed claims were rejected: %s", err)
+ }
+ claims["groups"] = []any{"users"}
+ if err := authorizeOIDCClaims(claims); err == nil {
+ t.Fatal("expected all claim rules to be required")
+ }
+}
+
+func TestOIDCTransactionUsesSeparateBoundPollToken(t *testing.T) {
+ setupOIDCTest(t)
+ transaction, err := newOIDCTransaction(&oidcStartInput{Flow: oidcFlowDesktop}, "binding-a", "http://127.0.0.1:6806/api/system/oidc/callback")
+ if err != nil {
+ t.Fatalf("create transaction failed: %s", err)
+ }
+ if transaction.State == transaction.PollToken || transaction.State == transaction.CodeVerifier || transaction.PollToken == "" {
+ t.Fatal("OIDC state, PKCE verifier, and poll token must be independent")
+ }
+ storeOIDCTransaction(transaction)
+ claimed, err := claimOIDCTransaction(transaction.State, "", true)
+ if err != nil || claimed.State != transaction.State {
+ t.Fatalf("desktop callback could not claim transaction: %v", err)
+ }
+ if _, err = claimOIDCTransaction(transaction.State, "", true); err == nil {
+ t.Fatal("OIDC state was accepted more than once")
+ }
+ completeOIDCTransaction(transaction.State, true, "")
+ if _, found := pollOIDCTransaction(transaction.PollToken, "binding-b"); found {
+ t.Fatal("poll token was accepted with the wrong WebView binding")
+ }
+ if result, found := pollOIDCTransaction(transaction.PollToken, "binding-a"); !found || !result.Success {
+ t.Fatal("completed desktop transaction was not returned to its bound WebView")
+ }
+}
+
+func TestOIDCTransactionExpiryAndSafeRedirect(t *testing.T) {
+ setupOIDCTest(t)
+ transaction := &oidcTransaction{
+ State: "expired", Binding: "binding", ConfigVersion: oidcSessionVersion(), ExpiresAt: time.Now().Add(-time.Second),
+ }
+ storeOIDCTransaction(transaction)
+ if _, err := claimOIDCTransaction(transaction.State, "binding", false); err == nil {
+ t.Fatal("expired OIDC transaction was accepted")
+ }
+ for _, unsafe := range []string{"https://example.com", "//example.com", "/\\example.com", "javascript:alert(1)", ""} {
+ if target := safeOIDCRedirectTarget(unsafe); target != "/" {
+ t.Fatalf("unsafe redirect target [%s] was accepted as [%s]", unsafe, target)
+ }
+ }
+ if target := safeOIDCRedirectTarget("/stage/build/mobile/"); target != "/stage/build/mobile/" {
+ t.Fatalf("safe redirect target was changed: %s", target)
+ }
+}
+
+func TestSecureRandomToken(t *testing.T) {
+ first, err := secureRandomToken(32)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := secureRandomToken(32)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first == second || strings.ContainsAny(first, "+/=") || len(first) < 43 {
+ t.Fatal("secure random token is not URL-safe or sufficiently random")
+ }
+}
+
+func TestOIDCSessionVersionInvalidatesOnConfigurationChange(t *testing.T) {
+ setupOIDCTest(t)
+ workspaceSession := &util.WorkspaceSession{OIDCSessionVersion: oidcSessionVersion()}
+ if !IsWorkspaceSessionAuthenticated(workspaceSession) {
+ t.Fatal("current OIDC session version was rejected")
+ }
+ Conf.OIDC.ClientID = "changed-client-id"
+ if IsWorkspaceSessionAuthenticated(workspaceSession) {
+ t.Fatal("OIDC session survived an authentication configuration change")
+ }
+ Conf.AccessAuthCode = "access-code"
+ workspaceSession.AccessAuthCode = "access-code"
+ if !IsWorkspaceSessionAuthenticated(workspaceSession) {
+ t.Fatal("valid access-code session should remain available as an independent login method")
+ }
+}
diff --git a/kernel/model/session.go b/kernel/model/session.go
index fc8537468a..f9d6fd2660 100644
--- a/kernel/model/session.go
+++ b/kernel/model/session.go
@@ -44,7 +44,7 @@ func LogoutAuth(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
- if "" == Conf.AccessAuthCode {
+ if !IsAccessAuthRequired() {
ret.Code = -1
ret.Msg = Conf.Language(86)
ret.Data = map[string]any{"closeTimeout": 5000}
@@ -113,7 +113,7 @@ func LoginAuth(c *gin.Context) {
authCode = util.RemoveInvalid(authCode)
authCode = strings.TrimSpace(authCode)
- if !util.AuthCodeEquals(Conf.AccessAuthCode, authCode) {
+ if Conf.AccessAuthCode == "" || !util.AuthCodeEquals(Conf.AccessAuthCode, authCode) {
ret.Code = -1
ret.Msg = Conf.Language(83)
logging.LogWarnf("invalid auth code [ip=%s]", util.GetRemoteAddr(c.Request))
@@ -135,6 +135,7 @@ func LoginAuth(c *gin.Context) {
}
workspaceSession.AccessAuthCode = authCode
+ workspaceSession.OIDCSessionVersion = ""
util.WrongAuthCount = 0
util.AuthThrottleReset(c.ClientIP())
workspaceSession.Captcha = gulu.Rand.String(7)
@@ -149,6 +150,7 @@ func LoginAuth(c *gin.Context) {
Secure: util.SSL,
MaxAge: maxAge,
HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
})
logging.LogInfof("auth success [ip=%s, maxAge=%d]", util.GetRemoteAddr(c.Request), maxAge)
@@ -243,7 +245,7 @@ func CheckAuth(c *gin.Context) {
localhost := IsLocalRequest(c)
// 未设置锁屏密码
- if "" == Conf.AccessAuthCode {
+ if !IsAccessAuthRequired() {
// Skip the empty access authorization code check https://github.com/siyuan-note/siyuan/issues/9709
if util.SiYuanAccessAuthCodeBypass {
c.Set(RoleContextKey, RoleAdministrator)
@@ -308,7 +310,7 @@ func CheckAuth(c *gin.Context) {
// 通过 Cookie
session := util.GetSession(c)
workspaceSession := util.GetWorkspaceSession(session)
- if workspaceSession.AccessAuthCode == Conf.AccessAuthCode {
+ if IsWorkspaceSessionAuthenticated(workspaceSession) {
// 校验 Origin 防止跨站请求伪造 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hhm2-g993-p656
if !util.IsSessionOriginAllowed(c.GetHeader("Origin"), c.GetHeader("Host")) {
logging.LogWarnf("invalid Origin [%s] for session auth [ip=%s]", c.GetHeader("Origin"), c.ClientIP())
@@ -322,25 +324,27 @@ func CheckAuth(c *gin.Context) {
}
// 通过 BasicAuth (header: Authorization)
- if username, password, ok := c.Request.BasicAuth(); ok {
- // 使用锁屏密码作为密码
- ip := c.ClientIP()
- if retryAfter := util.AuthThrottleCheck(ip); 0 < retryAfter {
- // 锁定期间持续记录失败,防止暴力破解 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
+ if Conf.AccessAuthCode != "" {
+ if username, password, ok := c.Request.BasicAuth(); ok {
+ // 使用锁屏密码作为密码
+ ip := c.ClientIP()
+ if retryAfter := util.AuthThrottleCheck(ip); 0 < retryAfter {
+ // 锁定期间持续记录失败,防止暴力破解 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
+ util.AuthThrottleFail(ip)
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ c.JSON(http.StatusTooManyRequests, map[string]any{"code": -1, "msg": Conf.Language(354)})
+ c.Abort()
+ return
+ }
+ if util.WorkspaceName == username && util.AuthCodeEquals(Conf.AccessAuthCode, password) {
+ util.AuthThrottleReset(ip)
+ c.Set(RoleContextKey, RoleAdministrator)
+ c.Next()
+ return
+ }
+ logging.LogWarnf("invalid auth code [ip=%s]", ip)
util.AuthThrottleFail(ip)
- c.Header("Retry-After", strconv.Itoa(retryAfter))
- c.JSON(http.StatusTooManyRequests, map[string]any{"code": -1, "msg": Conf.Language(354)})
- c.Abort()
- return
}
- if util.WorkspaceName == username && util.AuthCodeEquals(Conf.AccessAuthCode, password) {
- util.AuthThrottleReset(ip)
- c.Set(RoleContextKey, RoleAdministrator)
- c.Next()
- return
- }
- logging.LogWarnf("invalid auth code [ip=%s]", ip)
- util.AuthThrottleFail(ip)
}
// WebDAV BasicAuth Authenticate
@@ -358,7 +362,7 @@ func CheckAuth(c *gin.Context) {
return
}
- if workspaceSession.AccessAuthCode != Conf.AccessAuthCode {
+ if !IsWorkspaceSessionAuthenticated(workspaceSession) {
userAgentHeader := c.GetHeader("User-Agent")
if strings.HasPrefix(userAgentHeader, "SiYuan/") || strings.HasPrefix(userAgentHeader, "Mozilla/") {
if "GET" != c.Request.Method || c.IsWebsocket() {
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 03cf3945a9..0549c4cb7f 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -792,6 +792,10 @@ func serveAuthPage(c *gin.Context) {
"l9": model.Conf.Language(83),
"l10": model.Conf.Language(257),
"l11": model.Conf.Language(282),
+ "l12": model.Conf.Language(364),
+ "l13": model.Conf.Language(365),
+ "accessAuthCodeEnabled": model.Conf.AccessAuthCode != "",
+ "oidcEnabled": model.Conf.GetOIDC().Enabled,
"appearanceMode": model.Conf.Appearance.Mode,
"appearanceModeOS": model.Conf.Appearance.ModeOS,
"workspace": util.WorkspaceName,
@@ -1278,9 +1282,9 @@ func serveWebSocket(ginServer *gin.Engine) {
return
}
- authOk := true
+ authOk := !model.IsAccessAuthRequired()
- if "" != model.Conf.AccessAuthCode {
+ if model.IsAccessAuthRequired() {
session, err := sessionStore.Get(s.Request, "siyuan")
if err != nil {
authOk = false
@@ -1297,7 +1301,7 @@ func serveWebSocket(ginServer *gin.Engine) {
logging.LogErrorf("unmarshal cookie failed: %s", err)
} else {
workspaceSess := util.GetWorkspaceSession(sess)
- authOk = workspaceSess.AccessAuthCode == model.Conf.AccessAuthCode
+ authOk = model.IsWorkspaceSessionAuthenticated(workspaceSess)
}
}
}
diff --git a/kernel/util/session.go b/kernel/util/session.go
index 8bd8e53271..83660b13a2 100644
--- a/kernel/util/session.go
+++ b/kernel/util/session.go
@@ -122,8 +122,10 @@ type SessionData struct {
}
type WorkspaceSession struct {
- AccessAuthCode string
- Captcha string
+ AccessAuthCode string
+ OIDCSessionVersion string
+ OIDCBinding string
+ Captcha string
}
func (sd *SessionData) Clear(c *gin.Context) {
diff --git a/kernel/util/working.go b/kernel/util/working.go
index 965aa2b933..ae561a8cd6 100644
--- a/kernel/util/working.go
+++ b/kernel/util/working.go
@@ -162,22 +162,6 @@ func BootWithFlags(workspacePath, wdPath, port, readOnly, accessAuthCode, lang,
Container = ContainerStd
if RunInContainer {
Container = ContainerDocker
- if "" == AccessAuthCode { // Still empty?
- interruptBoot := true
-
- // Set the env `SIYUAN_ACCESS_AUTH_CODE_BYPASS=true` to skip checking empty access auth code https://github.com/siyuan-note/siyuan/issues/9709
- if SiYuanAccessAuthCodeBypass {
- interruptBoot = false
- fmt.Println("bypass access auth code check since the env [SIYUAN_ACCESS_AUTH_CODE_BYPASS] is set to [true]")
- }
-
- if interruptBoot {
- // The access authorization code command line parameter must be set when deploying via Docker https://github.com/siyuan-note/siyuan/issues/9328
- fmt.Printf("the access authorization code command line parameter (--accessAuthCode) must be set when deploying via Docker\n")
- fmt.Printf("or you can set the SIYUAN_ACCESS_AUTH_CODE env var")
- os.Exit(logging.ExitCodeSecurityRisk)
- }
- }
}
if ContainerStd != Container {
ServerPort = FixedPort