Module @web3-storage/access


web3.storage

The access client for https://web3.storage

About

The @web3-storage/access package provides an API for creating and managing "agents," which are software entities that control private signing keys and can invoke capabilities on behalf of a user (or another agent).

Agents are used to invoke capabilities provided by the w3up service layer, using the ucanto RPC framework. Agents are created locally on an end-user's device, and users are encouraged to create new agents for each device (or browser) that they want to use, rather than sharing agent keys between devices.

An Agent can create "spaces," which are namespaces for content stored on the w3up platform. Each space has its own keypair, the public half of which is used to form a did:key: URI that uniquely identifies the space. The space's private key is used to delegate capabilities to a primary agent, which then issues ucanto requests related to the space.

Although agents (and spaces) are created locally by generating keypairs, the w3up services will only act upon spaces that have been registered with the w3up access service. By default, a newly-created agent will be configured to use the production access service for remote operations, including registration.

Please note that the @web3-storage/access package is a fairly "low level" component of the w3up JavaScript stack, and most users will be better served by @web3-storage/w3up-client, which combines this package with a client for the upload and storage service and presents a simpler API.

Install

Install the package:

npm install @web3-storage/access

Usage

API Reference

Agent creation

To create an agent, you must first create a Store, which the agent will use to store and manage persistent state, including private keys.

If you're running in a web browser, use StoreIndexedDB, which uses IndexedDB to store non-extractable CryptoKey objects. This prevents the private key material from ever being exposed to the JavaScript environment.

Agents in a browser use RSA keys, which can be generated using the async generate function from @ucanto/principal/rsa.

import { Agent } from '@web3-storage/access/agent'
import { StoreIndexedDB } from '@web3-storage/access/stores/store-indexeddb'
import { generate } from '@ucanto/principal/rsa'

async function createAgent() {
const store = await StoreIndexedDB.open('my-db-name')

// if agent data already exists in the store, use it to create an Agent.
const data = await store.load()
if (data) {
return Agent.from(data, { store })
}

// otherwise, generate a new RSA signing key to act as the Agent's principal
// and create a new Agent, passing in the store so the Agent can persist its state
const principal = await generate()
const agentData = {
meta: { name: 'my-browser-agent' },
principal
}
return Agent.create(agentData, { store })
}

On node.js, use StoreConf, which uses the conf package to store keys and metadata in the user's platform-specific default configuration location (usually in their home directory).

Agents on node should use Ed25519 keys:

import { Agent } from '@web3-storage/access/agent'
import { StoreConf } from '@web3-storage/access/stores/store-conf'
import { generate } from '@ucanto/principal/ed25519'

async function createAgent() {
const store = new StoreConf({ profile: 'my-w3up-app' })
if (!(await store.exists())) {
await store.init({})
}

// if agent data already exists in the store, use it to create an Agent.
const data = await store.load()
if (data) {
return Agent.from(data, { store })
}

// otherwise, generate a new Ed25519 signing key to act as the Agent's principal
// and create a new Agent, passing in the store so the Agent can persist its state
const principal = await generate()
const agentData = {
meta: { name: 'my-nodejs-agent' },
principal
}
return Agent.create(agentData, { store })
}

See the AgentCreateOptions reference if you want to configure the agent to use a non-production service connection.

Space creation

A newly-created agent does not have access to any spaces, and is thus unable to store data using the w3up platform.

To create a new space, use agent.createSpace, optionally passing in a human-readable name.

This will create a new signing keypair for the space and use it to issue a non-expiring delegation for all space-related capabilities to the agent, which will persist the delegation in its Store for future use.

The createSpace method returns an object describing the space:

interface CreateSpaceResult {
/** The Space's Decentralized Identity Document (DID) */
did: string,

/**
* Metadata for the Space, including optional friendly `name` and an `isRegistered` flag.
* Persisted locally in the Agent's Store.
*/
meta: Record<string, unknown>,

/**
* Cryptographic proof of the delegation from Space to Agent.
* Persisted locally in the Agent's Store.
*/
proof: Ucanto.Delegation
}

Managing the current space

An agent can create multiple spaces and may also be issued delegations that allow it to manage spaces created by other agents. The agent's spaces property is a Map keyed by space DID, whose values are the metadata associated with each space.

Agents may also have a "current" space, which is used as the default space for storage operations if none is specified. You can retrieve the DID of the current space with agent.currentSpace. If you also want the metadata and proofs associated with the space, use agent.currentSpaceWithMeta.

To set the current space, use agent.setCurrentSpace. Note that this must be done explicitly; creating an agent's first space does not automatically set it as the current space.

Space registration

A newly-created space must be registered with the w3up access service before it can be used as a storage location.

To register a space, use agent.registerSpace, which takes an email address parameter and registers the current space with the access service.

Calling registerSpace will cause the access service to send a confirmation email to the provided email address. When the activation link in the email is clicked, the service will send the agent a delegation via a WebSocket connection that grants access to the services included in w3up's free tier. The registerSpace method returns a Promise that resolves once the registration process is complete. Make sure to wrap calls to registerSpace in a try/catch block, as registration will fail if the user does not confirm the email (or if network issues arise, etc.).

Delegating to another agent

The agent's delegate method allows you to delegate capabilities to another agent.

const delegation = await agent.delegate({
audience: 'did:key:kAgentToDelegateTo',
abilities: [
{
can: 'space/info',
with: agent.currentSpace()
}
]
})

Note that the receiving agent will need to import the delegation before they will be able to invoke the delegated capabilities.

Importing delegations from another agent

The addProof method takes in a ucanto Delegation and adds it to the agent's state Store. The proof of delegation can be retrieved using the agent's proofs method.

The importSpaceFromDelegation method also accepts a ucanto Delegation, but it is tailored for "full delegation" of all space-related capabilities. The delegated ability must be *, which is the "top" ability that can derive all abilities for the Space's DID. Use importSpaceFromDelegation in preference to addProofs when importing a full * delegation for a space, as it also adds metadata about the imported space to the Agent's persistent store and adds the space to the agent's set of authorized spaces.

Contributing

Feel free to join in. All welcome. Please open an issue!

License

Dual-licensed under MIT + Apache 2.0

References

Modules

Namespaces

Classes

Interfaces

AccessAuthorizeFailure AccessAuthorizeSuccess AccessClaimFailure AccessClaimSuccess AccessConfirmFailure AccessConfirmSuccess AccountNotFound AdminStoreInspectSuccess AdminUploadInspectSuccess AgentDataModel AgentDataOptions AgentMessage AgentMessageBuilder AgentMessageData AgentMeta AgentOptions AggregateAcceptSuccess AggregateOfferSuccess AllocatedMemoryHadNotBeenWrittenTo Amplify Archive Authorization AwaitError BlobAcceptSuccess BlobAddSuccess BlobAddress BlobAllocateSuccess BlobListItem BlobListSuccess BlobModel BlobRemoveSuccess BlobSizeOutsideOfSupportedRange BuildOptions ByteView CanIssue CapabilitiesParser Capability CapabilityMatch CapabilityParser CapabilityQuery Caveats ClaimOptions ClientCodec ComposedDIDParser CompositeImporter Connection ConnectionOptions ConnectionView ConsumerGetSuccess ConsumerNotFound ContentNotFound CustomerGetSuccess CustomerNotFound DIDKeyResolutionError DataAggregationProof DealDetails DealInfoSuccess DealMetadata DealNotFound DelegationError DelegationMeta DelegationNotFound DerivedMatch Derives DirectMatch Do Effects EffectsModel ErrorBuilder EscalatedDelegation Expired FilecoinAcceptSuccess FilecoinInfoAcceptedAggregate FilecoinInfoAcceptedDeal FilecoinInfoSuccess FilecoinOfferSuccess FilecoinSubmitSuccess ForkBuilder GroupSelector HTTPError HandlerExecutionError HandlerNotFound IPLDBlock IPLDView IPLDViewBuilder Importer InboundAcceptCodec InboundCodec InclusionProof InstructionModel InsufficientStorage InvalidAudience InvalidClaim InvalidContentPiece InvalidPiece InvalidPieceCID InvalidPlanName InvalidProvider InvalidRevocationScope InvalidSignature Invocation InvocationContext InvocationOptions IssuedInvocation IssuedInvocationView JoinBuilder Link ListResponse MalformedCapability Match MatchSelector Matcher Meta MultibaseDecoder MultibaseEncoder MultihashDigest MultihashHasher NotEnoughStorageCapacity NotValidBefore OkBuilder OutboundCodec OutboundTransportOptions OutcomeModel ParsedCapability Phantom PieceAcceptSuccess PieceOfferSuccess PlanGetSuccess PlanNotFound PlanUpdateError Principal PrincipalOptions PrincipalParser PrincipalResolver ProofNotFound ProofResolver ProviderAddSuccess ProviderInput RateLimitAddSuccess RateLimitListSuccess RateLimitSubject RateLimitsNotFound Reader ReceiptModel RecordNotFound ReferencedInvocationNotFound Report ReportBuilder ReportModel RevocationChecker RevocationsStoreFailure Revoked Select Selector Server ServerOptions ServerView ServiceMethod SessionEscalation ShardNotFound Signature SignatureError SignatureView Signer SignerArchive SignerImporter SignerKey SingletonMarketSource SliceNotFound Source SpaceAdmin SpaceInfoResult SpaceMeta SpaceUnknown StorageOperationError StoreAddSuccessDone StoreAddSuccessResult StoreAddSuccessUpload StoreItemNotFound StoreListItem StoreListSuccess StoreRemoveSuccess SubscriptionGetSuccess SubscriptionListItem SubscriptionListSuccess SubscriptionNotFound TheCapabilityParser Timestamp UCANAwait UCANBasicOptions UCANBlock UCANLink UCANNotFound UCANOptions Unauthorized UnauthorizedRevocation UnavailableProof UnexpectedError Unit UnknownCapability UnknownFormat UnknownMatch UnknownProvider UploadListItem UploadListSuccess UploadNotFound UsageData ValidationOptions Validator ValidatorOptions Verifier VerifierKey View

