• Stars
    star
    194
  • Rank 200,219 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Space SDK is a JavaScript/Typescript library for building web and mobile applications leveraging Open Web and distributed protocols like IPFS, Textile, GunDB, and Ethereum.

Space SDK

Fleek Dev Slack License

Javascript/Typescript library for interacting with Space in web/browser applications via an implementation of the Space API. Build websites or applications that can easily leverage Open Web protocols (IPFS, Textile, GunDB, Ethereum) to enable Web3-ready features like:

  • File and directory storage / retrieval in user-controlled, encrypted, and distributed storage.
  • Key-pair based identity management and challenge-based authentication.
  • Decentralized and secure key and bucket metadata storage.
  • Private and end-to-end encrypted, or public file sharing.

The Space SDK is a close friend of the Space Daemon, its desktop-focused counterpart.

You can find the SDK's documentation here:

Default Implementations

The Space SDK is modular and protocol agnostic. You can use the APIs and interfaces as is, with Space's default implementations, or replace them with your own custom ones.

Feature Description Service/Protocol
Users Key-pair based identity creation, and challenge authentication. Textile Users API
Storage File, directory, and bucket creation/listing. IPFS / Textile
Metadata Secure Bucket/directory schema storage GunDB
Sharing Private and public file sharing Textile

Introduction

@spacehq/sdk provides a suit of functionality to perform different action on Space.

Installation

Install the sdk using this npm command:

npm install @spacehq/sdk

Usage

Space SDK provides an interface perform the following actions:

  • Creating identities

  • Create files and directories

  • List files and directories

  • Creating buckets

  • Sharing buckets

Full SDK Documentation with examples can be found here

1. Identities

This involves managing users and their identities.

import { Users } from '@spacehq/sdk';

const users = new Users({ endpoint: 'wss://dev.space.storage' });

// createIdentity generate a random keypair identity
const identity = await users.createIdentity();

// the new keypair can be used to authenticate a new user
// `users.authenticate()` generates hub API session tokens for the keypair identity.
const user = await users.authenticate(identity);
// `user` can be used with the storage class to provide identity.

// user's identity can also be backed up with a special recovery phrase
const uuid = 'specify-uuid-representing-user-in-your-system';
const passphrase = 'specify-unique-pass-phrase-related-to-backup-type';
const backupType = VaultBackupType.Google;
await users.backupKeysByPassphrase(uuid, passphrase, backupType, user.identity);

// backed up users identity can also be recovered later
const recoveredUser = await users.recoverKeysByPassphrase(uuid, passphrase, backupType);
// `recoveredUser` has same authentication as `user` above.

Check the User's class for more examples of how to manage users with the sdk.

2. Storage

This involves operations to create and list files and directories in space storage.

import { UserStorage, AddItemsResultSummary } from '@spacehq/sdk';

const storage = new UserStorage(user);
await storage.createFolder({ bucket: 'personal', path: 'topFolder' });
const result = await storage.listDirectory({ bucket: 'personal', path: '' });
// result contains `topFolder` items

// upload a file
const uploadResponse = await spaceStorage.addItems({
   bucket: 'personal',
   files: [
     {
       path: 'file.txt',
       content: '',
     },
     {
       path: 'space.png',
       content: '',
     }
   ],
});
// uploadresponse is an event listener
uploadResponse.once('done', (data: AddItemsEventData) => {
  const summary = data as AddItemsResultSummary;
  // returns a summary of all files and their upload status
});

3. Sharing

This includes operations to share your storage items with existing user (identities)

import { UserStorage } from '@space/sdk';

const storage = new UserStorage(user);

// you can share privately with existing users via their public key:
await storage.shareViaPublicKey({
    publicKeys: [{
      id: '[email protected]', // or any identifier for the user
      pk: 'user-pk-hex-or-multibase', // optional, omit if user doesn't exist yet, it would generate temp access key
    }],
    paths: [{
        bucket: 'personal',
        path: '/file/path/here'
    }],
});

// or you could share the file publicly by generating a link. Generated link references
await spaceStorage.setFilePublicAccess({
  bucket: 'personal',
  path: '/file.txt',
  allowAccess: true, // <- set to false to revoke public access
});

Migrating from Space Daemon

If you are already familiar with the space daemon and its gRPC methods and would like to start using the space-sdk here are some pointers on how those gRPC methods correspond to functionalities exposed by the space-sdk.

Key Pairs (GenerateKeyPair)

In the sdk the concept of Key Pairs is represented as an Identity. To create a new Identity similar to the GenerateKeyPair method, you would do:

import { Users, BrowserStorage } from '@spacehq/sdk';

const users = new Users({ endpoint: 'wss://auth-dev.space.storage' });

// createIdentity generate a random keypair identity
const identity = await users.createIdentity();

identity represents a keypair and its primary key is accessible via identity.public.toString().

Managing authenticated users

In space-daemon the generated keypair is stored in the operating systems keychain but in space-sdk you would need to provide an IdentityStorage to the Users class when initializing it. For the browser environment there exists a BrowserStorage implementation you can use.

import { Users, BrowserStorage } from '@spacehq/sdk';

const users = await Users.withStorage(
    new BrowserStorage(), 
    { endpoint: 'wss://auth-dev.space.storage' }
);

Users.withStorage will load and authenticate all identities that exist inside the provided IdentityStorage. You can access all authenticated users through the Users.list method.

const spaceUsers = await users.list();

To authenticate a new user identity and get a SpaceUser, you can call the Users.authenticate method:

const spaceUser = await users.authenticate(identity);

Users.authentication would do two things:

  • Generate a SpaceUser.
  • Stores the new users information in the IdentityStorage, so subsequent initialization of Users.withStorage() would have the users loaded.

NOTE: An existing space user can also be gotten from Users.recoverKeysByPassphrase.

To delete a user from users lists, you can delete the user by pass the publicKey of that user to Users.remove.

await users.remove(spaceUser.identity.public.toString());

Managing current active user

If you have the concept of a current active user in your application that uses space-sdk. We recommend that you keep track of that users public key in your application and use it to filter the list method's result to get the authenticated SpaceUser for that public key.

On logout, you can call the remove method to stop tracking the user.

GetAPISessionToken

In space daemon GetAPISessionToken returns the message:

message GetAPISessionTokensResponse {
  string hubToken = 1;
  string servicesToken = 2;
}

In order to get the servicesToken and hubToken for a particular user, you would need to authenticate that user identity:

const spaceUser = await users.authenticate(identity);

The spaceUser.token value is the servicesToken, while the spaceUser.storageAuth.token is the hubToken.

Also, note that when an existing user is recovered via the Users.recoverKeysByPassphrase method, the SpaceUser returns is also authenticated and has the session tokens.

GetPublicKey

In space daemon GetPublicKey returned the id of the current keypair in keychain, but since space-sdk returns the identity object. You can get the public key bytes for a particular identity through identity.public.pubKey.

Also, an authenticated SpaceUser identity can be found in the identity field.

Storage Methods (createFolder, listDirectory, openFile, addItems)

The storage gRPC methods on space daemon can now be performed using the UserStorage class of the space-sdk.

import { UserStorage, AddItemsResultSummary } from '@spacehq/sdk';

const storage = new UserStorage(user);
await storage.createFolder({ bucket: 'personal', path: 'topFolder' });
const result = await storage.listDirectory({ path: '' });
// result contains `topFolder` items

// upload a file
const uploadResponse = await spaceStorage.addItems({
   bucket: 'personal',
   files: [
     {
       path: 'file.txt',
       content: 'plain-text-value',
     },
     {
       path: 'space.png',
       content: '', // could also be a ReadableStream<Uint8Array> or ArrayBuffer
     }
   ],
});
// uploadresponse is an event listener
uploadResponse.once('done', (data: AddItemsEventData) => {
  const summary = data as AddItemsResultSummary;
  // returns a summary of all files and their upload status
});

// read content of an uploaded file
const fileResponse = await storage.openFile({ bucket: 'personal', path: '/file.txt'});
const fileContent = await fileResponse.consumeStream();
// new TextDecoder('utf8').decode(actualTxtContent) == 'plain-text-value'

Contributing

All contributions are welcome. Before getting started, kindly take some time to review our contributing guidelines and code of conduct.

LICENSE

MIT

More Repositories

1

space-daemon

The Space Daemon packages together IPFS, Textile Threads/Buckets, and Textile Powergate (Filecoin*) into one easy to install Daemon to make it easy to build peer to peer and privacy focused apps.
Go
220
star
2

fleek-docs

Fleek's Technical Documentation
HTML
96
star
3

space-client

File Upload (encrypted), File Sharing, Filecoin Markets (TBD), and User Controlled Data. You can access same methods from the Space Daemon using our JS client, so you don't need to worry about gRPC calls.
JavaScript
77
star
4

apollo-cursor-pagination

Relay's Connection implementation for Apollo Server GraphQL library
JavaScript
61
star
5

IC-Deploy-Action

Github action that wraps dfx commands to deploy canisters to Dfinity on push
JavaScript
43
star
6

space-client-workshop

Workshop and Example to showcase how to build a desktop application on top of the Space Daemon and Client. From installation to building a full fledged private and peer to peer application
JavaScript
35
star
7

fleek-storage-js

JS SDK to interact with Fleek Storage
JavaScript
33
star
8

webflow-example

Quick example of how to build a static Webflow site on Fleek with a Python script.
JavaScript
17
star
9

space-web

JavaScript
14
star
10

space-desktop

JavaScript
13
star
11

brokkr

Background job processing and orchestrator for Node
TypeScript
12
star
12

site-builder-docker-images

Docker images for the site builder. Used for automated builds on docker hub.
Shell
9
star
13

action-deploy

Github Action to deploy code to a Fleek Site
Shell
8
star
14

tflow

Git Flow for managing Terminal apps
TypeScript
8
star
15

space-services

Back end services for Space App
TypeScript
8
star
16

knex-flex-filter

Flexible filtering and search for Knex queries
JavaScript
7
star
17

ic-proxy

HTTPS Proxy to Internet Computer
TypeScript
4
star
18

ic-auth-test

TypeScript
2
star
19

space-gundb-peer

GunDB Relay Peer in-sync with space-sdk's latest gundb version
JavaScript
2
star
20

javascript-style-guide

Javascript style guide to use across node / react / other javascript projects
JavaScript
1
star
21

workflows

Workflow configurations for the GitHub Actions CI/CD Plugin.
1
star
22

crdt-text-editor

JavaScript
1
star
23

terminal-graphql-directives

Terminal repository for GraphQL Directives
JavaScript
1
star
24

space-help-docs

Space's technical documentation and basic guides
1
star
25

fleek.xyz

aka Fleek Web3
TypeScript
1
star