forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
1package oauth 2 3import ( 4 "errors" 5 "fmt" 6 "log/slog" 7 "net/http" 8 "time" 9 10 comatproto "github.com/bluesky-social/indigo/api/atproto" 11 "github.com/bluesky-social/indigo/atproto/auth/oauth" 12 atpclient "github.com/bluesky-social/indigo/atproto/client" 13 atcrypto "github.com/bluesky-social/indigo/atproto/crypto" 14 "github.com/bluesky-social/indigo/atproto/syntax" 15 xrpc "github.com/bluesky-social/indigo/xrpc" 16 "github.com/gorilla/sessions" 17 "github.com/posthog/posthog-go" 18 "tangled.org/core/appview/config" 19 "tangled.org/core/appview/db" 20 "tangled.org/core/idresolver" 21 "tangled.org/core/rbac" 22) 23 24type OAuth struct { 25 ClientApp *oauth.ClientApp 26 SessStore *sessions.CookieStore 27 Config *config.Config 28 JwksUri string 29 ClientName string 30 ClientUri string 31 Posthog posthog.Client 32 Db *db.DB 33 Enforcer *rbac.Enforcer 34 IdResolver *idresolver.Resolver 35 Logger *slog.Logger 36} 37 38func New(config *config.Config, ph posthog.Client, db *db.DB, enforcer *rbac.Enforcer, res *idresolver.Resolver, logger *slog.Logger) (*OAuth, error) { 39 var oauthConfig oauth.ClientConfig 40 var clientUri string 41 if config.Core.Dev { 42 clientUri = "http://127.0.0.1:3000" 43 callbackUri := clientUri + "/oauth/callback" 44 oauthConfig = oauth.NewLocalhostConfig(callbackUri, []string{"atproto", "transition:generic"}) 45 } else { 46 clientUri = config.Core.AppviewHost 47 clientId := fmt.Sprintf("%s/oauth/client-metadata.json", clientUri) 48 callbackUri := clientUri + "/oauth/callback" 49 oauthConfig = oauth.NewPublicConfig(clientId, callbackUri, []string{"atproto", "transition:generic"}) 50 } 51 52 // configure client secret 53 priv, err := atcrypto.ParsePrivateMultibase(config.OAuth.ClientSecret) 54 if err != nil { 55 return nil, err 56 } 57 if err := oauthConfig.SetClientSecret(priv, config.OAuth.ClientKid); err != nil { 58 return nil, err 59 } 60 61 jwksUri := clientUri + "/oauth/jwks.json" 62 63 authStore, err := NewRedisStore(&RedisStoreConfig{ 64 RedisURL: config.Redis.ToURL(), 65 SessionExpiryDuration: time.Hour * 24 * 90, 66 SessionInactivityDuration: time.Hour * 24 * 14, 67 AuthRequestExpiryDuration: time.Minute * 30, 68 }) 69 if err != nil { 70 return nil, err 71 } 72 73 sessStore := sessions.NewCookieStore([]byte(config.Core.CookieSecret)) 74 75 clientApp := oauth.NewClientApp(&oauthConfig, authStore) 76 clientApp.Dir = res.Directory() 77 78 clientName := config.Core.AppviewName 79 80 return &OAuth{ 81 ClientApp: clientApp, 82 Config: config, 83 SessStore: sessStore, 84 JwksUri: jwksUri, 85 ClientName: clientName, 86 ClientUri: clientUri, 87 Posthog: ph, 88 Db: db, 89 Enforcer: enforcer, 90 IdResolver: res, 91 Logger: logger, 92 }, nil 93} 94 95func (o *OAuth) SaveSession(w http.ResponseWriter, r *http.Request, sessData *oauth.ClientSessionData) error { 96 // first we save the did in the user session 97 userSession, err := o.SessStore.Get(r, SessionName) 98 if err != nil { 99 return err 100 } 101 102 userSession.Values[SessionDid] = sessData.AccountDID.String() 103 userSession.Values[SessionPds] = sessData.HostURL 104 userSession.Values[SessionId] = sessData.SessionID 105 userSession.Values[SessionAuthenticated] = true 106 return userSession.Save(r, w) 107} 108 109func (o *OAuth) ResumeSession(r *http.Request) (*oauth.ClientSession, error) { 110 userSession, err := o.SessStore.Get(r, SessionName) 111 if err != nil { 112 return nil, fmt.Errorf("error getting user session: %w", err) 113 } 114 if userSession.IsNew { 115 return nil, fmt.Errorf("no session available for user") 116 } 117 118 d := userSession.Values[SessionDid].(string) 119 sessDid, err := syntax.ParseDID(d) 120 if err != nil { 121 return nil, fmt.Errorf("malformed DID in session cookie '%s': %w", d, err) 122 } 123 124 sessId := userSession.Values[SessionId].(string) 125 126 clientSess, err := o.ClientApp.ResumeSession(r.Context(), sessDid, sessId) 127 if err != nil { 128 return nil, fmt.Errorf("failed to resume session: %w", err) 129 } 130 131 return clientSess, nil 132} 133 134func (o *OAuth) DeleteSession(w http.ResponseWriter, r *http.Request) error { 135 userSession, err := o.SessStore.Get(r, SessionName) 136 if err != nil { 137 return fmt.Errorf("error getting user session: %w", err) 138 } 139 if userSession.IsNew { 140 return fmt.Errorf("no session available for user") 141 } 142 143 d := userSession.Values[SessionDid].(string) 144 sessDid, err := syntax.ParseDID(d) 145 if err != nil { 146 return fmt.Errorf("malformed DID in session cookie '%s': %w", d, err) 147 } 148 149 sessId := userSession.Values[SessionId].(string) 150 151 // delete the session 152 err1 := o.ClientApp.Logout(r.Context(), sessDid, sessId) 153 154 // remove the cookie 155 userSession.Options.MaxAge = -1 156 err2 := o.SessStore.Save(r, w, userSession) 157 158 return errors.Join(err1, err2) 159} 160 161type User struct { 162 Did string 163 Pds string 164} 165 166func (o *OAuth) GetUser(r *http.Request) *User { 167 sess, err := o.ResumeSession(r) 168 if err != nil { 169 return nil 170 } 171 172 return &User{ 173 Did: sess.Data.AccountDID.String(), 174 Pds: sess.Data.HostURL, 175 } 176} 177 178func (o *OAuth) GetDid(r *http.Request) string { 179 if u := o.GetUser(r); u != nil { 180 return u.Did 181 } 182 183 return "" 184} 185 186func (o *OAuth) AuthorizedClient(r *http.Request) (*atpclient.APIClient, error) { 187 session, err := o.ResumeSession(r) 188 if err != nil { 189 return nil, fmt.Errorf("error getting session: %w", err) 190 } 191 return session.APIClient(), nil 192} 193 194// this is a higher level abstraction on ServerGetServiceAuth 195type ServiceClientOpts struct { 196 service string 197 exp int64 198 lxm string 199 dev bool 200} 201 202type ServiceClientOpt func(*ServiceClientOpts) 203 204func WithService(service string) ServiceClientOpt { 205 return func(s *ServiceClientOpts) { 206 s.service = service 207 } 208} 209 210// Specify the Duration in seconds for the expiry of this token 211// 212// The time of expiry is calculated as time.Now().Unix() + exp 213func WithExp(exp int64) ServiceClientOpt { 214 return func(s *ServiceClientOpts) { 215 s.exp = time.Now().Unix() + exp 216 } 217} 218 219func WithLxm(lxm string) ServiceClientOpt { 220 return func(s *ServiceClientOpts) { 221 s.lxm = lxm 222 } 223} 224 225func WithDev(dev bool) ServiceClientOpt { 226 return func(s *ServiceClientOpts) { 227 s.dev = dev 228 } 229} 230 231func (s *ServiceClientOpts) Audience() string { 232 return fmt.Sprintf("did:web:%s", s.service) 233} 234 235func (s *ServiceClientOpts) Host() string { 236 scheme := "https://" 237 if s.dev { 238 scheme = "http://" 239 } 240 241 return scheme + s.service 242} 243 244func (o *OAuth) ServiceClient(r *http.Request, os ...ServiceClientOpt) (*xrpc.Client, error) { 245 opts := ServiceClientOpts{} 246 for _, o := range os { 247 o(&opts) 248 } 249 250 client, err := o.AuthorizedClient(r) 251 if err != nil { 252 return nil, err 253 } 254 255 // force expiry to atleast 60 seconds in the future 256 sixty := time.Now().Unix() + 60 257 if opts.exp < sixty { 258 opts.exp = sixty 259 } 260 261 resp, err := comatproto.ServerGetServiceAuth(r.Context(), client, opts.Audience(), opts.exp, opts.lxm) 262 if err != nil { 263 return nil, err 264 } 265 266 return &xrpc.Client{ 267 Auth: &xrpc.AuthInfo{ 268 AccessJwt: resp.Token, 269 }, 270 Host: opts.Host(), 271 Client: &http.Client{ 272 Timeout: time.Second * 5, 273 }, 274 }, nil 275}