@stacks/auth
Construct and decode authentication requests for Stacks apps.
This package provides the auth logic used by the Stacks Connect library. If you're looking to integrate Stacks authentication into your web app, Stacks Connect provides a simple API and built-in user interface. See the authentication tutorial.
Installation
npm install @stacks/auth
Usage
Generating an authentication request
import { UserSession, makeAuthRequest, AppConfig } from '@stacks/auth';
The app domain is the URL to your website/app. This is how the Stacks authentication system identifies apps and determines what credentials to provide. Changing the app domain is equivalent to changing the app. Note that you also need to have a valid manifest.json file at the domain.
const appDomain = 'https://www.myapp.com';
Next we set the basic permissions for your app to read and store user data. If your app will allow users to share data with other users, you will need an additional publish_data
permission. We will also initiate a UserSession
object using the configuration.
const appConfig = new AppConfig(['store_write'], appDomain);
const userSession = new UserSession({ appConfig });
The authentication payloads are encrypted during transit, the encryption key generated below provides this
const transitKey = userSession.generateAndStoreTransitKey();
The Stacks auth process will open a compatible Stacks authenticator or browser extension to perform the authentication. So you will need to provide a redirect URL which the authenticator or extension can redirect to with the authentication payload. This page should process the authentication payload.
const redirectUri = 'https://www.myapp.com/auth';
Set the location of your app manifest file. This file contains information about your app that is shown to the user during authentication.
const manifestUri = 'https://www.myapp.com/manifest.json';
Finally generate the authentication request payload:
const authRequest = userSession.makeAuthRequest(transitKey, redirectUri, manifestUri);
The resulting payload can now be passed to a compatible Stacks authenticator or browser extension. If you are using Stacks connect, this is performed automatically.
If you would like to implement a Stacks authenticator, check out the reference implementation of the Stacks browser extension, Hiro Wallet.
Handling an authentication response payload
After an authenticator has processed your app's request, and the user has granted permission, the resulting response will be passed back to your app via the URL set in your redirectUri
.
Below, we use userSession.isSignInPending
to determine if there is an incoming authentication response. If detected, the userSession.handlePendingSignIn
method will process the response and provide a userData
object containing the user's identity, BNS username and profile information.
if (userSession.isSignInPending()) {
userSession.handlePendingSignIn().then(userData => {
});
}
Checking if the user is signed in
Use the userSession.isUserSignedIn
method to check if the user is already authenticated. If so, we can retrieve the user's profile data using userSession.loadUserData
.
if (userSession.isUserSignedIn()) {
const userData = userSession.loadUserData();
}
Sign out
To sign the user out simply call the userSession.signUserOut
method.
userSession.signUserOut();
Data encryption
Stacks authentication also provides an easy way to encrypt the user's data. If you are using the @stacks/storage
package, encryption is automatically enabled. If you would like to perform encryption outside of storage you can use the userSession.encryptContent
and userSession.decryptContent
methods.
const message = 'My secret message';
const cipherText = await userSession.encryptContent(message);
const plainText = await userSession.decryptContent(cipherText);
Note that encryption here uses the user's private key associated with your app only. If you need to share this data with another app or other users, you should use the equivalent methods from @stacks/encryption
and provide a custom private key.
7.0.0 (2024-10-25)
⚠ BREAKING CHANGES
See full list of changes at MIGRATION.md
- Update Cl.serialize to return string instead of bytes (3d4052b)
- Rename StacksTransaction to StacksTransactionWire (fe74e87)
- Update StacksTransaction constructor to options object (2b15209)
- Make StacksTransaction.serialize() return a hex-string instead of bytes (b563a2d)
- Rename message types (3d8b2dc)
- Remove BN.js compatibility (ddd8dde)
- Rename more types to use "Wire" suffix (221633a)
- Remove wrapper type for message signatures (bf08b46)
- Rename networking/fetch methods to include
fetch
prefix (463176a)
- Update post-condition representation to human readable types (a7cff36)
- Remove optional anchor mode from transaction options (2bec7ae)
- Remove wrapped private key type (a4e86ce)
- Change clarity types to be human readable (edad3b4)
- Update to new network object (57369cc)
Features
- Add origin post-condition principals (ccc79b3)
- Add
Address
namespace (1291687)
- Add STX unit helper methods (94f6c6b)
- Add postConditionToHex helper (e224b0e)
- Add
Cl.parse
Clarity value parser (b9f8775)
- Add non-sequential multi-sig support (and fix legacy multi-sig bugs) (879263c)
- Add serialization helpers for transaction (2c57ea4)
- Allow
0x
prefix in hexToBytes helper (33ca645)
- Use API for nonce detection if available (855ca69)
- Add new api package (9cf8a75)
- Cleanup common files (8316766)
Bug Fixes
- Update post conditions input in transactions (d005d19)
- Switch to a network and client param solution (e7370a0)
- Fix string parsing in structured signature decode (9760497)
- Remove legacy methods (6cece09)
- Generate compressed private keys by default (badc4bf)
- Compressing private key should ensure string format (350e1fa)
- Move more helper functions to take network parameter (b8cbde2)
- Remove signed option for intToBigInt (1a3cc2f)
- Allow .appendOrigin to be used with unwrapped public key (9c4a951)
- Improve address helper functions (e53528b)
- Allow network name in more helper functions (3d92cc7)
- Add
.bootAddress
to network objects (9993519)
- Disable legacy triplesec support for mnemonic encryption (9b98e44)
- Remove legacy CLI methods (3c373e1)
- Update remaining packages for api (2378096)
- Consolidate poxaddress return types (0dbe0db)