did-session
Version:
Manage user DIDs in a web environment
218 lines (217 loc) • 7.66 kB
TypeScript
/**
* Manages user account DIDs in web based environments.
*
* ## Purpose
*
* Manages, creates and authorizes a DID session key for a user. Returns an authenticated DIDs instance
* to be used in other Ceramic libraries. Supports did:pkh for blockchain accounts with Sign-In with
* Ethereum and CACAO for authorization.
*
* ## Installation
*
* ```sh
* npm install did-session
* ```
*
* ## Usage
*
* Authorize and use DIDs where needed. Import the AuthMethod you need, Ethereum accounts used here for example.
*
* ```js
* import { DIDSession } from 'did-session'
* import { EthereumWebAuth, getAccountId } from '@didtools/pkh-ethereum'
*
* const ethProvider = // import/get your web3 eth provider
* const addresses = await ethProvider.request({ method: 'eth_requestAccounts' })
* const accountId = await getAccountId(ethProvider, addresses[0])
* const authMethod = await EthereumWebAuth.getAuthMethod(ethprovider, accountId)
*
* const session = await DIDSession.get(accountId, authMethod, { resources: [...]})
*
* // Uses DIDs in ceramic & glaze libraries, ie
* const ceramic = new CeramicClient()
* ceramic.did = session.did
*
* // pass ceramic instance where needed
*
* ```
*
* Additional helper functions are available to help you manage a session lifecycle and the user experience.
*
* ```js
* // Check if authorized or created from existing session string
* didsession.hasSession
*
* // Check if session expired
* didsession.isExpired
*
* // Get resources session is authorized for
* didsession.authorizations
*
* // Check number of seconds till expiration, may want to re auth user at a time before expiration
* didsession.expiresInSecs
* ```
*
* ## Configuration
*
* The resources your app needs to write access to must be passed during authorization. Resources are an array
* of Model Stream Ids or Streams Ids. Typically you will just pass resources from `@composedb` libraries as
* you will already manage your Composites and Models there. For example:
*
* ```js
* import { ComposeClient } from '@composedb/client'
*
* //... Reference above and `@composedb` docs for additional configuration here
*
* const client = new ComposeClient({ceramic, definition})
* const resources = client.resources
* const session = await DIDSession.get(accountId, authMethod, { resources })
* client.setDID(session.did)
* ```
*
* By default a session will expire in 1 week. You can change this time by passing the `expiresInSecs` option to
* indicate how many seconds from the current time you want this session to expire.
*
* ```js
* const oneDay = 60 * 60 * 24
* const session = await DIDSession.get(accountId, authMethod, { resources: [...], expiresInSecs: oneDay })
* ```
*
* A domain/app name is used when making requests, by default in a browser based environment the library will use
* the domain name of your app. If you are using the library in a non web based environment you will need to pass
* the `domain` option otherwise an error will thrown.
*
* ```js
* const session = await DIDSession.get(accountId, authMethod, { resources: [...], domain: 'YourAppName' })
* ```
*
* ## Upgrading from `@glazed/did-session` to `did-session`
*
* `authorize` changes to a static method which returns a did-session instance and `getDID()` becomes a `did` getter. For example:
*
* ```js
* // Before @glazed/did-session
* const session = new DIDSession({ authProvider })
* const did = await session.authorize()
*
* // Now did-session
* const session = await DIDSession.get(accountId, authMethod, { resources: [...]})
* const did = session.did
* ```
*
* ## Upgrading from `did-session@0.x.x` to `did-session@1.x.x`
*
* AuthProviders change to AuthMethod interfaces. Similarly you can import the auth libraries you need. How you configure and manage
* these AuthMethods may differ, but each will return an AuthMethod function to be used with did-session.
*
* ```js
* // Before with v0.x.x
* ...
* import { EthereumAuthProvider } from '@ceramicnetwork/blockchain-utils-linking'
*
* const ethProvider = // import/get your web3 eth provider
* const addresses = await ethProvider.request({ method: 'eth_requestAccounts' })
* const authProvider = new EthereumAuthProvider(ethProvider, addresses[0])
* const session = new DIDSession({ authProvider })
* const did = await session.authorize()
*
* // Now did-session@1.0.0
* ...
* import { EthereumWebAuth, getAccountId } from '@didtools/pkh-ethereum'
*
* const ethProvider = // import/get your web3 eth provider
* const addresses = await ethProvider.request({ method: 'eth_requestAccounts' })
* const accountId = await getAccountId(ethProvider, addresses[0])
* const authMethod = await EthereumWebAuth.getAuthMethod(ethProvider, accountId)
* const session = await DIDSession.get(accountId, authMethod, { resources: [...]})
* const did = session.did
* ```
*
* @module did-session
*/
import { DID } from 'dids';
import { AccountId } from 'caip';
import type { Cacao, AuthMethod } from '@didtools/cacao';
export type SessionParams = {
keySeed?: Uint8Array;
cacao: Cacao;
did: DID;
};
interface AuthOpts {
domain?: string;
statement?: string;
version?: string;
nonce?: string;
requestId?: string;
expirationTime?: string;
resources?: Array<string>;
expiresInSecs?: number;
}
export declare function createDIDKey(seed?: Uint8Array): Promise<DID>;
export declare function createDIDCacao(didKey: DID, cacao: Cacao): Promise<DID>;
export declare function getAccountIdByDID(did: string): AccountId;
export declare function cacaoContainsResources(cacao: Cacao, resources: Array<string>): boolean;
/**
* DID Session
*
* ```sh
* import { DIDSession } from 'did-session'
* ```
*/
export declare class DIDSession {
#private;
constructor(params: SessionParams);
/**
* Request authorization for session
*/
static authorize(authMethod: AuthMethod, authOpts?: AuthOpts): Promise<DIDSession>;
static initDID(didKey: DID, cacao: Cacao): Promise<DID>;
/**
* Get a session for the given accountId, if one exists, otherwise creates a new one.
*/
static get(account: AccountId, authMethod: AuthMethod, authOpts?: AuthOpts): Promise<DIDSession>;
/**
* Removes a session from storage for a given account (if created using `DIDSession.get`)
*/
static remove(account: AccountId): Promise<void>;
/**
* Check if there is an active session for a given account.
*/
static hasSessionFor(account: AccountId, resources: Array<string>): Promise<boolean>;
/**
* Get DID instance, if authorized
*/
get did(): DID;
/**
* Serialize session into string, can store and initalize the same session again while valid
*/
serialize(): string;
/**
* Initialize a session from a serialized session string
*/
static fromSession(session: string): Promise<DIDSession>;
get hasSession(): boolean;
/**
* Determine if a session is expired or not
*/
get isExpired(): boolean;
/**
* Number of seconds until a session expires
*/
get expireInSecs(): number;
/**
* Get the list of resources a session is authorized for
*/
get authorizations(): Array<string>;
/**
* Get the session CACAO
*/
get cacao(): Cacao;
/**
* Determine if session is available and optionally if authorized for given resources
*/
isAuthorized(resources?: Array<string>): boolean;
/** DID string associated to the session instance. session.id == session.getDID().parent */
get id(): string;
}
export {};