A vibe coded tangled fork which supports pijul.
at b6fe3ea895df24cf85f7239cb245212899d5d09f 344 lines 8.9 kB view raw
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, TangledScopes) 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, TangledScopes) 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 // allow non-public transports in dev mode 78 if config.Core.Dev { 79 clientApp.Resolver.Client.Transport = http.DefaultTransport 80 } 81 82 clientName := config.Core.AppviewName 83 84 logger.Info("oauth setup successfully", "IsConfidential", clientApp.Config.IsConfidential()) 85 return &OAuth{ 86 ClientApp: clientApp, 87 Config: config, 88 SessStore: sessStore, 89 JwksUri: jwksUri, 90 ClientName: clientName, 91 ClientUri: clientUri, 92 Posthog: ph, 93 Db: db, 94 Enforcer: enforcer, 95 IdResolver: res, 96 Logger: logger, 97 }, nil 98} 99 100func (o *OAuth) SaveSession(w http.ResponseWriter, r *http.Request, sessData *oauth.ClientSessionData) error { 101 userSession, err := o.SessStore.Get(r, SessionName) 102 if err != nil { 103 return err 104 } 105 106 userSession.Values[SessionDid] = sessData.AccountDID.String() 107 userSession.Values[SessionPds] = sessData.HostURL 108 userSession.Values[SessionId] = sessData.SessionID 109 userSession.Values[SessionAuthenticated] = true 110 111 if err := userSession.Save(r, w); err != nil { 112 return err 113 } 114 115 handle := "" 116 resolved, err := o.IdResolver.ResolveIdent(r.Context(), sessData.AccountDID.String()) 117 if err == nil && resolved.Handle.String() != "" { 118 handle = resolved.Handle.String() 119 } 120 121 registry := o.GetAccounts(r) 122 if err := registry.AddAccount(sessData.AccountDID.String(), handle, sessData.SessionID); err != nil { 123 return err 124 } 125 return o.saveAccounts(w, r, registry) 126} 127 128func (o *OAuth) ResumeSession(r *http.Request) (*oauth.ClientSession, error) { 129 userSession, err := o.SessStore.Get(r, SessionName) 130 if err != nil { 131 return nil, fmt.Errorf("error getting user session: %w", err) 132 } 133 if userSession.IsNew { 134 return nil, fmt.Errorf("no session available for user") 135 } 136 137 d := userSession.Values[SessionDid].(string) 138 sessDid, err := syntax.ParseDID(d) 139 if err != nil { 140 return nil, fmt.Errorf("malformed DID in session cookie '%s': %w", d, err) 141 } 142 143 sessId := userSession.Values[SessionId].(string) 144 145 clientSess, err := o.ClientApp.ResumeSession(r.Context(), sessDid, sessId) 146 if err != nil { 147 return nil, fmt.Errorf("failed to resume session: %w", err) 148 } 149 150 return clientSess, nil 151} 152 153func (o *OAuth) DeleteSession(w http.ResponseWriter, r *http.Request) error { 154 userSession, err := o.SessStore.Get(r, SessionName) 155 if err != nil { 156 return fmt.Errorf("error getting user session: %w", err) 157 } 158 if userSession.IsNew { 159 return fmt.Errorf("no session available for user") 160 } 161 162 d := userSession.Values[SessionDid].(string) 163 sessDid, err := syntax.ParseDID(d) 164 if err != nil { 165 return fmt.Errorf("malformed DID in session cookie '%s': %w", d, err) 166 } 167 168 sessId := userSession.Values[SessionId].(string) 169 170 // delete the session 171 err1 := o.ClientApp.Logout(r.Context(), sessDid, sessId) 172 if err1 != nil { 173 err1 = fmt.Errorf("failed to logout: %w", err1) 174 } 175 176 // remove the cookie 177 userSession.Options.MaxAge = -1 178 err2 := o.SessStore.Save(r, w, userSession) 179 if err2 != nil { 180 err2 = fmt.Errorf("failed to save into session store: %w", err2) 181 } 182 183 return errors.Join(err1, err2) 184} 185 186func (o *OAuth) SwitchAccount(w http.ResponseWriter, r *http.Request, targetDid string) error { 187 registry := o.GetAccounts(r) 188 account := registry.FindAccount(targetDid) 189 if account == nil { 190 return fmt.Errorf("account not found in registry: %s", targetDid) 191 } 192 193 did, err := syntax.ParseDID(targetDid) 194 if err != nil { 195 return fmt.Errorf("invalid DID: %w", err) 196 } 197 198 sess, err := o.ClientApp.ResumeSession(r.Context(), did, account.SessionId) 199 if err != nil { 200 registry.RemoveAccount(targetDid) 201 _ = o.saveAccounts(w, r, registry) 202 return fmt.Errorf("session expired for account: %w", err) 203 } 204 205 userSession, err := o.SessStore.Get(r, SessionName) 206 if err != nil { 207 return err 208 } 209 210 userSession.Values[SessionDid] = sess.Data.AccountDID.String() 211 userSession.Values[SessionPds] = sess.Data.HostURL 212 userSession.Values[SessionId] = sess.Data.SessionID 213 userSession.Values[SessionAuthenticated] = true 214 215 return userSession.Save(r, w) 216} 217 218func (o *OAuth) RemoveAccount(w http.ResponseWriter, r *http.Request, targetDid string) error { 219 registry := o.GetAccounts(r) 220 account := registry.FindAccount(targetDid) 221 if account == nil { 222 return nil 223 } 224 225 did, err := syntax.ParseDID(targetDid) 226 if err == nil { 227 _ = o.ClientApp.Logout(r.Context(), did, account.SessionId) 228 } 229 230 registry.RemoveAccount(targetDid) 231 return o.saveAccounts(w, r, registry) 232} 233 234func (o *OAuth) GetDid(r *http.Request) string { 235 if u := o.GetMultiAccountUser(r); u != nil { 236 return u.Did 237 } 238 239 return "" 240} 241 242func (o *OAuth) AuthorizedClient(r *http.Request) (*atpclient.APIClient, error) { 243 session, err := o.ResumeSession(r) 244 if err != nil { 245 return nil, fmt.Errorf("error getting session: %w", err) 246 } 247 return session.APIClient(), nil 248} 249 250// this is a higher level abstraction on ServerGetServiceAuth 251type ServiceClientOpts struct { 252 service string 253 exp int64 254 lxm string 255 dev bool 256 timeout time.Duration 257} 258 259type ServiceClientOpt func(*ServiceClientOpts) 260 261func DefaultServiceClientOpts() ServiceClientOpts { 262 return ServiceClientOpts{ 263 timeout: time.Second * 5, 264 } 265} 266 267func WithService(service string) ServiceClientOpt { 268 return func(s *ServiceClientOpts) { 269 s.service = service 270 } 271} 272 273// Specify the Duration in seconds for the expiry of this token 274// 275// The time of expiry is calculated as time.Now().Unix() + exp 276func WithExp(exp int64) ServiceClientOpt { 277 return func(s *ServiceClientOpts) { 278 s.exp = time.Now().Unix() + exp 279 } 280} 281 282func WithLxm(lxm string) ServiceClientOpt { 283 return func(s *ServiceClientOpts) { 284 s.lxm = lxm 285 } 286} 287 288func WithDev(dev bool) ServiceClientOpt { 289 return func(s *ServiceClientOpts) { 290 s.dev = dev 291 } 292} 293 294func WithTimeout(timeout time.Duration) ServiceClientOpt { 295 return func(s *ServiceClientOpts) { 296 s.timeout = timeout 297 } 298} 299 300func (s *ServiceClientOpts) Audience() string { 301 return fmt.Sprintf("did:web:%s", s.service) 302} 303 304func (s *ServiceClientOpts) Host() string { 305 scheme := "https://" 306 if s.dev { 307 scheme = "http://" 308 } 309 310 return scheme + s.service 311} 312 313func (o *OAuth) ServiceClient(r *http.Request, os ...ServiceClientOpt) (*xrpc.Client, error) { 314 opts := DefaultServiceClientOpts() 315 for _, o := range os { 316 o(&opts) 317 } 318 319 client, err := o.AuthorizedClient(r) 320 if err != nil { 321 return nil, err 322 } 323 324 // force expiry to atleast 60 seconds in the future 325 sixty := time.Now().Unix() + 60 326 if opts.exp < sixty { 327 opts.exp = sixty 328 } 329 330 resp, err := comatproto.ServerGetServiceAuth(r.Context(), client, opts.Audience(), opts.exp, opts.lxm) 331 if err != nil { 332 return nil, err 333 } 334 335 return &xrpc.Client{ 336 Auth: &xrpc.AuthInfo{ 337 AccessJwt: resp.Token, 338 }, 339 Host: opts.Host(), 340 Client: &http.Client{ 341 Timeout: opts.timeout, 342 }, 343 }, nil 344}