auth

package
v1.0.0-rc.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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).

View Source
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.

View Source
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.

View Source
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

View Source
var ErrKeyringUnavailable = errors.New("OS keyring unavailable")

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.

View Source
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.

View Source
var ErrNotFound = errors.New("credential not found")

ErrNotFound is returned by Load when no value is stored under a key.

View Source
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

func IsLoopback(host string) bool

IsLoopback reports whether host names the local machine: "localhost" or a loopback IP literal.

func RequireTLS

func RequireTLS(u *url.URL, secure string) error

RequireTLS rejects u unless its scheme is secure (the https of an http/https pair, the wss of a ws/wss pair) or its host is loopback, where plaintext is the local dev stack talking to itself.

Types

type FailError

type FailError struct {
	Status int
	Fields map[string][]string
}

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

func (e *FailError) Error() string

Error implements error with the user-facing message only; the status stays available for callers that branch on it.

func (*FailError) Has

func (e *FailError) Has(field string) bool

Has reports whether the response carried a message for field.

func (*FailError) Message

func (e *FailError) Message() string

Message returns the first message of the first known field, else the first message of any field, else the HTTP status text. The text is the site's and goes straight to the terminal, so it is sanitized here (render.Line) rather than at every print site.

type LoginResult

type LoginResult struct {
	TwoFactor       string
	ObfuscatedEmail string
	User            User
}

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

type Minter interface {
	Mint(ctx context.Context) (string, error)
}

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.

func (*ServiceTokenMinter) Mint

func (m *ServiceTokenMinter) Mint(ctx context.Context) (string, error)

Mint implements Minter.

type Session

type Session struct {
	User     User
	Remember string
}

Session is what a completed login yields: who logged in, and the remember cookie value to persist.

func Login

func Login(ctx context.Context, site *Site, p Prompter, out io.Writer) (Session, error)

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

func NewSite(baseURL string) (*Site, error)

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

func (s *Site) CheckChatURL(raw string) error

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

func (s *Site) CredentialKey() string

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

func (s *Site) Login(ctx context.Context, identity, password string) (LoginResult, error)

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

func (s *Site) Logout(ctx context.Context) error

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

func (s *Site) Prime(ctx context.Context) error

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) Remember

func (s *Site) Remember() (string, bool)

Remember returns the remember cookie currently in the jar, if any.

func (*Site) SeedCookies

func (s *Site) SeedCookies(header string) error

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

func (s *Site) ServiceToken(ctx context.Context, service string) (string, error)

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

func (s *Site) SetRemember(value string)

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.

func (*Site) TwoFactor

func (s *Site) TwoFactor(ctx context.Context, code string) (User, error)

TwoFactor completes the challenge started by Login. A six-character entry is sent as the emailed or TOTP code, anything else as a TOTP recovery code, so backup codes need no separate command.

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

func (Store) Delete(key string) error

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

func (Store) Load(key string) (string, error)

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

func (s Store) Migrate() (bool, error)

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

func (Store) Save(key, value string) error

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.

type User

type User struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
}

User identifies the account that logged in.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL