#!/bin/bash # Gitea SSO first-login via Cloudron OIDC — creates/binds the gitea account. # usage: gitea-sso-login.sh [vault-item] # Verifies a logged-in session at /user/settings and echoes the gitea username. set -uo pipefail U="${1:?usage: gitea-sso-login.sh [vault-item]}" ITEM="${2:-$U Cloudron}" BASE="https://git.knownelement.com" IDP="https://my.knownelement.com" ENTRY="$BASE/user/oauth2/cloudron" JAR="/tmp/gitea-jar-$U.txt"; rm -f "$JAR" SM() { if [ "$(id -un)" = "TSGCOO" ]; then /data2/TSGCOO/.local/bin/sm "$@" &2; exit 1; } SEED=$(SM get "$ITEM" --field totp_seed 2>/dev/null || true) INT=$(curl -sk -c "$JAR" -o /dev/null -w '%{url_effective}' -L --max-redirs 8 "$ENTRY") case "$INT" in */openid/interaction/*) : ;; *) echo "FAIL: no interaction reached: $INT" >&2; exit 3 ;; esac UIDPATH=$(printf '%s' "$INT" | grep -o '/openid/interaction/[^?]*') BODY="{\"username\":\"$U\",\"password\":\"$PW\"" if [ -n "$SEED" ]; then TCODE=$(bash "$(dirname "$0")/totp.sh" "$SEED") BODY="$BODY,\"totpToken\":\"$TCODE\"" fi BODY="$BODY}" LOGIN_RESP=$(curl -sk -b "$JAR" -c "$JAR" -X POST "$IDP$UIDPATH/login" -H 'Content-Type: application/json' -d "$BODY") unset BODY case "$LOGIN_RESP" in *redirectTo*) : ;; *) echo "FAIL: login rejected: $LOGIN_RESP" >&2; exit 5 ;; esac RED=$(printf '%s' "$LOGIN_RESP" | sed -n 's/.*"redirectTo":"\([^"]*\)".*/\1/p') FINAL=$(curl -sk -b "$JAR" -c "$JAR" -o /dev/null -w '%{url_effective}' -L --max-redirs 8 "$RED") # consent interaction may appear for app clients case "$FINAL" in */openid/interaction/*) CUIDPATH=$(printf '%s' "$FINAL" | grep -o '/openid/interaction/[^?]*') CLOC=$(curl -sk -b "$JAR" -c "$JAR" -D - -o /dev/null -X POST "$IDP$CUIDPATH/confirm" -d '' | grep -i '^location:' | head -1 | tr -d '\r' | sed 's/^[Ll]ocation: //') [ -n "$CLOC" ] || { echo "FAIL: consent confirm produced no redirect" >&2; exit 6; } CLOC=$(printf '%s' "$CLOC" | sed 's|^https://|https://|; s|^https//|https://|; s|^http//|http://|') case "$CLOC" in http://*|https://*) : ;; /*) CLOC="$IDP$CLOC" ;; *) CLOC="$IDP/$CLOC" ;; esac FINAL=$(curl -sk -b "$JAR" -c "$JAR" -o /dev/null -w '%{url_effective}' -L --max-redirs 8 "$CLOC") ;; esac CODE=$(curl -sk -b "$JAR" -o /dev/null -w '%{http_code}' "$BASE/user/settings") if [ "$CODE" = "200" ]; then echo "OK: $U logged into gitea (session verified)" exit 0 fi echo "FAIL: no gitea session (settings HTTP $CODE), landed: $FINAL" >&2 exit 7