Documentation
¶
Overview ¶
Package auth handles credential storage, site login, and chat-JWT minting.
The stored credential is the value of the site's long-lived remember cookie — never the account password (ADR 0001, ADR 0003).
Index ¶
- Constants
- Variables
- func IsLoopback(host string) bool
- func RequireTLS(u *url.URL, secure string) error
- type FailError
- type LoginResult
- type Minter
- type Prompter
- type ServiceTokenMinter
- type Session
- type Site
- func (s *Site) CheckChatURL(raw string) error
- func (s *Site) CredentialKey() string
- func (s *Site) Login(ctx context.Context, identity, password string) (LoginResult, error)
- func (s *Site) Logout(ctx context.Context) error
- func (s *Site) Prime(ctx context.Context) error
- func (s *Site) Remember() (string, bool)
- func (s *Site) SeedCookies(header string) error
- func (s *Site) ServiceToken(ctx context.Context, service string) (string, error)
- func (s *Site) SetRemember(value string)
- func (s *Site) TwoFactor(ctx context.Context, code string) (User, error)
- type Store
- type User
Constants ¶
const (
// ChatService is the service name the chat JWT is minted for.
ChatService = "chat"
)
Routes under the site's /api/v1/auth group (docs/site-login-endpoints.md).
const IdentityHelp = "Use your email address if your account is set to " +
"log in with email only."
IdentityHelp is shown before the identity prompt. The site answers an email-only account's username with the same 422 as a wrong password, on purpose, so the CLI cannot detect that case and says so up front.
const PasswordHelp = "Press Enter with no password to change the username."
PasswordHelp is shown before the password prompt. An empty password is never sent: the site would only answer 422 and count it against the login limiter, so the entry doubles as the way back to the identity.
const RememberKey = "ng_remember"
RememberKey is the credential-store slot for the production site's remember cookie value. Other sites get their own slot (Site.CredentialKey) so a credential is only ever presented to the origin that issued it.
Variables ¶
ErrKeyringUnavailable marks an OS keyring that gave no answer: there is none (a headless box), or it is locked or denied. Load returns it when the file has no value and the keyring could not be read, so that absence is never inferred from a backend that did not answer; Delete returns it when the key could neither be removed nor read back. Save carries on with the file, since Load reads the file first.
var ErrNoChallenge = errors.New("no two-factor challenge in progress")
ErrNoChallenge reports a 403 from two-factor: the login challenge in this session expired or was consumed, so login must start over.
var ErrNotFound = errors.New("credential not found")
ErrNotFound is returned by Load when no value is stored under a key.
var ErrSignedOut = errors.New("signed out")
ErrSignedOut reports a 401 from service-token: the remember cookie no longer works (password changed, or `ngchat logout` ran). Nothing the client can do fixes it, so callers stop instead of retrying.
Functions ¶
func IsLoopback ¶
IsLoopback reports whether host names the local machine: "localhost" or a loopback IP literal.
Types ¶
type FailError ¶
FailError is a JSend "fail" (or non-JSend error) response. Fields follows Laravel's validation shape: field name to a list of messages.
func (*FailError) Error ¶
Error implements error with the user-facing message only; the status stays available for callers that branch on it.
type LoginResult ¶
LoginResult is the outcome of a successful password step. TwoFactor is "" when the login completed, or "email"/"totp" when a code is needed.
type Minter ¶
Minter obtains a fresh chat JWT. The token lives 1 hour and the chat server hard-closes the socket when it lapses, so minting recurs for the life of a session.
type Prompter ¶
type Prompter interface {
// Line reads a visible line, trimmed.
Line(prompt string) (string, error)
// Secret reads a line without echo.
Secret(prompt string) (string, error)
}
Prompter collects login input. The terminal implementation lives in cmd/ngchat so this flow can be driven by a script in tests.
type ServiceTokenMinter ¶
type ServiceTokenMinter struct {
Site *Site
}
ServiceTokenMinter re-mints through POST /api/v1/auth/service-token with the run's cookie jar (ADR 0003). Callers mint exactly once per connect and once per server revalidate: the site's service_token limiter (10/min per user) counts before auth and CSRF, so a retry loop would lock the user's browser out of chat too. A 401 surfaces as ErrSignedOut and must stop the client rather than reconnect.
type Session ¶
Session is what a completed login yields: who logged in, and the remember cookie value to persist.
func Login ¶
Login walks the password and two-factor steps until the jar holds a remember cookie. Wrong credentials re-prompt from the password step; three wrong codes or an expired challenge restart there too; an empty password goes back to the identity prompt. Lockout (429) and an undeliverable code (422) end the flow with the site's message, since only waiting or support can fix them.
type Site ¶
type Site struct {
// contains filtered or unexported fields
}
Site talks to the newgrounds.com JSON auth API through one in-memory cookie jar per run. Only the remember cookie survives the process; the session and CSRF cookies are re-established by priming (ADR 0003).
func NewSite ¶
NewSite builds a Site for baseURL (e.g. https://www.newgrounds.com). The scheme must be https unless the host is loopback: the remember cookie and, at login, the password ride on every request, and a plaintext origin would hand them to the network.
func (*Site) CheckChatURL ¶
CheckChatURL rejects a chat endpoint the site's token must not go to: the scheme must be wss (or the host loopback), and the chat host must belong to the same registrable domain as the site (chat.newgrounds.com for www.newgrounds.com), a loopback site pairing only with a loopback chat host and an IP-literal site only with the same literal. The chat JWT is minted from the site's cookie and sent as the first frame, so this runs before any mint.
func (*Site) CredentialKey ¶
CredentialKey names the credential-store slot for this site: the bare RememberKey for production, "ng_remember@<host>" for anything else. A remember cookie is a bearer for the origin that issued it, so a dev or staging login never overwrites the production one and, more to the point, the production one is never sent anywhere but production when NGCHAT_SITE_URL points elsewhere (ADR 0004).
func (*Site) Login ¶
Login runs the password step. A 403 means the jar was already authenticated, which a fresh jar cannot be, so it is reset and the login retried once.
func (*Site) Logout ¶
Logout revokes this device's remember token on the site (the token rows behind the jar's cookies are deleted, so a copy kept elsewhere stops minting) and ends the session. A 401 means the jar is already a guest, which is the state being asked for, so it is not an error.
func (*Site) Prime ¶
Prime establishes the session and CSRF cookies with a guest GET of auth/me. The 401 it answers is expected; only the cookies matter.
func (*Site) SeedCookies ¶
SeedCookies adds a raw Cookie header ("a=1; b=2") to the jar for the site host. Used for NGCHAT_NG_COOKIE and the dev proxy routing cookie.
func (*Site) ServiceToken ¶
ServiceToken mints a JWT for service. Callers own the rate: the site's limiter counts before auth and CSRF, so a retry loop here would also lock the user's browser out. A 401 is ErrSignedOut.
func (*Site) SetRemember ¶
SetRemember seeds the jar with a stored remember cookie so the first service-token call of a run authenticates. On an https site the cookie is marked Secure, so a redirect to a plaintext URL cannot carry it.
type Store ¶
type Store struct{}
Store persists secrets in the OS keyring (macOS Keychain, Windows Credential Manager, Linux Secret Service), falling back to a 0600 JSON file under the user config dir on headless boxes without a keyring.
func (Store) Delete ¶
Delete removes a secret from both backends. Both are attempted even when the first fails, and nil means both are confirmed clear: a logout that reports success while a copy survives is worse than one that says what it could not check. Missing entries are not an error; a keyring that answers nothing is ErrKeyringUnavailable.
func (Store) Load ¶
Load retrieves a secret, checking the fallback file then the keyring. The file comes first because a Save only lands there after the keyring refused the value, and a keyring that was locked at the time may still hold the previous account's entry once it opens; the file is the more recent write whenever it has the key. Returns ErrNotFound only when both backends answered that they have nothing; a keyring that did not answer is ErrKeyringUnavailable, because "not found" is what callers act on (a fresh login, a logout with nothing to revoke) and an unread keyring may still hold a live credential.
func (Store) Migrate ¶
Migrate removes the v0.1 cookie-header slot. It reports whether one was there so the caller can explain the login prompt that follows. An unreadable keyring is not fatal here, on either side: the slot is a dead value being tidied away, and a run must not die on a cleanup it cannot finish.
func (Store) Save ¶
Save stores a secret under key, preferring the keyring. Whichever backend takes the value, the other is cleared, so at most one holds it. When the keyring refuses the write, the stale entry it may hold is removed on a best-effort basis: a keyring that still serves it and refuses to drop it fails the Save (something is wrong with it), but one that answers nothing, absent or locked, is tolerated, because Load reads the file first and the file is what this Save writes, so an entry that resurfaces when the keyring unlocks cannot shadow it.