Skip to content

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

:lock: Harden OIDC configuration validation and mobile flow https://github.com/siyuan-note/siyuan/issues/18542

Danielfac1ec50cfd9
diff --git a/README.md b/README.md
index f226f7799d..c380e69468 100644
--- a/README.md
+++ b/README.md
@@ -221,9 +221,9 @@ docker run -d \
- `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`; register it exactly as written. Custom providers, Microsoft, and GitHub can be used only when their application registration accepts this callback URI. Google does not accept this private-use URI for its Android client type, so Google login is limited to browser and desktop flows
+ - `SIYUAN_OIDC_ALLOW_ALL`: Explicitly grant SiYuan administrator access to 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]"]},{"claim":"email_verified","operator":"equals","values":["true"]}]`; values within a rule use OR, while rules use AND
+ - Native mobile apps use the fixed callback URI `siyuan:/oidc-callback`; register it exactly as written. Mobile configuration verification uses this callback before saving. Custom providers, Microsoft, and GitHub can be used only when their application registration accepts this callback URI. Google does not accept this private-use URI for its Android client type, so Google login is limited to browser and desktop flows
- `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 f6a624ca0f..1ed3d3eda2 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "إعداد قواعد مطالبات OIDC غير صالح",
"oidcClaimRulesTip": "مصفوفة JSON؛ القيم داخل القاعدة مرتبطة بـ OR والقواعد مرتبطة بـ AND",
"oidcClaimRules": "قواعد مطالبات OIDC",
- "oidcAllowAll": "السماح لجميع المستخدمين المصادق عليهم",
+ "oidcAllowAll": "منح صلاحيات المسؤول لجميع المستخدمين المصادق عليهم",
"oidcRedirectURL": "عنوان URL لإعادة توجيه OIDC",
"oidcScopes": "نطاقات OIDC",
"oidcClientSecret": "سر عميل OIDC",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index a0c8a254e4..d98dc9d263 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Allen authentifizierten Benutzern Administratorzugriff gewähren",
"oidcRedirectURL": "OIDC-Weiterleitungs-URL",
"oidcScopes": "OIDC-Bereiche",
"oidcClientSecret": "OIDC-Client-Geheimnis",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 29983fb50d..6d3dfbb4b5 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Grant administrator access to all authenticated users",
"oidcRedirectURL": "OIDC redirect URL",
"oidcScopes": "OIDC scopes",
"oidcClientSecret": "OIDC client secret",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index fdc57156b8..af2de63809 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Conceder acceso de administrador a todos los usuarios autenticados",
"oidcRedirectURL": "URL de redirección OIDC",
"oidcScopes": "Ámbitos OIDC",
"oidcClientSecret": "Secreto del cliente OIDC",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 0cfd6ce00a..64fe34719d 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Accorder l’accès administrateur à tous les utilisateurs authentifiés",
"oidcRedirectURL": "URL de redirection OIDC",
"oidcScopes": "Portées OIDC",
"oidcClientSecret": "Secret client OIDC",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index ba8977019f..b3e5cfc389 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "תצורת כללי תביעות OIDC אינה תקינה",
"oidcClaimRulesTip": "מערך JSON; ערכים בתוך כלל משתמשים ב-OR וכללים משתמשים ב-AND",
"oidcClaimRules": "כללי תביעות OIDC",
- "oidcAllowAll": "אפשר לכל המשתמשים המאומתים",
+ "oidcAllowAll": "הענק גישת מנהל לכל המשתמשים המאומתים",
"oidcRedirectURL": "כתובת הפניה של OIDC",
"oidcScopes": "טווחי OIDC",
"oidcClientSecret": "סוד לקוח OIDC",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d7042b3500..268036b45f 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "OIDC क्लेम नियम कॉन्फ़िगरेशन अमान्य है",
"oidcClaimRulesTip": "JSON सरणी; एक नियम के मान OR और अलग नियम AND का उपयोग करते हैं",
"oidcClaimRules": "OIDC क्लेम नियम",
- "oidcAllowAll": "सभी प्रमाणित उपयोगकर्ताओं को अनुमति दें",
+ "oidcAllowAll": "सभी प्रमाणित उपयोगकर्ताओं को व्यवस्थापक पहुँच दें",
"oidcRedirectURL": "OIDC रीडायरेक्ट URL",
"oidcScopes": "OIDC स्कोप",
"oidcClientSecret": "OIDC क्लाइंट सीक्रेट",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 9fdd42b75e..bf05e058aa 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Berikan akses administrator kepada semua pengguna terautentikasi",
"oidcRedirectURL": "URL pengalihan OIDC",
"oidcScopes": "Cakupan OIDC",
"oidcClientSecret": "Rahasia klien OIDC",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 45009328a1..2cb511acdc 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Concedi l’accesso amministratore a tutti gli utenti autenticati",
"oidcRedirectURL": "URL di reindirizzamento OIDC",
"oidcScopes": "Ambiti OIDC",
"oidcClientSecret": "Segreto client OIDC",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index ba5da3f5f3..d85e3ce41c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "OIDC クレームルールの設定が無効です",
"oidcClaimRulesTip": "JSON 配列。同一ルール内の値は OR、ルール間は AND として評価されます",
"oidcClaimRules": "OIDC クレームルール",
- "oidcAllowAll": "認証済みのすべてのユーザーを許可",
+ "oidcAllowAll": "認証済みのすべてのユーザーに管理者権限を付与",
"oidcRedirectURL": "OIDC リダイレクト URL",
"oidcScopes": "OIDC スコープ",
"oidcClientSecret": "OIDC クライアントシークレット",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 823979ee47..3a99fe4fa4 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "OIDC 클레임 규칙 구성이 올바르지 않습니다",
"oidcClaimRulesTip": "JSON 배열이며 한 규칙 안의 값은 OR, 규칙 사이는 AND로 평가됩니다",
"oidcClaimRules": "OIDC 클레임 규칙",
- "oidcAllowAll": "인증된 모든 사용자 허용",
+ "oidcAllowAll": "인증된 모든 사용자에게 관리자 권한 부여",
"oidcRedirectURL": "OIDC 리디렉션 URL",
"oidcScopes": "OIDC 범위",
"oidcClientSecret": "OIDC 클라이언트 비밀",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index aa611e287a..4b5e7c289b 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Alle geverifieerde gebruikers beheerderstoegang geven",
"oidcRedirectURL": "OIDC-omleidings-URL",
"oidcScopes": "OIDC-bereiken",
"oidcClientSecret": "OIDC-clientgeheim",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index ca192a1eda..b31885a73c 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Przyznaj dostęp administratora wszystkim uwierzytelnionym użytkownikom",
"oidcRedirectURL": "Adres URL przekierowania OIDC",
"oidcScopes": "Zakresy OIDC",
"oidcClientSecret": "Sekret klienta OIDC",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 4de8d1a3b9..0d7320f931 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Conceder acesso de administrador a todos os usuários autenticados",
"oidcRedirectURL": "URL de redirecionamento OIDC",
"oidcScopes": "Escopos OIDC",
"oidcClientSecret": "Segredo do cliente OIDC",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 9a5ceee399..b6f12e07b3 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "Недопустимая конфигурация правил утверждений OIDC",
"oidcClaimRulesTip": "Массив JSON; значения внутри правила объединяются ИЛИ, а правила — И",
"oidcClaimRules": "Правила утверждений OIDC",
- "oidcAllowAll": "Разрешить всех прошедших проверку пользователей",
+ "oidcAllowAll": "Предоставить права администратора всем прошедшим проверку пользователям",
"oidcRedirectURL": "URL-адрес перенаправления OIDC",
"oidcScopes": "Области OIDC",
"oidcClientSecret": "Секрет клиента OIDC",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index a98320df27..4053b3ecb7 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Udeliť prístup správcu všetkým overeným používateľom",
"oidcRedirectURL": "Adresa URL presmerovania OIDC",
"oidcScopes": "Rozsahy OIDC",
"oidcClientSecret": "Tajomstvo klienta OIDC",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 76dde7825d..e7a19741ad 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "การกำหนดค่ากฎเคลม OIDC ไม่ถูกต้อง",
"oidcClaimRulesTip": "อาร์เรย์ JSON; ค่าในกฎเดียวกันใช้ OR และระหว่างกฎใช้ AND",
"oidcClaimRules": "กฎเคลม OIDC",
- "oidcAllowAll": "อนุญาตผู้ใช้ที่ยืนยันตัวตนแล้วทั้งหมด",
+ "oidcAllowAll": "ให้สิทธิ์ผู้ดูแลระบบแก่ผู้ใช้ที่ยืนยันตัวตนแล้วทั้งหมด",
"oidcRedirectURL": "URL เปลี่ยนเส้นทาง OIDC",
"oidcScopes": "ขอบเขต OIDC",
"oidcClientSecret": "รหัสลับไคลเอนต์ OIDC",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 93cb98d0d7..4b6b79b020 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -7,7 +7,7 @@
"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",
+ "oidcAllowAll": "Kimliği doğrulanmış tüm kullanıcılara yönetici erişimi ver",
"oidcRedirectURL": "OIDC yönlendirme URL'si",
"oidcScopes": "OIDC kapsamları",
"oidcClientSecret": "OIDC istemci gizli anahtarı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 9b8567b00b..72497a6710 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "Неприпустима конфігурація правил тверджень OIDC",
"oidcClaimRulesTip": "Масив JSON; значення в правилі поєднуються АБО, а правила — І",
"oidcClaimRules": "Правила тверджень OIDC",
- "oidcAllowAll": "Дозволити всіх автентифікованих користувачів",
+ "oidcAllowAll": "Надати права адміністратора всім автентифікованим користувачам",
"oidcRedirectURL": "URL-адреса переспрямування OIDC",
"oidcScopes": "Області OIDC",
"oidcClientSecret": "Секрет клієнта OIDC",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 1751b074b0..74ca542579 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "OIDC 声明规则配置无效",
"oidcClaimRulesTip": "JSON 数组;同一规则内的值为或关系,不同规则之间为与关系",
"oidcClaimRules": "OIDC 声明规则",
- "oidcAllowAll": "允许所有已认证用户",
+ "oidcAllowAll": "授予所有已认证用户管理员权限",
"oidcRedirectURL": "OIDC 回调地址",
"oidcScopes": "OIDC 授权范围",
"oidcClientSecret": "OIDC 客户端密钥",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index cb1ea5b3d0..5cf2452e72 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -7,7 +7,7 @@
"oidcConfigInvalid": "OIDC 宣告規則設定無效",
"oidcClaimRulesTip": "JSON 陣列;同一規則內的值為或關係,不同規則之間為與關係",
"oidcClaimRules": "OIDC 宣告規則",
- "oidcAllowAll": "允許所有已驗證使用者",
+ "oidcAllowAll": "授予所有已驗證使用者管理員權限",
"oidcRedirectURL": "OIDC 回呼位址",
"oidcScopes": "OIDC 授權範圍",
"oidcClientSecret": "OIDC 用戶端密鑰",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy
index 3fafc98201..1b23ac4fd4 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy
@@ -6,7 +6,7 @@
"id": "20201004194026-s8h2cog",
"title": "Use on browser",
"type": "doc",
- "updated": "20260804120100"
+ "updated": "20260804165000"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104091447-8iiuxlt",
- "updated": "20260804120100"
+ "updated": "20260804165000"
},
"Children": [
{
@@ -254,7 +254,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260804120101-oidclog",
- "updated": "20260804120101"
+ "updated": "20260804165000"
},
"Children": [
{
@@ -268,7 +268,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120102-oidcset",
- "updated": "20260804120102"
+ "updated": "20260804165000"
},
"Children": [
{
@@ -291,7 +291,7 @@
},
{
"Type": "NodeText",
- "Data": ". Remote browser access requires a public HTTPS callback URL ending in /api/system/oidc/callback. SiYuan's local listening address is valid only for a local browser login and cannot be used as the fixed callback for remote browsers or mobile apps."
+ "Data": ". Remote browser access requires a public HTTPS callback URL ending in /api/system/oidc/callback. SiYuan's local listening address is valid only for a local browser login and cannot be used as the fixed callback for remote browsers or mobile apps. Custom and Microsoft providers require an issuer URL, and GitHub requires a client secret. Every accepted identity receives administrator access. Keep the option that grants all authenticated users administrator access disabled when possible and use exact claim rules; an email rule should normally be combined with email_verified equal to true. Verify and save completes an actual provider login before activating the configuration. For Docker, configure SIYUAN_OIDC_ENABLED, SIYUAN_OIDC_PROVIDER, SIYUAN_OIDC_CLIENT_ID, and the applicable SIYUAN_OIDC_ISSUER_URL, SIYUAN_OIDC_CLIENT_SECRET, SIYUAN_OIDC_SCOPES, SIYUAN_OIDC_REDIRECT_URL, SIYUAN_OIDC_ALLOW_ALL, and SIYUAN_OIDC_CLAIM_RULES variables."
}
]
},
@@ -300,12 +300,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120103-oidcmob",
- "updated": "20260804120103"
+ "updated": "20260804165000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Native mobile apps always use siyuan:/oidc-callback; register it exactly as written with the identity provider. Google does not accept this mobile callback form, so Google login is available only in browser and desktop flows."
+ "Data": "Native mobile apps always use siyuan:/oidc-callback; register it exactly as written with the identity provider. Mobile configuration verification uses the same callback and is not saved unless the callback succeeds. Google does not accept this mobile callback form, so Google login is available only in browser and desktop flows. A redirect_uri mismatch usually means that the registered callback differs in scheme, slash, path, or port. Discovery failures usually indicate an incorrect issuer URL or an unreachable provider, while exchange failures commonly indicate an incorrect client ID or client secret."
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy
index 40bc46169c..ac8deaef0f 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy
@@ -6,7 +6,7 @@
"id": "20201004184819-nj8ibyg",
"title": "在浏览器上使用",
"type": "doc",
- "updated": "20260804120000"
+ "updated": "20260804165001"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104090909-6pyfjgx",
- "updated": "20260804120000"
+ "updated": "20260804165001"
},
"Children": [
{
@@ -253,7 +253,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260804120001-oidclog",
- "updated": "20260804120001"
+ "updated": "20260804165001"
},
"Children": [
{
@@ -267,7 +267,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120002-oidcset",
- "updated": "20260804120002"
+ "updated": "20260804165001"
},
"Children": [
{
@@ -290,7 +290,7 @@
},
{
"Type": "NodeText",
- "Data": " 中配置 OIDC 登录。远程浏览器访问必须配置以 /api/system/oidc/callback 结尾的公网 HTTPS 回调地址;思源的本机监听地址仅适用于本机浏览器登录,不能作为远程浏览器或移动端的固定回调地址。"
+ "Data": " 中配置 OIDC 登录。远程浏览器访问必须配置以 /api/system/oidc/callback 结尾的公网 HTTPS 回调地址;思源的本机监听地址仅适用于本机浏览器登录,不能作为远程浏览器或移动端的固定回调地址。Custom 和 Microsoft 提供商需要填写签发者地址,GitHub 需要填写客户端密钥。通过准入规则的身份都会获得管理员权限,请尽量不要授予所有已认证用户管理员权限,并优先使用精确匹配规则;按邮箱准入时通常还应要求 email_verified 等于 true。配置只有在“验证并保存”完成一次真实的提供商登录后才会生效。Docker 部署需要配置 SIYUAN_OIDC_ENABLED、SIYUAN_OIDC_PROVIDER、SIYUAN_OIDC_CLIENT_ID,以及按需配置 SIYUAN_OIDC_ISSUER_URL、SIYUAN_OIDC_CLIENT_SECRET、SIYUAN_OIDC_SCOPES、SIYUAN_OIDC_REDIRECT_URL、SIYUAN_OIDC_ALLOW_ALL 和 SIYUAN_OIDC_CLAIM_RULES。"
}
]
},
@@ -299,12 +299,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120003-oidcmob",
- "updated": "20260804120003"
+ "updated": "20260804165001"
},
"Children": [
{
"Type": "NodeText",
- "Data": "原生移动端固定使用 siyuan:/oidc-callback,请在身份提供商中原样注册。Google 不接受该移动回调格式,因此 Google 仅支持浏览器和桌面端登录。"
+ "Data": "原生移动端固定使用 siyuan:/oidc-callback,请在身份提供商中原样注册;移动端配置验证也会使用该回调,只有成功返回思源后才会保存。Google 不接受该移动回调格式,因此 Google 仅支持浏览器和桌面端登录。出现 redirect_uri 不匹配通常表示注册的回调在协议、斜线、路径或端口上不完全一致;发现提供商失败通常表示签发者地址错误或无法访问,交换授权码失败则通常需要检查客户端 ID 和客户端密钥。"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy
index 174c7f227c..ddbdb8b8ed 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy
@@ -6,7 +6,7 @@
"id": "20211226122523-rl8356a",
"title": "在瀏覽器上使用",
"type": "doc",
- "updated": "20260804120200"
+ "updated": "20260804165002"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122545-a65v8e1",
- "updated": "20260804120200"
+ "updated": "20260804165002"
},
"Children": [
{
@@ -239,7 +239,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260804120201-oidclog",
- "updated": "20260804120201"
+ "updated": "20260804165002"
},
"Children": [
{
@@ -253,7 +253,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120202-oidcset",
- "updated": "20260804120202"
+ "updated": "20260804165002"
},
"Children": [
{
@@ -276,7 +276,7 @@
},
{
"Type": "NodeText",
- "Data": " 中設定 OIDC 登入。遠端瀏覽器存取必須設定以 /api/system/oidc/callback 結尾的公開 HTTPS 回呼位址;思源的本機監聽位址僅適用於本機瀏覽器登入,不能作為遠端瀏覽器或行動端的固定回呼位址。"
+ "Data": " 中設定 OIDC 登入。遠端瀏覽器存取必須設定以 /api/system/oidc/callback 結尾的公開 HTTPS 回呼位址;思源的本機監聽位址僅適用於本機瀏覽器登入,不能作為遠端瀏覽器或行動端的固定回呼位址。Custom 和 Microsoft 提供者需要填寫簽發者位址,GitHub 需要填寫用戶端密鑰。通過準入規則的身分都會獲得管理員權限,請盡量不要授予所有已驗證使用者管理員權限,並優先使用精確比對規則;按電子郵件準入時通常還應要求 email_verified 等於 true。設定只有在「驗證並儲存」完成一次真實的提供者登入後才會生效。Docker 部署需要設定 SIYUAN_OIDC_ENABLED、SIYUAN_OIDC_PROVIDER、SIYUAN_OIDC_CLIENT_ID,以及按需設定 SIYUAN_OIDC_ISSUER_URL、SIYUAN_OIDC_CLIENT_SECRET、SIYUAN_OIDC_SCOPES、SIYUAN_OIDC_REDIRECT_URL、SIYUAN_OIDC_ALLOW_ALL 和 SIYUAN_OIDC_CLAIM_RULES。"
}
]
},
@@ -285,12 +285,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260804120203-oidcmob",
- "updated": "20260804120203"
+ "updated": "20260804165002"
},
"Children": [
{
"Type": "NodeText",
- "Data": "原生行動端固定使用 siyuan:/oidc-callback,請在身分提供者中原樣註冊。Google 不接受此行動回呼格式,因此 Google 僅支援瀏覽器和桌面端登入。"
+ "Data": "原生行動端固定使用 siyuan:/oidc-callback,請在身分提供者中原樣註冊;行動端設定驗證也會使用此回呼,只有成功返回思源後才會儲存。Google 不接受此行動回呼格式,因此 Google 僅支援瀏覽器和桌面端登入。出現 redirect_uri 不相符通常表示註冊的回呼在通訊協定、斜線、路徑或連接埠上不完全一致;發現提供者失敗通常表示簽發者位址錯誤或無法存取,交換授權碼失敗則通常需要檢查用戶端 ID 和用戶端密鑰。"
}
]
}
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index f1c8cd6586..1a78e38c6b 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -8,7 +8,7 @@ import {showMessage} from "../../dialog/message";
/// #if !BROWSER
import {shell} from "electron";
/// #endif
-import {isInMobileApp, saveExportFile} from "../../protyle/util/compatibility";
+import {isInAndroid, isInHarmony, isInIOS, isInMobileApp, saveExportFile} from "../../protyle/util/compatibility";
import {openByMobile} from "../../editor/openLink";
import {bindPasswordIconaToggle, genConfigItemMainHtml} from "../render/fragments";
import {renderPublishAuthAccounts, savePublish, sendAccessSetting, updatePublishConfig} from "./accessRuntime";
@@ -88,6 +88,7 @@ const mountOIDCButton = (root: HTMLElement) => {
root.querySelector("#oidcConfig")?.addEventListener("click", () => {
const config = window.siyuan.config.oidc;
const escape = (value: string) => Lute.EscapeHTMLStr(value);
+ let destroyOIDCDialog: () => void = () => undefined;
const dialog = new Dialog({
title: window.siyuan.languages.oidcLogin,
content: `<div class="b3-dialog__content" id="oidcConfigForm">
@@ -131,7 +132,7 @@ const mountOIDCButton = (root: HTMLElement) => {
<input data-field="redirectURL" class="b3-text-field fn__block" spellcheck="false" value="${escape(config.redirectURL)}">
</div>
<label class="b3-label b3-label--inner fn__flex">
- <div class="fn__flex-1"><div class="config-name">${window.siyuan.languages.oidcAllowAll}</div></div>
+ <div class="fn__flex-1"><div class="config-name ft__error">${window.siyuan.languages.oidcAllowAll}</div></div>
<span class="fn__space"></span>
<input type="checkbox" data-field="allowAll" class="b3-switch fn__flex-center"${config.allowAll ? " checked" : ""}>
</label>
@@ -146,6 +147,8 @@ const mountOIDCButton = (root: HTMLElement) => {
<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",
height: "80vh",
+ disableClose: true,
+ destroyCallback: () => destroyOIDCDialog(),
});
const form = dialog.element.querySelector<HTMLElement>("#oidcConfigForm");
const buttons = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-dialog__action .b3-button");
@@ -154,6 +157,12 @@ const mountOIDCButton = (root: HTMLElement) => {
let validationPollTimer = 0;
let validationWindow: Window | null = null;
let validationCancelled = false;
+ let validationPollToken = "";
+ let validationPollInFlight = false;
+ let validationActivating = false;
+ let mobileCallbackInstalled = false;
+ let previousMobileCallback: ((callbackURL: string) => void) | undefined;
+ let previousMobileAuthError: ((message: string) => void) | undefined;
const refreshSections = () => {
const provider = form.querySelector<HTMLSelectElement>('[data-field="provider"]').value;
const enabled = form.querySelector<HTMLInputElement>('[data-field="enabled"]').checked;
@@ -173,6 +182,30 @@ const mountOIDCButton = (root: HTMLElement) => {
window.clearInterval(validationPollTimer);
validationPollTimer = 0;
};
+ const restoreMobileCallback = () => {
+ if (!mobileCallbackInstalled) {
+ return;
+ }
+ window.handleOIDCCallback = previousMobileCallback;
+ window.handleOIDCAuthError = previousMobileAuthError;
+ previousMobileCallback = undefined;
+ previousMobileAuthError = undefined;
+ mobileCallbackInstalled = false;
+ };
+ const cancelValidation = () => {
+ validationCancelled = true;
+ stopValidation();
+ validationWindow?.close();
+ validationWindow = null;
+ restoreMobileCallback();
+ if (validationPollToken && !validationActivating) {
+ void fetchSyncPost("/api/system/oidc/validateCancel", {
+ pollToken: validationPollToken,
+ }, undefined, false).catch(() => undefined);
+ }
+ validationPollToken = "";
+ };
+ destroyOIDCDialog = cancelValidation;
const setValidationPending = (pending: boolean) => {
buttons[1].disabled = pending;
form.querySelector<HTMLElement>('[data-section="validationStatus"]').classList.toggle("fn__none", !pending);
@@ -181,17 +214,60 @@ const mountOIDCButton = (root: HTMLElement) => {
}
};
const validationFailed = (message?: string) => {
- stopValidation();
- validationWindow?.close();
- validationWindow = null;
- setValidationPending(false);
+ validationActivating = false;
+ buttons[0].disabled = false;
+ cancelValidation();
+ if (dialog.element.isConnected) {
+ setValidationPending(false);
+ }
showMessage(message || window.siyuan.languages.oidcVerificationFailed, 6000, "error");
};
+ const installMobileCallback = () => {
+ if (!isInMobileApp() || mobileCallbackInstalled) {
+ return;
+ }
+ previousMobileCallback = window.handleOIDCCallback;
+ previousMobileAuthError = window.handleOIDCAuthError;
+ mobileCallbackInstalled = true;
+ const handleMobileCallback = (callbackURL: string, retryCount = 0) => {
+ if (validationCancelled || !dialog.element.isConnected) {
+ return;
+ }
+ void fetchSyncPost("/api/system/oidc/mobileCallback", {callbackURL}, undefined, false).then((response) => {
+ if (validationCancelled || !dialog.element.isConnected) {
+ return;
+ }
+ if (response.code !== 0) {
+ validationFailed(response.msg);
+ }
+ }).catch((error) => {
+ if (retryCount < 4 && !validationCancelled && dialog.element.isConnected) {
+ window.setTimeout(() => handleMobileCallback(callbackURL, retryCount + 1), 1000 * (retryCount + 1));
+ return;
+ }
+ validationFailed(error instanceof Error ? error.message : String(error));
+ });
+ };
+ window.handleOIDCCallback = handleMobileCallback;
+ window.handleOIDCAuthError = (message: string) => validationFailed(message);
+ };
const openValidationURL = (url: string) => {
if (validationWindow) {
validationWindow.location.href = url;
return;
}
+ if (isInAndroid()) {
+ window.JSAndroid.openAuthURL(url);
+ return;
+ }
+ if (isInIOS()) {
+ window.webkit.messageHandlers.openAuthURL.postMessage(url);
+ return;
+ }
+ if (isInHarmony()) {
+ window.JSHarmony.openAuthURL(url);
+ return;
+ }
/// #if !BROWSER
void shell.openExternal(url).catch((error: Error) => validationFailed(error.message));
/// #else
@@ -199,8 +275,15 @@ const mountOIDCButton = (root: HTMLElement) => {
/// #endif
};
const pollValidation = async (pollToken: string) => {
+ if (validationCancelled || validationPollInFlight || validationActivating) {
+ return;
+ }
+ validationPollInFlight = true;
try {
const response = await fetchSyncPost("/api/system/oidc/validatePoll", {pollToken}, undefined, false);
+ if (validationCancelled || !dialog.element.isConnected) {
+ return;
+ }
if (response.code !== 0) {
validationFailed(response.msg);
return;
@@ -210,17 +293,26 @@ const mountOIDCButton = (root: HTMLElement) => {
}
stopValidation();
validationWindow?.close();
- window.siyuan.config.oidc = response.data.config;
+ validationActivating = true;
+ buttons[0].disabled = true;
+ const activation = await fetchSyncPost("/api/system/oidc/validateActivate", {pollToken}, undefined, false);
+ if (activation.code !== 0) {
+ validationFailed(activation.msg);
+ return;
+ }
+ validationPollToken = "";
+ restoreMobileCallback();
+ window.siyuan.config.oidc = activation.data.config;
showMessage(window.siyuan.languages.oidcVerificationSuccess);
dialog.destroy();
} catch (error) {
validationFailed(error instanceof Error ? error.message : String(error));
+ } finally {
+ validationPollInFlight = false;
}
};
buttons[0].addEventListener("click", () => {
- validationCancelled = true;
- stopValidation();
- validationWindow?.close();
+ cancelValidation();
dialog.destroy();
});
buttons[1].addEventListener("click", () => {
@@ -240,6 +332,7 @@ const mountOIDCButton = (root: HTMLElement) => {
};
if (nextConfig.enabled) {
validationCancelled = false;
+ validationActivating = false;
setValidationPending(true);
buttons[1].textContent = window.siyuan.languages.oidcVerifying;
if (isBrowser() && !isInMobileApp()) {
@@ -253,12 +346,19 @@ const mountOIDCButton = (root: HTMLElement) => {
void fetchSyncPost("/api/system/oidc/validate", nextConfig, undefined, false).then((response) => {
if (validationCancelled || !dialog.element.isConnected) {
validationWindow?.close();
+ if (response.code === 0 && response.data.pollToken) {
+ void fetchSyncPost("/api/system/oidc/validateCancel", {
+ pollToken: response.data.pollToken,
+ }, undefined, false).catch(() => undefined);
+ }
return;
}
if (response.code !== 0) {
validationFailed(response.msg);
return;
}
+ validationPollToken = response.data.pollToken;
+ installMobileCallback();
openValidationURL(response.data.authURL);
validationPollTimer = window.setInterval(() => {
void pollValidation(response.data.pollToken);
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 5754d636a3..516bd235c3 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -195,6 +195,8 @@ interface CSSStyleDeclarationElectron extends CSSStyleDeclaration {
}
interface Window {
+ handleOIDCCallback?: (callbackURL: string) => void;
+ handleOIDCAuthError?: (message: string) => void;
DOMPurify: {
sanitize(dirty: string, options?: any): string;
};
@@ -272,6 +274,7 @@ interface Window {
saveExportFile: { postMessage: (url: string) => void }
saveExportFileV2?: { postMessage: (data: {uri: string, requestID: string}) => void }
openLink: { postMessage: (url: string) => void }
+ openAuthURL: { postMessage: (url: string) => void }
startKernelFast: { postMessage: (url: string) => void }
changeStatusBar: { postMessage: (url: string) => void }
setClipboard: { postMessage: (url: string) => void }
@@ -296,6 +299,7 @@ interface Window {
};
siyuan: ISiyuan;
JSAndroid: {
+ openAuthURL(url: string): void
returnDesktop(): void
openExternal(url: string): void
exportByDefault(url: string): void
@@ -321,6 +325,7 @@ interface Window {
logInputEvent?(details: string): void
};
JSHarmony: {
+ openAuthURL(url: string): void
showKeyboard(): void
hideKeyboard(): void
openExternal(url: string): void
diff --git a/app/stage/auth.html b/app/stage/auth.html
index 074226248d..fc6fd63555 100644
--- a/app/stage/auth.html
+++ b/app/stage/auth.html
@@ -174,6 +174,12 @@
font-size: 12px;
margin: 16px 0;
}
+
+ .auth-actions {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
</style>
</head>
<body>
@@ -191,12 +197,14 @@
<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>
- {{if .accessAuthCodeEnabled}}<button class="b3-button" onclick="submitAuth()">{{.l1}}</button>{{end}}
- {{if .oidcEnabled}}<button class="b3-button" id="oidcLogin" onclick="startOIDC()">{{.l12}}</button>{{end}}
- {{if .accessAuthCodeEnabled}}<div class="ft__on-surface">
- {{.l2}}
- </div>{{end}}
- <button class="b3-button b3-button--white" onclick="exitSiYuan()">{{.l5}}</button>
+ <div class="auth-actions">
+ {{if .accessAuthCodeEnabled}}<button class="b3-button" onclick="submitAuth()">{{.l1}}</button>{{end}}
+ {{if .oidcEnabled}}<button class="b3-button" id="oidcLogin" onclick="startOIDC()">{{.l12}}</button>{{end}}
+ {{if .accessAuthCodeEnabled}}<div class="ft__on-surface">
+ {{.l2}}
+ </div>{{end}}
+ <button class="b3-button b3-button--white" onclick="exitSiYuan()">{{.l5}}</button>
+ </div>
<div class="ft__on-surface">
{{.l7}}
</div>
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 00e204c12d..6eb9706f7c 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -57,6 +57,8 @@ func ServeAPI(ginServer *gin.Engine) {
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/oidc/validate", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, model.OIDCValidateStart)
+ ginServer.Handle("POST", "/api/system/oidc/validateActivate", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, model.OIDCValidateActivate)
+ ginServer.Handle("POST", "/api/system/oidc/validateCancel", model.CheckAuth, model.CheckAdminRole, model.OIDCValidateCancel)
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 be34a6eef9..18f682d508 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -877,6 +877,22 @@ func setAccessAuthCode(c *gin.Context) {
ret.Msg = model.Conf.Language(355)
return
}
+ if aac == "" {
+ currentOIDC := model.Conf.GetOIDC()
+ var err error
+ if util.IsMobileContainer() {
+ err = model.ValidateOIDCMobileConfiguration(currentOIDC)
+ } else if !model.IsLocalRequest(c) {
+ err = model.ValidateOIDCConfigurationChange(c.Request.Context(), currentOIDC, true, false,
+ util.SiYuanAccessAuthCodeBypass)
+ }
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(369)
+ logging.LogWarnf("reject clearing the last usable access authentication method [ip=%s]: %s", c.ClientIP(), err)
+ return
+ }
+ }
model.Conf.AccessAuthCode = aac
model.Conf.Save()
diff --git a/kernel/api/system_test.go b/kernel/api/system_test.go
index 0ce76523da..9f9342f497 100644
--- a/kernel/api/system_test.go
+++ b/kernel/api/system_test.go
@@ -73,6 +73,81 @@ func TestSetOIDCRejectsUnverifiedEnabledConfiguration(t *testing.T) {
}
}
+func TestSetAccessAuthCodeRejectsRemoteAuthenticationLockout(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ previousConf := model.Conf
+ previousReadOnly := util.ReadOnly
+ previousBypass := util.SiYuanAccessAuthCodeBypass
+ model.Conf = model.NewAppConf()
+ model.Conf.CookieKey = "access-auth-api-test-cookie-key"
+ model.Conf.AccessAuthCode = "existing-code"
+ util.ReadOnly = true
+ util.SiYuanAccessAuthCodeBypass = false
+ t.Cleanup(func() {
+ model.Conf = previousConf
+ util.ReadOnly = previousReadOnly
+ util.SiYuanAccessAuthCodeBypass = previousBypass
+ })
+
+ engine := gin.New()
+ engine.POST("/api/system/setAccessAuthCode", setAccessAuthCode)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "https://notes.example.com/api/system/setAccessAuthCode",
+ strings.NewReader(`{"accessAuthCode":""}`))
+ request.RemoteAddr = "203.0.113.2:1234"
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ response := &struct {
+ Code int `json:"code"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal setAccessAuthCode response failed: %v", err)
+ }
+ if response.Code != -1 || model.Conf.AccessAuthCode != "existing-code" {
+ t.Fatalf("remote access authentication lockout was accepted: %s", recorder.Body.String())
+ }
+}
+
+func TestSetAccessAuthCodeRejectsUnsupportedMobileOIDC(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ previousConf := model.Conf
+ previousReadOnly := util.ReadOnly
+ previousContainer := util.Container
+ model.Conf = model.NewAppConf()
+ model.Conf.CookieKey = "mobile-access-auth-api-test-cookie-key"
+ model.Conf.AccessAuthCode = "existing-code"
+ model.Conf.OIDC = &conf.OIDC{
+ Enabled: true, Provider: conf.OIDCProviderGoogle, ClientID: "client-id", AllowAll: true,
+ }
+ util.ReadOnly = true
+ util.Container = util.ContainerAndroid
+ t.Cleanup(func() {
+ model.Conf = previousConf
+ util.ReadOnly = previousReadOnly
+ util.Container = previousContainer
+ })
+
+ engine := gin.New()
+ engine.POST("/api/system/setAccessAuthCode", setAccessAuthCode)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/api/system/setAccessAuthCode",
+ strings.NewReader(`{"accessAuthCode":""}`))
+ request.RemoteAddr = "127.0.0.1:1234"
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ response := &struct {
+ Code int `json:"code"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal mobile setAccessAuthCode response failed: %v", err)
+ }
+ if response.Code != -1 || model.Conf.AccessAuthCode != "existing-code" {
+ t.Fatalf("unsupported mobile OIDC lockout was accepted: %s", recorder.Body.String())
+ }
+}
+
func TestGetConfUILayoutByRole(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/kernel/model/auth_session.go b/kernel/model/auth_session.go
index d3d91afa4b..bcdf16a182 100644
--- a/kernel/model/auth_session.go
+++ b/kernel/model/auth_session.go
@@ -72,11 +72,18 @@ func oidcConfigurationVersion(config *conf.OIDC) string {
if Conf == nil || Conf.CookieKey == "" || config == nil {
return ""
}
+ return oidcConfigurationVersionWithKey(Conf.CookieKey, config)
+}
+
+func oidcConfigurationVersionWithKey(cookieKey string, config *conf.OIDC) string {
+ if cookieKey == "" || config == nil {
+ return ""
+ }
data, err := gulu.JSON.MarshalJSON(config)
if err != nil {
return ""
}
- mac := hmac.New(sha256.New, []byte(Conf.CookieKey))
+ mac := hmac.New(sha256.New, []byte(cookieKey))
_, _ = mac.Write(data)
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index c0d7113851..9602624279 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -23,6 +23,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "reflect"
"runtime"
"sort"
"strconv"
@@ -182,6 +183,28 @@ func (appConf *AppConf) SetOIDC(config *conf.OIDC) {
appConf.Save()
}
+// CompareAndSetOIDC 仅在当前配置版本仍与预期一致时写入 OIDC 配置。
+func (appConf *AppConf) CompareAndSetOIDC(expectedVersion string, config *conf.OIDC) (changed, swapped bool) {
+ appConf.m.Lock()
+ current := appConf.OIDC
+ if current == nil {
+ current = conf.NewOIDC()
+ }
+ if oidcConfigurationVersionWithKey(appConf.CookieKey, current) != expectedVersion {
+ appConf.m.Unlock()
+ return false, false
+ }
+ changed = !reflect.DeepEqual(current, config)
+ if changed {
+ appConf.OIDC = config
+ }
+ appConf.m.Unlock()
+ if changed {
+ appConf.Save()
+ }
+ return changed, true
+}
+
func (conf *AppConf) SetAI(ai *conf.AI) {
conf.m.Lock()
conf.AI = ai
diff --git a/kernel/model/oidc.go b/kernel/model/oidc.go
index 884dc8e60b..f44bac8a93 100644
--- a/kernel/model/oidc.go
+++ b/kernel/model/oidc.go
@@ -17,7 +17,6 @@ import (
"fmt"
"net/http"
"net/url"
- "reflect"
"strings"
"sync"
"time"
@@ -48,26 +47,27 @@ const (
)
type oidcTransaction struct {
- State string
- Nonce string
- CodeVerifier string
- PollToken string
- Binding string
- ClientIP string
- Flow string
- RedirectURL string
- To string
- ConfigVersion string
- RememberMe bool
- Claimed bool
- Completed bool
- Success bool
- Message string
- ExpiresAt time.Time
- Done chan struct{}
- Config *conf.OIDC
- Provider *oidc_provider.Provider
- Activated bool
+ State string
+ Nonce string
+ CodeVerifier string
+ PollToken string
+ Binding string
+ ClientIP string
+ Flow string
+ RedirectURL string
+ To string
+ ConfigVersion string
+ RememberMe bool
+ Claimed bool
+ Completed bool
+ Success bool
+ Message string
+ ExpiresAt time.Time
+ Done chan struct{}
+ Config *conf.OIDC
+ Provider *oidc_provider.Provider
+ Activated bool
+ MobileValidation bool
}
var oidcTransactions = struct {
@@ -107,6 +107,13 @@ func OIDCValidateStart(c *gin.Context) {
return
}
config.Normalize()
+ mobileValidation := util.IsMobileContainer()
+ if mobileValidation && config.Provider == conf.OIDCProviderGoogle {
+ ret.Code = -1
+ ret.Msg = oidcLanguage(368, "This OIDC provider does not support the SiYuan mobile callback URI")
+ logging.LogErrorf("validate mobile OIDC candidate configuration failed [ip=%s]: Google does not support the fixed SiYuan mobile OIDC callback URI", c.ClientIP())
+ return
+ }
requireRemoteAuthentication := util.ContainerDocker == util.Container || !IsLocalRequest(c)
if err := ValidateOIDCConfigurationChange(c.Request.Context(), config, requireRemoteAuthentication,
Conf.AccessAuthCode != "", util.SiYuanAccessAuthCodeBypass); err != nil {
@@ -115,7 +122,7 @@ func OIDCValidateStart(c *gin.Context) {
logging.LogErrorf("validate OIDC candidate configuration failed [ip=%s]: %s", c.ClientIP(), err)
return
}
- redirectURL, err := oidcValidationRedirectURL(c, config)
+ redirectURL, err := oidcValidationRedirectURL(c, config, mobileValidation)
if err != nil {
ret.Code = -1
ret.Msg = oidcLanguage(369, "Invalid OIDC configuration")
@@ -150,6 +157,7 @@ func OIDCValidateStart(c *gin.Context) {
}
transaction.Config = config
transaction.Provider = provider
+ transaction.MobileValidation = mobileValidation
if err = session.Save(c); err != nil {
ret.Code = -1
ret.Msg = Conf.Language(258)
@@ -263,7 +271,7 @@ func OIDCCallback(c *gin.Context) {
respondRepeatedOIDCCallback(c, transaction)
return
}
- if transaction.Flow == oidcFlowMobile {
+ if transaction.Flow == oidcFlowMobile || (transaction.Flow == oidcFlowValidate && transaction.MobileValidation) {
completeOIDCTransaction(transaction.State, false, oidcUserMessage())
writeOIDCCallbackPage(c, false, oidcUserMessage())
return
@@ -333,6 +341,10 @@ func OIDCMobileCallback(c *gin.Context) {
return
}
if repeated {
+ if transaction.Flow == oidcFlowValidate && transaction.MobileValidation && transaction.Success {
+ ret.Data = map[string]any{"validation": true}
+ return
+ }
if transaction.Flow != oidcFlowMobile || !transaction.Success {
ret.Code = -1
ret.Msg = oidcUserMessage()
@@ -346,7 +358,7 @@ func OIDCMobileCallback(c *gin.Context) {
ret.Data = map[string]any{"to": safeOIDCRedirectTarget(transaction.To)}
return
}
- if transaction.Flow != oidcFlowMobile {
+ if transaction.Flow != oidcFlowMobile && !(transaction.Flow == oidcFlowValidate && transaction.MobileValidation) {
ret.Code = -1
ret.Msg = oidcUserMessage()
completeOIDCTransaction(transaction.State, false, ret.Msg)
@@ -366,6 +378,11 @@ func OIDCMobileCallback(c *gin.Context) {
completeOIDCTransaction(transaction.State, false, ret.Msg)
return
}
+ if transaction.Flow == oidcFlowValidate {
+ completeOIDCTransaction(transaction.State, true, "")
+ ret.Data = map[string]any{"validation": true}
+ return
+ }
if err = authenticateOIDCSession(c, transaction.RememberMe); err != nil {
ret.Code = -1
ret.Msg = oidcUserMessage()
@@ -434,6 +451,19 @@ func OIDCValidatePoll(c *gin.Context) {
ret.Msg = transaction.Message
return
}
+ ret.Data = map[string]any{"status": "completed"}
+}
+
+func OIDCValidateActivate(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 = oidcLanguage(369, "Invalid OIDC configuration")
+ return
+ }
+ workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
activated, err := activateOIDCValidation(input.PollToken, workspaceSession.OIDCBinding)
if err != nil {
ret.Code = -1
@@ -458,6 +488,22 @@ func OIDCValidatePoll(c *gin.Context) {
ret.Data = map[string]any{"status": "completed", "config": masked.OIDC}
}
+func OIDCValidateCancel(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 = oidcLanguage(369, "Invalid OIDC configuration")
+ return
+ }
+ workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
+ if !cancelOIDCValidation(input.PollToken, workspaceSession.OIDCBinding) {
+ ret.Code = -1
+ ret.Msg = oidcLanguage(369, "Invalid OIDC configuration")
+ }
+}
+
func validateOIDCConfiguration() error {
return ValidateOIDCConfiguration(Conf.GetOIDC())
}
@@ -505,6 +551,16 @@ func ValidateOIDCConfiguration(config *conf.OIDC) error {
return nil
}
+func ValidateOIDCMobileConfiguration(config *conf.OIDC) error {
+ if err := ValidateOIDCConfiguration(config); err != nil {
+ return err
+ }
+ if config.Provider == conf.OIDCProviderGoogle {
+ return errors.New("Google does not support the fixed SiYuan mobile OIDC callback URI")
+ }
+ return nil
+}
+
func ValidateOIDCProviderConfiguration(ctx context.Context, config *conf.OIDC) error {
if err := ValidateOIDCConfiguration(config); err != nil {
return err
@@ -559,7 +615,10 @@ func effectiveOIDCRedirectURL(c *gin.Context, flow string) (string, error) {
return scheme + "://" + host + "/api/system/oidc/callback", nil
}
-func oidcValidationRedirectURL(c *gin.Context, config *conf.OIDC) (string, error) {
+func oidcValidationRedirectURL(c *gin.Context, config *conf.OIDC, mobile bool) (string, error) {
+ if mobile {
+ return oidcMobileRedirectURL, nil
+ }
if config.RedirectURL != "" {
return validatePublicOIDCRedirectURL(config.RedirectURL)
}
@@ -776,19 +835,30 @@ func activateOIDCValidation(pollToken, binding string) (activated bool, err erro
if transaction.Config == nil {
return false, errors.New("OIDC validation configuration is missing")
}
- if transaction.ConfigVersion != oidcConfigurationVersion(Conf.GetOIDC()) {
+ configurationChanged, swapped := Conf.CompareAndSetOIDC(transaction.ConfigVersion, transaction.Config)
+ if !swapped {
deleteOIDCTransactionLocked(state)
return false, errors.New("OIDC configuration changed during validation")
}
- configurationChanged := !reflect.DeepEqual(Conf.GetOIDC(), transaction.Config)
- if configurationChanged {
- Conf.SetOIDC(transaction.Config)
- }
transaction.Config = nil
transaction.Activated = true
return configurationChanged, nil
}
+func cancelOIDCValidation(pollToken, binding string) bool {
+ oidcTransactions.Lock()
+ defer oidcTransactions.Unlock()
+ cleanupOIDCTransactionsLocked()
+ state := oidcTransactions.byPoll[pollToken]
+ transaction := oidcTransactions.byState[state]
+ if transaction == nil || transaction.Flow != oidcFlowValidate || transaction.Activated || transaction.Binding == "" ||
+ binding == "" || transaction.Binding != binding {
+ return false
+ }
+ deleteOIDCTransactionLocked(state)
+ return true
+}
+
func deleteOIDCTransactionLocked(state string) {
if transaction := oidcTransactions.byState[state]; transaction != nil {
if !transaction.Completed && transaction.Done != nil {
diff --git a/kernel/model/oidc_test.go b/kernel/model/oidc_test.go
index f27b6aea1b..7feb79cdce 100644
--- a/kernel/model/oidc_test.go
+++ b/kernel/model/oidc_test.go
@@ -18,6 +18,8 @@ import (
"testing"
"time"
+ ginSessions "github.com/gin-contrib/sessions"
+ "github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -80,6 +82,21 @@ func TestValidateOIDCConfigurationRejectsInsecureIssuer(t *testing.T) {
}
}
+func TestValidateOIDCMobileConfigurationRejectsUnsupportedProvider(t *testing.T) {
+ setupOIDCTest(t)
+ config := Conf.GetOIDC()
+ config.Provider = conf.OIDCProviderGoogle
+ config.IssuerURL = ""
+ if err := ValidateOIDCMobileConfiguration(config); err == nil {
+ t.Fatal("Google was accepted for the fixed mobile OIDC callback")
+ }
+ config.Provider = conf.OIDCProviderCustom
+ config.IssuerURL = "https://issuer.example.com"
+ if err := ValidateOIDCMobileConfiguration(config); err != nil {
+ t.Fatalf("custom OIDC provider was rejected for mobile validation: %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 {
@@ -114,6 +131,9 @@ func TestEffectiveOIDCRedirectURLForLocalAndRemoteFlows(t *testing.T) {
if redirect, err := effectiveOIDCRedirectURL(local, oidcFlowMobile); err != nil || redirect != oidcMobileRedirectURL {
t.Fatalf("mobile OIDC redirect changed: %q, %v", redirect, err)
}
+ if redirect, err := oidcValidationRedirectURL(local, Conf.GetOIDC(), true); err != nil || redirect != oidcMobileRedirectURL {
+ t.Fatalf("mobile OIDC validation did not use the native callback: %q, %v", redirect, err)
+ }
Conf.OIDC.RedirectURL = "https://notes.example.com/api/system/oidc/callback"
remote := contextFor("203.0.113.2:12345", "notes.example.com", nil)
@@ -327,6 +347,56 @@ func TestActivateOIDCValidationRejectsChangedConfiguration(t *testing.T) {
}
}
+func TestCancelOIDCValidationPreventsActivation(t *testing.T) {
+ setupOIDCTest(t)
+ candidate := Conf.GetOIDC()
+ candidate.ClientID = "cancelled-client-id"
+ transaction := &oidcTransaction{
+ State: "cancelled-validation-state",
+ PollToken: "cancelled-validation-poll-token",
+ Binding: "validation-binding",
+ Flow: oidcFlowValidate,
+ ConfigVersion: oidcConfigurationVersion(Conf.GetOIDC()),
+ Completed: true,
+ Success: true,
+ Config: candidate,
+ ExpiresAt: time.Now().Add(time.Minute),
+ }
+ if err := storeOIDCTransaction(transaction); err != nil {
+ t.Fatal(err)
+ }
+ if !cancelOIDCValidation(transaction.PollToken, transaction.Binding) {
+ t.Fatal("bound OIDC validation could not be cancelled")
+ }
+ if activated, err := activateOIDCValidation(transaction.PollToken, transaction.Binding); err == nil || activated {
+ t.Fatalf("cancelled OIDC validation was activated: activated=%v, err=%v", activated, err)
+ }
+ if Conf.GetOIDC().ClientID == candidate.ClientID {
+ t.Fatal("cancelled OIDC validation changed the active configuration")
+ }
+}
+
+func TestCompareAndSetOIDCRejectsStaleVersion(t *testing.T) {
+ setupOIDCTest(t)
+ previousReadOnly := util.ReadOnly
+ util.ReadOnly = true
+ t.Cleanup(func() { util.ReadOnly = previousReadOnly })
+ expectedVersion := oidcConfigurationVersion(Conf.GetOIDC())
+ first := Conf.GetOIDC()
+ first.ClientID = "first-client-id"
+ if changed, swapped := Conf.CompareAndSetOIDC(expectedVersion, first); !changed || !swapped {
+ t.Fatalf("current OIDC configuration was not swapped: changed=%v, swapped=%v", changed, swapped)
+ }
+ stale := Conf.GetOIDC()
+ stale.ClientID = "stale-client-id"
+ if changed, swapped := Conf.CompareAndSetOIDC(expectedVersion, stale); changed || swapped {
+ t.Fatalf("stale OIDC configuration was swapped: changed=%v, swapped=%v", changed, swapped)
+ }
+ if Conf.GetOIDC().ClientID != first.ClientID {
+ t.Fatal("stale OIDC configuration overwrote the current configuration")
+ }
+}
+
func TestApplyOIDCEnvironmentOverridesStoredConfiguration(t *testing.T) {
t.Setenv("SIYUAN_OIDC_ENABLED", "true")
t.Setenv("SIYUAN_OIDC_PROVIDER", conf.OIDCProviderGitHub)
@@ -515,6 +585,36 @@ func TestOIDCSessionVersionInvalidatesOnConfigurationChange(t *testing.T) {
}
}
+func TestApplyAuthenticatedSessionRememberMeCookie(t *testing.T) {
+ setupOIDCTest(t)
+ gin.SetMode(gin.TestMode)
+ renderCookie := func(rememberMe bool) string {
+ engine := gin.New()
+ store := cookie.NewStore([]byte("oidc-remember-me-test-key"))
+ engine.Use(ginSessions.Sessions("siyuan", store))
+ engine.POST("/login", func(c *gin.Context) {
+ session := util.GetSession(c)
+ workspaceSession := util.GetWorkspaceSession(session)
+ applyAuthenticatedSession(c, workspaceSession, rememberMe)
+ if err := session.Save(c); err != nil {
+ c.Status(http.StatusInternalServerError)
+ return
+ }
+ c.Status(http.StatusNoContent)
+ })
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/login", nil)
+ engine.ServeHTTP(recorder, request)
+ return recorder.Header().Get("Set-Cookie")
+ }
+ if remembered := renderCookie(true); !strings.Contains(remembered, "Max-Age=2592000") {
+ t.Fatalf("remembered OIDC session cookie has no 30-day lifetime: %s", remembered)
+ }
+ if sessionOnly := renderCookie(false); strings.Contains(sessionOnly, "Max-Age=") {
+ t.Fatalf("session-only OIDC cookie unexpectedly has a persistent lifetime: %s", sessionOnly)
+ }
+}
+
func TestOIDCConfigurationVersionTracksDisabledConfiguration(t *testing.T) {
setupOIDCTest(t)
Conf.OIDC.Enabled = false
diff --git a/kernel/server/serve_auth_test.go b/kernel/server/serve_auth_test.go
index aa0346deac..18907351ab 100644
--- a/kernel/server/serve_auth_test.go
+++ b/kernel/server/serve_auth_test.go
@@ -47,8 +47,10 @@ func TestAuthPageHidesLockScreenHelpForOIDCOnly(t *testing.T) {
}
oidcOnlyPage := render(false)
- if strings.Contains(oidcOnlyPage, "lock-screen-help-marker") || !strings.Contains(oidcOnlyPage, `id="oidcLogin"`) {
- t.Fatal("OIDC-only authentication page contains lock screen help or omits OIDC login")
+ if strings.Contains(oidcOnlyPage, "lock-screen-help-marker") ||
+ !strings.Contains(oidcOnlyPage, `id="oidcLogin"`) ||
+ !strings.Contains(oidcOnlyPage, `class="auth-actions"`) {
+ t.Fatal("OIDC-only authentication page contains lock screen help or omits the OIDC action layout")
}
if !strings.Contains(render(true), "lock-screen-help-marker") {
t.Fatal("lock screen authentication page omits lock screen help")