x402/examples
Sam Ragsdale fe42994900
feat(extensions): SIWX Extension (#921)
* feat(extensions): add Sign-In-With-X (SIWX) extension

Implements CAIP-122 compliant wallet-based identity assertions for x402 v2.

- Add SIWX types following CAIP-122 standard
- Server-side: declareSIWxExtension() for 402 response generation
- Client-side: createSIWxPayload() for proof creation and signing
- Message construction following CAIP-122 format
- Header encoding/parsing (base64 per x402 v2 spec)
- Validation: temporal, domain binding, nonce checking
- Verification: cryptographic signature validation via siwe library
- JSON Schema generation for payload validation
- Test coverage for core flows

* simplify; remove future looking code

* add integration test

* address own comments

* update readme, rm TODO.md

* add SIWS

* cleanup

* further cleanup

* split code path btwn evm and solana

* mv solana constants

* fmt

* lint

* rm .claude

* smart wallet verifier

* add domain param; support outside EVM verifier for contract wallets; Solana CAIP-2 compliant; rm clockskew slop

* fix missing type field; update lock file

* Add Sign-In-With-X extension spec

* server & client siwx examples

* chore: update pnpm-lock.yaml for sign-in-with-x examples

Update lockfile to include @types/node added to client example.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add wrapFetchWithSIWx helper to @x402/extensions

Adds a fetch wrapper for SIWX authentication that mirrors the
wrapFetchWithPayment pattern from @x402/fetch. The wrapper
automatically handles 402 responses with SIWX extension info.

Changes:
- Add fetch.ts with wrapFetchWithSIWx function
- Export wrapFetchWithSIWx from sign-in-with-x index
- Add DOM lib to tsconfig for Request/Response types
- Simplify client example to use the new wrapper
- Add .prettierignore and eslint globals to match other examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(extensions/siwx): Add lifecycle hooks for simplified DevX

Adds pre-built hooks that integrate SIWX with x402's lifecycle system:

- SIWxStorage interface + InMemorySIWxStorage for tracking paid addresses
- createSIWxSettleHook: records payments after settlement
- createSIWxRequestHook: validates SIWX auth before payment processing
- createSIWxClientHook: automatically tries SIWX auth on 402 responses

Simplifies examples dramatically by removing custom middleware in favor
of composable hooks that plug into the standard x402 lifecycle.

* fix(extensions/siwx): Improve hooks robustness and add tests

- Extract payer address from multiple payload formats (EVM, Solana)
- Add onEvent callback for logging/debugging
- Handle header case-insensitivity
- Add comprehensive tests for storage and all three hooks

* fix(extensions/siwx): Only record payment if settlement succeeded

Previously, createSIWxSettleHook would record payments even when
settlement failed, allowing free access to users who attempted
payment but failed. Now checks ctx.result.success before recording.

* style: Fix JSDoc and lint errors

* style: Fix formatting and JSDoc in examples

* refactor(extensions/siwx): Migrate to supportedChains[] architecture

Implements reviewer feedback (phdargen) on multi-chain architecture for
SIWX extension, separating message metadata from authentication capabilities.

- **NEW**: SupportedChain interface with chainId, type, signatureScheme
- **CHANGED**: SIWxExtensionInfo no longer includes chainId/type/signatureScheme
- **CHANGED**: SIWxExtension now has supportedChains[] array
- **CHANGED**: declareSIWxExtension accepts string|string[] for network param
- **CHANGED**: expirationTime (absolute) → expirationSeconds (relative)

- **server.ts**: siwxResourceServerExtension with enrichDeclaration hook
  - Refreshes nonce, issuedAt, expirationTime per request
  - Fixes critical bug where time-based fields never updated after startup

- **NEW**: CompleteSIWxInfo type = SIWxExtensionInfo + chain fields
- **CHANGED**: createSIWxClientHook uses exact chain matching via supportedChains
- **CHANGED**: fetch wrapper matches signer chain with supportedChains
- Updated utility functions (message, evm, solana) to use CompleteSIWxInfo

- All 65 SIWX tests updated for supportedChains[] structure
- Added multi-chain test coverage
- All tests passing (120/120 total)

- Updated spec with supportedChains[] examples
- Added multi-chain example in spec
- Updated README with hook-based approach (recommended)
- Added manual usage examples for advanced use cases
- Updated API reference with new parameters

- Server example updated to use siwxResourceServerExtension
- Client example unchanged (hook handles supportedChains internally)

- ✅ Single shared nonce (correct replay semantics)
- ✅ No metadata duplication (domain/uri/statement shared)
- ✅ Exact chain matching (no heuristics)
- ✅ 83% wire size reduction for 10-chain configurations
- ✅ Aligns with CAIP-122 mental model

- Extension structure: info no longer has chainId/type
- Clients must use supportedChains to find matching chain
- declareSIWxExtension: expirationTime → expirationSeconds
- Servers must call .registerExtension(siwxResourceServerExtension)

BREAKING CHANGE: First version - no migration needed

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(examples): Add getChainId() to signer for proper SIWX chain matching

Without this method, the client hook falls back to eip155:1 which doesn't
match the server's eip155:84532 (Base Sepolia), preventing SIWX auth from
working.

* refactor(extensions/siwx): Extract duplicated getSignerChainId helper

- Extract getSignerChainId to sign.ts (shared location)
- Remove duplicate from hooks.ts (-16 lines)
- Remove duplicate from fetch.ts (-14 lines)
- Net: -5 lines, eliminates code duplication

Co-locates all signer utilities (getEVMAddress, getSolanaAddress,
signEVMMessage, signSolanaMessage, getSignerChainId) in sign.ts for
better discoverability and maintainability.

* feat(examples/siwx): Add payment header logging to client

Shows whether each request used payment settlement or SIWX auth
by checking for PAYMENT-RESPONSE header. Helps debug auth flow.

* fix(examples/siwx): Improve payment flow logging

- Properly distinguish between payment success, payment failure, and SIWX auth
- Check body.error to detect payment failures (no PAYMENT-RESPONSE header)
- Bug investigation: Rapid successive payments fail with transaction_failed

Investigation findings:
- Wallet has sufficient funds (0.009 ETH, 0.984 USDC)
- EIP-3009 nonces are randomly generated (no collisions possible)
- Issue only occurs with rapid successive requests
- 2-second delay between requests works around the issue
- Facilitator returns generic 'transaction_failed' without detailed error

Likely cause: Race condition in facilitator's blockchain transaction
submission when handling concurrent payment authorizations.

Next steps: Need facilitator-level debugging to see actual error details.

* fix(examples/siwx): Add 300ms delay to avoid facilitator race condition

Testing shows 300ms is sufficient to work around the rapid payment issue.
Without delay: second payment fails with transaction_failed.
With 300ms: both payments succeed consistently.

This minimal delay allows the facilitator to properly handle concurrent
payment authorizations without blockchain transaction nonce conflicts.

* refactor(extensions/siwx): Use payment network instead of signer chain detection

Simplify SIWX by deriving chain from paymentRequired.accepts[0].network
instead of requiring signers to implement getChainId(). This removes
the need for the Object.assign hack in client code.

- Update createSIWxClientHook to use network from payment requirements
- Update wrapFetchWithSIWx similarly
- Remove unused getSignerChainId helper
- Simplify example client code

* refactor(extensions/siwx): Auto-derive network/domain/uri from context

Make declareSIWxExtension fields optional - they're now derived automatically
from request context by siwxResourceServerExtension:
- network: from accepts[].network in route config
- resourceUri: from request URL
- domain: parsed from resourceUri

This eliminates redundant configuration and reduces chance of mismatches.
Explicit values still override automatic derivation.

* refactor(extensions/siwx): Remove time-based fields from declareSIWxExtension

Time-based fields (nonce, issuedAt, expirationTime) are now generated
per-request by enrichPaymentRequiredResponse instead of at declaration
time. This ensures fresh nonces and accurate timestamps for each request.

- Remove nonce/issuedAt generation from declareSIWxExtension
- Store expirationSeconds in _options for per-request calculation
- Update tests to use generateTimeBasedFields helper to simulate
  server extension behavior

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(extensions/siwx): Add smart wallet docs, align signature schemes

- Remove sep10 and eip712 from supported signature schemes (not implemented)
- Add documentation for EIP-1271/EIP-6492 smart wallet verification
- Show how to use verifyOptions with createSIWxRequestHook
- Fix domain validation to use hostname instead of host (removes port)
- Add logging to example server for SIWX events
- Add tests for siwxResourceServerExtension

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: regenerate pnpm lockfile

Fixes ERR_PNPM_LOCKFILE_CONFIG_MISMATCH error in CI where the
"overrides" configuration didn't match the lockfile.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(examples/siwx): Add missing JSDoc to onEvent function

* fix(extensions/siwx): Use result.payer instead of extracting from payload

The SVM payment payload is just `{ transaction: string }` with no payer
field. The payer address is extracted by the facilitator during settlement
and returned in the SettleResponse.payer field.

This fix:
- Removes extractPayerAddress() which incorrectly assumed payload.payer exists
- Uses ctx.result.payer from the facilitator's settle response
- Updates tests to pass payer in result object

This ensures SIWX works correctly for both EVM and SVM payment flows.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(extensions/siwx): Add optional nonce tracking to prevent replay attacks

Adds optional hasUsedNonce/recordNonce methods to SIWxStorage interface
to prevent signature replay attacks. When a valid SIWX signature is
intercepted, it could be reused by an attacker to access resources
without paying.

Changes:
- Add optional hasUsedNonce?(nonce) and recordNonce?(nonce) to SIWxStorage
- Update createSIWxRequestHook to check/record nonces if methods exist
- Add nonce_reused event type for logging
- InMemorySIWxStorage unchanged (servers implement if they want protection)

This is opt-in: servers that want replay protection implement the
nonce methods in their storage. Servers without nonce tracking continue
to work as before.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: Add changeset for SIWX extension

* fix(examples/siwx): Add missing JSDoc params for onEvent function

* fix(extensions/siwx): Require both nonce methods or neither

Throw error at hook creation if only one of hasUsedNonce/recordNonce
is implemented, preventing silent failure of replay protection.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-03 08:39:02 +09:00
..
2025-12-11 07:41:57 -08:00