Files
iam/internal/wallet/wallet.go
zeekay 5c9b1d6397 wallet: cap the accounts sign-up creates per address and network
A wallet is a free key, so headless web3 sign-up minted one free account
per key without limit. Cap counts account creations, never sign-ins,
per client address and per IPv4 /24 or IPv6 /64 in a window: default
10 and 50 per 24h, set by IAM_WALLET_CAP_IP, IAM_WALLET_CAP_SUBNET and
IAM_WALLET_CAP_WINDOW (0 = off).

The count is the wallet-signup audit ledger, read and written in the
account's own transaction, so a refusal writes no row and concurrent
creations cannot share a count. Past a bound: 429, Retry-After, code
wallet_signup_capped and the bound in data.

The client address is httpx.Client, the identifier throttle's rule
moved so both read one: CF-Connecting-IP, else the last
X-Forwarded-For hop.
2026-10-26 16:17:31 -07:00

420 lines
16 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
// Package wallet is native multi-chain wallet sign-in for IAM (HIP-0111):
// keyless CAIP-122 challenge/response over github.com/luxwallet/connect/go —
// the SAME VerifyProof the TypeScript SDK runs, so Go and TS verify identically.
//
// GET /v1/iam/web3/nonce -> mint a single-use CAIP-122 challenge
// POST /v1/iam/web3/verify -> verify a signed proof; THIS is the login
//
// Both are anonymous-reachable by construction: they precede any token, so
// they are registered on the public route group (before the Guard). Neither reads tenant data nor
// takes a state-changing action on a caller's behalf — the nonce writes only its
// own challenge row, and verify acts solely on a cryptographically-verified
// address.
//
// HTTP shell only. The auth logic (burn, verify, resolve) lives in verify.go so
// it stays unit-testable and decomplected from the transport.
package wallet
import (
"crypto/rand"
"encoding/hex"
"errors"
"log"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/hanzoai/orm"
"github.com/zap-proto/zip"
wc "github.com/luxwallet/connect/go/walletconnect"
"github.com/hanzoai/iam/internal/authz"
"github.com/hanzoai/iam/internal/did"
"github.com/hanzoai/iam/internal/httpx"
"github.com/hanzoai/iam/internal/oidc"
"github.com/hanzoai/iam/internal/sessions"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// The canonical wallet sign-in endpoints.
const (
PathNonce = "/v1/iam/web3/nonce"
PathVerify = "/v1/iam/web3/verify"
)
//go:generate go run github.com/zap-proto/zip/cmd/zipdoc
// Route registers the wallet sign-in surface on the PUBLIC route group (before
// the authz Guard): a wallet holder has no token until this flow gives them one,
// so membership in the public group is what makes the two endpoints reachable
// without a bearer.
//
// The Cap on the accounts sign-up creates is read here, once, from the
// deployment's IAM_WALLET_CAP_* variables.
func Route(r *zip.Group, db orm.DB) {
limit, err := capFrom(os.Getenv)
if err != nil {
log.Print(err)
}
r.Raw(http.MethodGet, PathNonce, nonce(db))
r.Raw(http.MethodPost, PathVerify, check(db, limit))
}
// challenge is the LoginChallenge the client feeds to connector.signLogin().
// The field names mirror walletconnect.LoginChallenge so the JS passes it
// through unchanged, and the set is exact: renaming or dropping one desyncs the
// message the wallet SIGNS from the one the server PARSES, which reads as a
// universal bad-signature.
type challenge struct {
Domain string `json:"domain"`
URI string `json:"uri"`
Statement string `json:"statement,omitempty"`
Nonce string `json:"nonce"`
IssuedAt string `json:"issuedAt"`
ExpirationTime string `json:"expirationTime,omitempty"`
Version string `json:"version"`
}
// nonce starts a wallet sign-in: it returns a one-time challenge for the wallet
// to sign. The challenge is good once and is tied to the site that asked for it,
// so a signature collected elsewhere cannot be replayed here. Pass your
// application's clientId and, from a page at one of its registered redirect
// origins, the challenge names that page's site, which is what the wallet shows
// the person.
func nonce(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
chain := wc.Chain(trim(c.Query("chain")))
if !supported(chain) {
return httpx.Err(c, "web3: unsupported chain: "+string(chain))
}
address := c.Query("address")
if len(address) > maxAddress {
return httpx.Err(c, "web3: oversized address")
}
ctx := c.Context()
app, err := store.GetApplicationByClientId(ctx, db, trim(c.Query("clientId")))
if err != nil {
return httpx.Err(c, err.Error())
}
domain, uri := site(c, app)
if domain == "" {
return httpx.Err(c, "web3: empty domain")
}
n, err := random()
if err != nil {
return httpx.Err(c, err.Error())
}
now := time.Now().UTC()
expire := now.Add(ttl)
if err := mint(ctx, db, &schema.Challenge{
Owner: owner,
Name: n,
Chain: string(chain),
Address: trim(address),
Domain: domain,
CreatedTime: stamp(now),
ExpireTime: stamp(expire),
}); err != nil {
return httpx.Err(c, err.Error())
}
return httpx.Ok(c, challenge{
Domain: domain,
URI: uri,
Statement: statement,
Nonce: n,
IssuedAt: stamp(now),
ExpirationTime: stamp(expire),
Version: "1",
})
}
}
// proof is the POST body: a walletconnect SignedProof plus the routing the shell
// resolves and the authorize params the mint passes through.
type proof struct {
Organization string `json:"organization"`
Application string `json:"application"`
Method string `json:"method"` // "signup" (default) | "login"
Chain string `json:"chain"`
Scheme string `json:"scheme"`
Address string `json:"address"`
PublicKey string `json:"publicKey,omitempty"`
Message string `json:"message"`
Signature string `json:"signature"`
Extra map[string]any `json:"extra,omitempty"`
// Authorize passthrough. Type defaults to "login" (the shape the login page
// expects); Type="code" + the rest drives the PKCE authorize flow.
Type string `json:"type"`
ClientId string `json:"clientId"`
RedirectUri string `json:"redirectUri"`
State string `json:"state"`
Scope string `json:"scope"`
Nonce string `json:"nonce"`
CodeChallenge string `json:"codeChallenge"`
CodeChallengeMethod string `json:"codeChallengeMethod"`
}
// Field bounds, enforced before any per-chain parser reaches the input. A real
// proof's message/signature/key are a few hundred bytes; a multi-MB field is the
// parser-bomb vector (a deeply-nested Cardano COSE blob can fatally overflow the
// Go stack — uncatchable by recover, taking the IdP down). The SDK carries its
// own looser caps; these are defense in depth, rejecting early and cheaply.
const (
maxField = 8 * 1024 // message / signature
maxKey = 1024 // publicKey
maxAddress = 256
)
// check completes a wallet sign-in: it verifies the signed challenge and, if it
// holds, signs the wallet's owner in.
//
// This IS the login — it answers exactly as a password sign-in does, so the rest
// of your flow does not branch on how somebody arrived.
//
// A wallet no account holds yet creates one, and one address or one network
// creates only so many in a window, a day by default. Past that the answer is
// 429 with Retry-After and code wallet_signup_capped; data names the bound ("ip"
// or "subnet"), its limit, and its window in seconds. A wallet already on file
// is never counted.
func check(db orm.DB, limit Cap) zip.Handler {
return func(c *zip.Ctx) error {
var f proof
if err := c.Bind(&f); err != nil {
return httpx.Err(c, "invalid request body")
}
if len(f.Signature) > maxField || len(f.Message) > maxField ||
len(f.PublicKey) > maxKey || len(f.Address) > maxAddress {
return httpx.Err(c, "web3: oversized proof field")
}
chain := wc.Chain(trim(f.Chain))
if !supported(chain) {
return httpx.Err(c, "web3: unsupported chain: "+string(chain))
}
ctx := c.Context()
app, err := oidc.ResolveApp(ctx, db, f.ClientId, f.Application)
if err != nil {
return httpx.Err(c, err.Error())
}
if app == nil {
return httpx.Err(c, "application not found")
}
org, err := store.GetOrganizationByName(ctx, db, app.Organization)
if err != nil {
return httpx.Err(c, err.Error())
}
if org == nil {
return httpx.Err(c, "web3: organization not found")
}
// The same site() as the mint, re-derived here and re-checked against the
// burned challenge, so a challenge redeems only where it could be minted.
domain, _ := site(c, app)
in, err := verify(ctx, db, login{
Domain: domain,
Host: trim(c.Host()),
Proof: wc.Proof{
Chain: chain,
Scheme: wc.SignatureScheme(f.Scheme),
Address: f.Address,
PublicKey: f.PublicKey,
Message: f.Message,
Signature: f.Signature,
Extra: f.Extra,
},
Method: f.Method,
App: app,
Org: org,
Session: session(c, db),
Client: httpx.Client(c.Header("CF-Connecting-IP"), c.Header("X-Forwarded-For")),
Cap: limit,
}, time.Now().UTC())
var refused *capped
if errors.As(err, &refused) {
return refuse(c, refused)
}
if err != nil {
return httpx.Err(c, err.Error())
}
user := in.user
// The multi-factor gate belongs HERE — after the wallet proves the
// identity, before any session or code is minted. It is oidc's ONE gate,
// called rather than copied: a wallet is attachable to any existing
// identity, so a second factor a password login demands must not be
// skippable by signing in with the wallet on the same account. A signature
// proves none of the offerable factors, so the gate is told "" and may ask
// for any of them; it answers the request itself (NextMfa) and the person
// finishes at /v1/iam/login with the challenge it set, exactly as the
// password path does.
gated, err := oidc.Gate(c, db, user, org, "")
if err != nil {
return httpx.Err(c, err.Error())
}
if gated {
return nil
}
data, err := oidc.MintFor(ctx, db, app, user.Owner+"/"+user.Name, oidc.Mint{
Type: f.Type,
RedirectUri: f.RedirectUri,
State: f.State,
Scope: f.Scope,
Nonce: f.Nonce,
CodeChallenge: f.CodeChallenge,
CodeChallengeMethod: f.CodeChallengeMethod,
})
if err != nil {
return httpx.Err(c, err.Error())
}
// The wallet holder is now signed in to the IDENTITY PROVIDER, so the IdP
// remembers them — the same tail every interactive sign-in has. Without
// it a bare wallet sign-in returned a user id and no session, and the portal
// sent the person to a page whose bootstrap found nobody signed in and
// bounced them back to the credential form.
_ = sessions.Open(ctx, c.Fiber(), db, user.Owner, user.Name, app.Name)
// A NEW binding — and only a new one — is anchored. Signing in with a
// wallet already on file changes nothing, so re-anchoring would add a
// duplicate verification method to the document on every login. The
// write runs in the background on its own context: the person is signed
// in, and a chain that is slow or unreachable must not hold this
// response open or fail it. A no-op unless a registry is configured.
if in.bound != nil {
if iss, err := oidc.Issuer(trim(c.Host())); err == nil {
registry().Report(oidc.Subject(user), iss, in.bound.Chain, in.bound.Address)
}
}
return httpx.Ok(c, data)
}
}
// registry is the DID registry this deployment configured, resolved once. A
// deployment that named none gets a nil *did.Registry, whose methods are no-ops
// — which is why the link path above needs no branch on whether anchoring is
// switched on.
//
// A misconfiguration (a half-named registry, unreadable key material, an
// address that is not one) also yields nil, having said so once rather than on
// every link. It does not stop the service: IAM's job is issuing tokens, and it
// still does that correctly with the DID claim derived and nothing written.
var registry = sync.OnceValue(func() *did.Registry {
r, err := did.FromEnv()
if err != nil {
log.Printf("did: registry disabled: %v", err)
return nil
}
return r
})
// session resolves the authenticated caller, but ONLY on a same-site request.
//
// This is the sole branch of the flow carrying ambient authority (the caller's
// bearer), and the only one that attaches a verified wallet to an EXISTING
// identity. A cross-site forged POST must not be able to attach an attacker's
// wallet to a victim's account, so a cross-site caller is treated as anonymous
// and falls through to the login/signup branches, which have no ambient
// authority to abuse.
func session(c *zip.Ctx, db orm.DB) *schema.User {
if !same(c) {
return nil
}
p := authz.Optional(c, db)
if p == nil || p.User == "" {
return nil // anonymous, unverifiable, or a machine token with no identity
}
user, err := store.GetUserByName(c.Context(), db, p.Org, p.User)
if err != nil {
return nil
}
return user
}
// site is the domain and URI a wallet challenge names for this request, and the
// one rule both legs read: the nonce mints with it and verify expects it.
//
// It is the origin of the page that asked when that origin is one of app's own
// (oidc.Landing: the scheme, host and port of a registered redirect URI, matched
// exactly), so a person signing in on hanzo.ai through IAM at api.hanzo.ai signs
// for hanzo.ai, and a wallet that compares the EIP-4361 domain with the page
// finds them equal. With no application, or an Origin it does not register, it
// is the host the request arrived on, read through the header-immune c.Host()
// (zip has no trusted-proxy knob, so X-Forwarded-Host is ignored). Referer is
// never read.
//
// Origin decides it only among app's registered origins. A browser sets Origin
// and page script cannot change it. A client outside a browser can send any
// Origin, but the only values that move the answer are origins the application
// already registers, so a forger obtains a challenge naming a site the
// application owns: what every browser on that site obtains, and nothing a
// direct call to that host's IAM would not give. What keeps a captured signature
// from signing anyone in is unchanged: the single-use burn, the burned row's
// domain re-checked at verify, and the wallet's own comparison of the domain with
// the page asking. The same-site check that gates linking a wallet to a
// signed-in caller (same) still compares Origin with c.Host() and never reads
// this.
func site(c *zip.Ctx, app *schema.Application) (domain, uri string) {
if app != nil {
origin := c.Header("Origin")
if oidc.Landing(app, origin) != "" {
_, host, _ := strings.Cut(origin, "://")
return host, origin + "/login"
}
}
host := trim(c.Host())
return host, "https://" + host + "/login"
}
// same reports whether the request is same-site: the Origin (else Referer) host
// equals the brand host the request arrived on.
//
// A request carrying NEITHER header is same-site: there is no browser
// cross-site context to abuse. A CSRF attack needs a browser, and browsers
// attach Origin to a cross-site POST; a native or server-side client sends
// neither, and refusing those would break wallet linking from them for no
// security gain. A malformed Origin/Referer, or one naming another host, is
// cross-site. Hosts compare case-insensitively (DNS is).
//
// The comparison target is the header-immune c.Host(), NOT a client header: an
// attacker who could also spoof X-Forwarded-Host to equal their forged Origin
// would otherwise pass this check cross-site. c.Host() is the true routed brand
// host, so a forged Origin can never match it.
func same(c *zip.Ctx) bool {
src := c.Header("Origin")
if src == "" {
src = c.Header("Referer")
}
if src == "" {
return true
}
if u, err := url.Parse(src); err == nil && u.Host != "" {
return strings.EqualFold(u.Host, trim(c.Host()))
}
return false // malformed → fail closed (treat as cross-site)
}
// random returns a crypto-random 32-character nonce (128 bits, far above the
// CAIP-122 minimum of 8). It MUST be random, never time-derived: a per-second id
// both COLLIDES on the (owner, name) key when two logins land in the same second
// and is guessable, weakening the replay guard the single-use burn provides.
func random() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// trim is the one input-trim used across the shell.
func trim(s string) string { return strings.TrimSpace(s) }