feat(mobile-sso): serve assetlinks.json + App Links redirect allowlist
Add the server side of Android App Links (M9 follow-up, docs/android/APP_LINKS.md): - GET /.well-known/assetlinks.json at the web root, gated by the new admin setting `mobile_app_links_enabled` (default off -> 404; on-but-no-fingerprint -> 404). Emits the Digital Asset Links statement for the fixed published package (MOBILE_APP_PACKAGE) + MOBILE_APP_CERT_SHA256 fingerprint(s). - mobileSso `/start` additionally accepts this shard's own self-origin https://<host>/mobile/callback when App Links are enabled — one additive exact-match entry, derived from APP_BASE_URL/request origin, never client input; the custom-scheme allowlist is never narrowed. The settings lookup is short-circuited for non-https redirects so custom-scheme rejections stay fast. - settings.isMobileAppLinksEnabled() (fail-closed) + getPublic().mobileAppLinks; admin updateSettings validates the boolean; seed default off. Tests: test/appLinks.test.js (route gating + allowlist). Full suite 284 pass. Swagger unchanged (web-root verification file is #swagger.ignore'd). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NgyHnrNa8WwG3doxvxjuCr
This commit is contained in:
@@ -10,6 +10,7 @@ require('dotenv').config()
|
||||
const swaggerUi = require('swagger-ui-express')
|
||||
|
||||
const apiRouter = require('./router/api.router')
|
||||
const wellKnown = require('./router/wellKnown.controller')
|
||||
const brand = require('./config/brand')
|
||||
const createLogger = require('./utils/logger')
|
||||
const { applyTrustProxy, trustProxyDebug } = require('./utils/trustProxy')
|
||||
@@ -143,6 +144,12 @@ app.get(
|
||||
app.use('/api', apiRouter)
|
||||
app.use('/api', (req, res) => res.status(404).json({ message: 'Not found' }))
|
||||
|
||||
// ── /.well-known ──────────────────────────────────────────────────────
|
||||
// Android App Links verification file at the web root (M9 follow-up). Mounted
|
||||
// before the SPA catch-all so it returns JSON, not the index shell. 404s unless
|
||||
// the admin has enabled App Links for this shard (docs/android/APP_LINKS.md).
|
||||
app.get('/.well-known/assetlinks.json', wellKnown.assetlinks)
|
||||
|
||||
// ── Client SPA ────────────────────────────────────────────────────────
|
||||
// Serve the built React app if present; otherwise show a placeholder so the
|
||||
// server is usable API-only before the frontend phase.
|
||||
|
||||
@@ -54,6 +54,22 @@ async function isGameAccountSignupEnabled() {
|
||||
return GAME_SIGNUP_OFFER.includes(await getGameSignupMode())
|
||||
}
|
||||
|
||||
// Android App Links opt-in (M9 follow-up). When on, the shard auto-serves
|
||||
// /.well-known/assetlinks.json and the mobile SSO bridge additionally accepts the
|
||||
// self-origin https://<host>/mobile/callback redirect. Stored as the string
|
||||
// 'true'/'false'; default off. See docs/android/APP_LINKS.md.
|
||||
const MOBILE_APP_LINKS_KEY = 'mobile_app_links_enabled'
|
||||
|
||||
// Fail-closed: any read error (e.g. DB unavailable) reports "disabled" so a
|
||||
// transient fault can never open the https redirect path or serve assetlinks.json.
|
||||
async function isMobileAppLinksEnabled() {
|
||||
try {
|
||||
return String(await settingsDb.get(MOBILE_APP_LINKS_KEY)) === 'true'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function get(key) {
|
||||
return settingsDb.get(key)
|
||||
}
|
||||
@@ -113,6 +129,11 @@ async function getPublic() {
|
||||
// that we use the first NTFY_ALLOWED_ORIGINS entry (a device endpoint must sit
|
||||
// on an allowed origin anyway). Never NTFY_BASE_URL — it may be internal-only.
|
||||
out.push = { ntfyUrl: publicNtfyUrl() }
|
||||
// Whether this shard has opted into Android App Links (M9 follow-up). Lets a
|
||||
// native client tell whether it may request the https App Link redirect_uri
|
||||
// before doing so (the server would otherwise reject an unallowlisted one). The
|
||||
// custom-scheme callback works regardless of this flag.
|
||||
out.mobileAppLinks = String(all[MOBILE_APP_LINKS_KEY]) === 'true'
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -142,4 +163,6 @@ module.exports = {
|
||||
GAME_SIGNUP_MODES,
|
||||
getGameSignupMode,
|
||||
isGameAccountSignupEnabled,
|
||||
MOBILE_APP_LINKS_KEY,
|
||||
isMobileAppLinksEnabled,
|
||||
}
|
||||
|
||||
@@ -512,6 +512,15 @@ async function updateSettings(req, res) {
|
||||
) {
|
||||
return res.status(400).json({ message: 'Invalid game_account_signup value' })
|
||||
}
|
||||
// App Links toggle is a boolean stored as a 'true'/'false' string; accept a real
|
||||
// boolean or those two strings and normalize, reject anything else.
|
||||
if (settings.MOBILE_APP_LINKS_KEY in updates) {
|
||||
const v = updates[settings.MOBILE_APP_LINKS_KEY]
|
||||
if (v !== true && v !== false && v !== 'true' && v !== 'false') {
|
||||
return res.status(400).json({ message: 'Invalid mobile_app_links_enabled value' })
|
||||
}
|
||||
updates[settings.MOBILE_APP_LINKS_KEY] = String(v === true || v === 'true')
|
||||
}
|
||||
// The homepage teaser is rich text (HTML) from the shared editor — sanitize it
|
||||
// against the same allowlist as post/wiki bodies so a stored value is safe (the
|
||||
// client re-sanitizes on render as defense in depth).
|
||||
|
||||
@@ -18,6 +18,7 @@ const users = require('../../../model/users/users.model')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
const mobileSessions = require('../../../model/mobileSessions/mobileSessions.model')
|
||||
const mobileBridge = require('../../../model/mobileAuthBridge/mobileAuthBridge.model')
|
||||
const settings = require('../../../model/settings/settings.model')
|
||||
const sessionService = require('../../../auth/session.service')
|
||||
const ssoState = require('../../../auth/ssoState')
|
||||
const ssoController = require('./sso.controller')
|
||||
@@ -37,6 +38,32 @@ const REDIRECT_ALLOWLIST = new Set(
|
||||
|
||||
const PROVIDER_ID_RE = /^[a-z0-9-]+$/
|
||||
|
||||
// This shard's own https App Link callback. Built from APP_BASE_URL (preferred, so
|
||||
// it is never derived from an attacker-set Host header) or, failing that, the
|
||||
// request's own origin. Path is the fixed /mobile/callback the app's autoVerify
|
||||
// intent-filter is registered for.
|
||||
function selfOriginCallback(req) {
|
||||
const base = (process.env.APP_BASE_URL || '').trim().replace(/\/+$/, '')
|
||||
const origin = base || `${req.protocol}://${req.get('host')}`
|
||||
return `${origin}/mobile/callback`
|
||||
}
|
||||
|
||||
// redirect_uri is valid if it is one of the statically-allowlisted app callbacks
|
||||
// (default the custom scheme), OR — only when the admin has enabled App Links —
|
||||
// this shard's own https://<host>/mobile/callback. EXACT match in both cases; the
|
||||
// App Links entry is additive and never narrows the custom-scheme allowlist.
|
||||
async function isAllowedRedirect(redirectUri, req) {
|
||||
if (REDIRECT_ALLOWLIST.has(redirectUri)) return true
|
||||
// App Links only ever add an https callback, so skip the settings lookup for
|
||||
// anything that can't be one — custom-scheme rejections stay fast and DB-free.
|
||||
if (typeof redirectUri === 'string' && redirectUri.startsWith('https://')) {
|
||||
if (await settings.isMobileAppLinksEnabled()) {
|
||||
return redirectUri === selfOriginCallback(req)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Append query params to an (already-allowlisted) app callback URI.
|
||||
function appDeepLink(redirectUri, params) {
|
||||
const sep = redirectUri.includes('?') ? '&' : '?'
|
||||
@@ -63,7 +90,7 @@ async function start(req, res) {
|
||||
// redirect_uri must be exactly one of the registered app callbacks. Validate
|
||||
// it FIRST — everything else can only be surfaced to the app by redirecting
|
||||
// to a trusted callback, so an untrusted one is a hard 400 (no redirect).
|
||||
if (!REDIRECT_ALLOWLIST.has(redirectUri)) {
|
||||
if (!(await isAllowedRedirect(redirectUri, req))) {
|
||||
log.warn('mobile sso start: redirect_uri not in allowlist', { ip: req.ip })
|
||||
return res.status(400).json({ message: 'Unrecognized redirect URI.' })
|
||||
}
|
||||
|
||||
63
server/src/router/wellKnown.controller.js
Normal file
63
server/src/router/wellKnown.controller.js
Normal file
@@ -0,0 +1,63 @@
|
||||
// ── /.well-known/* — web-root, non-API endpoints ──────────────────────────
|
||||
//
|
||||
// Android App Links verification file (M9 follow-up, docs/android/APP_LINKS.md).
|
||||
// Served at the web root (outside /api/v1) because Android's Play/verifier fetch
|
||||
// it from a fixed path. It is gated by the `mobile_app_links_enabled` admin
|
||||
// setting: off ⇒ 404 (the app stays on the custom-scheme callback for this shard).
|
||||
//
|
||||
// The asserted package + fingerprint are constants of the ONE published app, not
|
||||
// per-shard: the same binary is verifiable against every shard that opts in.
|
||||
|
||||
const settings = require('../model/settings/settings.model')
|
||||
const log = require('../utils/logger')('well-known')
|
||||
|
||||
// Fixed identity of the published app. Overridable via env for a white-label build
|
||||
// that ships under a different package / release cert.
|
||||
const PACKAGE = (process.env.MOBILE_APP_PACKAGE || 'com.runicgateway.app').trim()
|
||||
|
||||
// Release signing-cert SHA-256 fingerprint(s), comma-separated. Multiple entries
|
||||
// support cert rotation (old + new) and a debug + release cert during testing.
|
||||
// Colons and case are normalized to the upper-cased, colon-separated form the
|
||||
// Digital Asset Links spec expects.
|
||||
function fingerprints() {
|
||||
return (process.env.MOBILE_APP_CERT_SHA256 || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim().toUpperCase())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
let warnedNoFingerprint = false
|
||||
|
||||
// GET /.well-known/assetlinks.json
|
||||
async function assetlinks(req, res) {
|
||||
// #swagger.ignore = true (web-root verification file, not part of the API surface)
|
||||
const enabled = await settings.isMobileAppLinksEnabled() // fail-closed on any error
|
||||
const fps = fingerprints()
|
||||
|
||||
// Off, or on-but-unconfigured, both 404 — serving a statement with no fingerprint
|
||||
// asserts nothing and would only mislead the verifier.
|
||||
if (!enabled || fps.length === 0) {
|
||||
if (enabled && fps.length === 0 && !warnedNoFingerprint) {
|
||||
warnedNoFingerprint = true
|
||||
log.warn(
|
||||
'mobile_app_links_enabled is ON but MOBILE_APP_CERT_SHA256 is unset — assetlinks.json 404s',
|
||||
)
|
||||
}
|
||||
return res.status(404).json({ message: 'Not found' })
|
||||
}
|
||||
|
||||
// The OS/verifier re-fetch this; it changes only on a cert rotation.
|
||||
res.set('Cache-Control', 'public, max-age=3600')
|
||||
return res.json([
|
||||
{
|
||||
relation: ['delegate_permission/common.handle_all_urls'],
|
||||
target: {
|
||||
namespace: 'android_app',
|
||||
package_name: PACKAGE,
|
||||
sha256_cert_fingerprints: fps,
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
module.exports = { assetlinks }
|
||||
Reference in New Issue
Block a user