Type Aliases

API Abilities AbilitiesArray Ability AccessAuthorize AccessClaim AccessConfirm AccessDelegate AccessDelegateFailure AccessDelegateSuccess AccountDID Admin AdminStoreInspect AdminStoreInspectFailure AdminUploadInspect AdminUploadInspectFailure AgentDataExport AgentMessageModel AggregateAccept AggregateAcceptFailure AggregateOffer AggregateOfferFailure Allows AttachedLinkSet AuthorizationWaiter AuthorizationWaiterOpts Await Blob BlobAccept BlobAcceptFailure BlobAdd BlobAddFailure BlobAllocate BlobAllocateFailure BlobList BlobListFailure BlobRemove BlobRemoveFailure BlockStore BytesDelegation CARLink CIDString Capabilities ConsumerGet ConsumerGetFailure ConsumerHas ConsumerHasFailure ConsumerHasSuccess CustomerGet CustomerGetFailure DID DIDKey DealInfo DealInfoFailure DelegationJSON DelegationOptions DelegationsChecker DidMailto Domain Effect EmailAddress EmptyObject EncodedDelegation ExecuteInvocation Fact FilecoinAccept FilecoinAcceptFailure FilecoinAddress FilecoinInfo FilecoinInfoFailure FilecoinOffer FilecoinOfferFailure FilecoinSubmit FilecoinSubmitFailure HTTPPut ISO8601Date ImpliedInvocationModel Index IndexAdd IndexAddFailure IndexAddSuccess InferAllowedFromCapabilities InferAllowedFromCapability InferAllowedFromDelegation InferAllowedFromDelegations InferCapability InferCreateOptions InferDelegatedCapability InferDelegationOptions InferDeriveProof InferInvocation InferInvocations InferInvokeOptions InferInvokedCapability InferMatch InferMembers InferNb InferReceipt InferReceipts InferServiceInvocationReturn InferServiceInvocations InferTransaction InferValue Intersection InvalidCapability InvalidProof InvocationError InvocationService InvokeOptions JSONUnknown JoinAbilities JoinAllows KeyArchive LinkJSON LocalPart MatchResult MulticodecCode Multihash PercentEncoded PieceAccept PieceAcceptFailure PieceLink PieceLinkSchema PieceOffer PieceOfferFailure PlanGet PlanGetFailure PlanSet PlanSetFailure PlanSetSuccess Proof ProofJSON Protocol ProviderAdd ProviderAddFailure ProviderDID ProviderMethod RateLimitAdd RateLimitAddFailure RateLimitList RateLimitListFailure RateLimitRemove RateLimitRemoveFailure RateLimitRemoveSuccess Receipt ResolveServiceInvocation ResolveServiceMethod Resource ResourceAbilities ResourceQuery Run Service ServiceAbility ServiceAbilityArray ServiceBlob ServiceInvocation ServiceInvocations SigAlg SpaceDID SpaceInfo StorageGetError StoragePutError Store StoreAdd StoreAddSuccess StoreAddSuccessStatusDone StoreAddSuccessStatusUpload StoreGet StoreGetFailure StoreGetSuccess StoreList StoreRemove StoreRemoveFailure SubscriptionGet SubscriptionGetFailure SubscriptionList SubscriptionListFailure ToJSON ToString Top Transaction UCANAttest UCANConclude UCANConcludeFailure UCANConcludeSuccess UCANRevoke UCANRevokeFailure UCANRevokeSuccess URI UTCUnixTimestamp UnknownLink Upload UploadAdd UploadAddSuccess UploadGet UploadGetFailure UploadGetSuccess UploadList UploadRemove UploadRemoveSuccess Usage UsageReport UsageReportFailure UsageReportSuccess Variant

Functions

References

Re-exports Block
Re-exports Channel
Re-exports EncodeOptions
Renames and re-exports Error
Re-exports HTTPRequest
Re-exports HTTPResponse
Renames and re-exports Link
Re-exports OwnedSpace
Re-exports RequestDecoder
Re-exports RequestEncodeOptions
Re-exports RequestEncoder
Re-exports ResponseDecoder
Re-exports ResponseEncoder
Re-exports Result
Re-exports SharedSpace
Re-exports Tuple

Generated using TypeDoc