A vibe coded tangled fork which supports pijul.
at a2b976317789c0dc88bcdca4b0b8337d6307dae4 359 lines 9.2 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 234type User struct { 235 Did string 236} 237 238func (o *OAuth) GetUser(r *http.Request) *User { 239 sess, err := o.ResumeSession(r) 240 if err != nil { 241 return nil 242 } 243 244 return &User{ 245 Did: sess.Data.AccountDID.String(), 246 } 247} 248 249func (o *OAuth) GetDid(r *http.Request) string { 250 if u := o.GetMultiAccountUser(r); u != nil { 251 return u.Did() 252 } 253 254 return "" 255} 256 257func (o *OAuth) AuthorizedClient(r *http.Request) (*atpclient.APIClient, error) { 258 session, err := o.ResumeSession(r) 259 if err != nil { 260 return nil, fmt.Errorf("error getting session: %w", err) 261 } 262 return session.APIClient(), nil 263} 264 265// this is a higher level abstraction on ServerGetServiceAuth 266type ServiceClientOpts struct { 267 service string 268 exp int64 269 lxm string 270 dev bool 271 timeout time.Duration 272} 273 274type ServiceClientOpt func(*ServiceClientOpts) 275 276func DefaultServiceClientOpts() ServiceClientOpts { 277 return ServiceClientOpts{ 278 timeout: time.Second * 5, 279 } 280} 281 282func WithService(service string) ServiceClientOpt { 283 return func(s *ServiceClientOpts) { 284 s.service = service 285 } 286} 287 288// Specify the Duration in seconds for the expiry of this token 289// 290// The time of expiry is calculated as time.Now().Unix() + exp 291func WithExp(exp int64) ServiceClientOpt { 292 return func(s *ServiceClientOpts) { 293 s.exp = time.Now().Unix() + exp 294 } 295} 296 297func WithLxm(lxm string) ServiceClientOpt { 298 return func(s *ServiceClientOpts) { 299 s.lxm = lxm 300 } 301} 302 303func WithDev(dev bool) ServiceClientOpt { 304 return func(s *ServiceClientOpts) { 305 s.dev = dev 306 } 307} 308 309func WithTimeout(timeout time.Duration) ServiceClientOpt { 310 return func(s *ServiceClientOpts) { 311 s.timeout = timeout 312 } 313} 314 315func (s *ServiceClientOpts) Audience() string { 316 return fmt.Sprintf("did:web:%s", s.service) 317} 318 319func (s *ServiceClientOpts) Host() string { 320 scheme := "https://" 321 if s.dev { 322 scheme = "http://" 323 } 324 325 return scheme + s.service 326} 327 328func (o *OAuth) ServiceClient(r *http.Request, os ...ServiceClientOpt) (*xrpc.Client, error) { 329 opts := DefaultServiceClientOpts() 330 for _, o := range os { 331 o(&opts) 332 } 333 334 client, err := o.AuthorizedClient(r) 335 if err != nil { 336 return nil, err 337 } 338 339 // force expiry to atleast 60 seconds in the future 340 sixty := time.Now().Unix() + 60 341 if opts.exp < sixty { 342 opts.exp = sixty 343 } 344 345 resp, err := comatproto.ServerGetServiceAuth(r.Context(), client, opts.Audience(), opts.exp, opts.lxm) 346 if err != nil { 347 return nil, err 348 } 349 350 return &xrpc.Client{ 351 Auth: &xrpc.AuthInfo{ 352 AccessJwt: resp.Token, 353 }, 354 Host: opts.Host(), 355 Client: &http.Client{ 356 Timeout: opts.timeout, 357 }, 358 }, nil 359}