or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

access-controllers.mdaddress-management.mddatabase-types.mdidentity-system.mdindex.mdoplog-system.mdorbitdb-factory.mdstorage-backends.md

identity-system.mddocs/

0

# Identity System

1

2

OrbitDB's identity system provides cryptographic identity management for database operations and peer authentication. It enables secure, verifiable operations across the distributed network.

3

4

## Capabilities

5

6

### Identities Management

7

8

The Identities class manages identity creation, verification, and keystore integration.

9

10

```javascript { .api }

11

/**

12

* Creates an Identities instance

13

* @param params Configuration parameters

14

* @param params.ipfs IPFS instance for storage

15

* @param params.keystore Optional keystore instance

16

* @returns Promise resolving to Identities instance

17

*/

18

function Identities(params: {

19

ipfs: IPFS;

20

keystore?: KeyStore;

21

}): Promise<Identities>;

22

23

interface Identities {

24

/** Creates a new identity */

25

createIdentity(options?: IdentityOptions): Promise<Identity>;

26

/** Verifies an identity's authenticity */

27

verifyIdentity(identity: Identity): Promise<boolean>;

28

/** The keystore used by this identities instance */

29

keystore: KeyStore;

30

}

31

32

interface IdentityOptions {

33

/** Identity provider to use */

34

provider?: IdentityProvider;

35

/** Identity ID (auto-generated if not provided) */

36

id?: string;

37

/** Additional provider-specific options */

38

[key: string]: any;

39

}

40

```

41

42

**Usage Examples:**

43

44

```javascript

45

import { createHelia } from 'helia';

46

import { Identities, PublicKeyIdentityProvider } from '@orbitdb/core';

47

48

const ipfs = await createHelia();

49

50

// Create identities instance

51

const identities = await Identities({ ipfs });

52

53

// Create default identity

54

const identity1 = await identities.createIdentity();

55

56

// Create identity with custom provider

57

const identity2 = await identities.createIdentity({

58

provider: PublicKeyIdentityProvider()

59

});

60

61

// Create identity with specific ID

62

const identity3 = await identities.createIdentity({

63

id: 'my-custom-id'

64

});

65

66

console.log('Identity 1:', identity1.id);

67

console.log('Identity 2:', identity2.id);

68

console.log('Identity 3:', identity3.id);

69

```

70

71

### Identity Interface

72

73

Individual identities contain cryptographic information and metadata.

74

75

```javascript { .api }

76

interface Identity {

77

/** Unique identifier for this identity */

78

id: string;

79

/** Public key for verification */

80

publicKey: string;

81

/** Cryptographic signatures proving identity */

82

signatures: {

83

id: string;

84

publicKey: string;

85

};

86

/** Identity type (e.g., 'publickey') */

87

type: string;

88

/** The identity provider that created this identity */

89

provider: IdentityProvider;

90

}

91

92

/**

93

* Checks if an object is a valid Identity

94

* @param identity Object to test

95

* @returns True if object is a valid Identity

96

*/

97

function isIdentity(identity: any): identity is Identity;

98

99

/**

100

* Checks if two identities are equal

101

* @param identity1 First identity

102

* @param identity2 Second identity

103

* @returns True if identities are equal

104

*/

105

function isEqual(identity1: Identity, identity2: Identity): boolean;

106

```

107

108

**Usage Examples:**

109

110

```javascript

111

import { isIdentity, isEqual } from '@orbitdb/core';

112

113

const ipfs = await createHelia();

114

const identities = await Identities({ ipfs });

115

116

// Create identities

117

const identity1 = await identities.createIdentity();

118

const identity2 = await identities.createIdentity();

119

120

// Check if objects are identities

121

console.log(isIdentity(identity1)); // true

122

console.log(isIdentity({ id: 'fake' })); // false

123

124

// Compare identities

125

console.log(isEqual(identity1, identity1)); // true

126

console.log(isEqual(identity1, identity2)); // false

127

128

// Access identity properties

129

console.log('ID:', identity1.id);

130

console.log('Public Key:', identity1.publicKey);

131

console.log('Type:', identity1.type);

132

console.log('Signatures:', identity1.signatures);

133

```

134

135

### Identity Verification

136

137

Verify the authenticity and integrity of identities.

138

139

```javascript

140

import { Identities } from '@orbitdb/core';

141

142

const ipfs = await createHelia();

143

const identities = await Identities({ ipfs });

144

145

// Create and verify identity

146

const identity = await identities.createIdentity();

147

const isValid = await identities.verifyIdentity(identity);

148

console.log('Identity is valid:', isValid);

149

150

// Verify identity from another source

151

const receivedIdentity = JSON.parse(someIdentityJson);

152

const isReceivedValid = await identities.verifyIdentity(receivedIdentity);

153

console.log('Received identity is valid:', isReceivedValid);

154

```

155

156

### Public Key Identity Provider

157

158

The default identity provider using public key cryptography.

159

160

```javascript { .api }

161

/**

162

* Creates a PublicKeyIdentityProvider instance

163

* @param options Provider configuration options

164

* @returns PublicKeyIdentityProvider instance

165

*/

166

function PublicKeyIdentityProvider(options?: any): PublicKeyIdentityProvider;

167

168

interface PublicKeyIdentityProvider extends IdentityProvider {

169

/** Provider type identifier */

170

type: 'publickey';

171

172

/** Gets the ID from an identity */

173

getId(identity: Identity): string;

174

175

/** Signs identity data with keystore */

176

signIdentity(data: any, keystore: KeyStore): Promise<string>;

177

178

/** Verifies an identity's signatures */

179

verifyIdentity(identity: Identity): Promise<boolean>;

180

}

181

```

182

183

**Usage Examples:**

184

185

```javascript

186

import {

187

Identities,

188

PublicKeyIdentityProvider,

189

createOrbitDB

190

} from '@orbitdb/core';

191

192

const ipfs = await createHelia();

193

194

// Create identities with public key provider

195

const identities = await Identities({ ipfs });

196

const identity = await identities.createIdentity({

197

provider: PublicKeyIdentityProvider()

198

});

199

200

// Use identity with OrbitDB

201

const orbitdb = await createOrbitDB({

202

ipfs,

203

identity,

204

identities

205

});

206

207

console.log('OrbitDB identity:', orbitdb.identity.id);

208

```

209

210

### Custom Identity Providers

211

212

Create custom identity providers for different authentication schemes.

213

214

```javascript { .api }

215

/**

216

* Registers a custom identity provider

217

* @param provider Identity provider implementation

218

*/

219

function useIdentityProvider(provider: IdentityProvider): void;

220

221

/**

222

* Gets a registered identity provider by type

223

* @param type The provider type identifier

224

* @returns The identity provider instance

225

* @throws Error if provider type is not supported

226

*/

227

function getIdentityProvider(type: string): IdentityProvider;

228

229

interface IdentityProvider {

230

/** Unique type identifier */

231

type: string;

232

233

/** Gets the ID from an identity */

234

getId(identity: Identity): string;

235

236

/** Signs identity data */

237

signIdentity(data: any, keystore: KeyStore): Promise<string>;

238

239

/** Verifies an identity */

240

verifyIdentity(identity: Identity): Promise<boolean>;

241

242

/** Optional: creates identity data */

243

createIdentity?(options: any): Promise<any>;

244

}

245

```

246

247

**Usage Examples:**

248

249

```javascript

250

import { useIdentityProvider } from '@orbitdb/core';

251

252

// Custom OAuth-based identity provider

253

const OAuthIdentityProvider = {

254

type: 'oauth',

255

256

getId(identity) {

257

return identity.oauthId;

258

},

259

260

async signIdentity(data, keystore) {

261

// Sign with OAuth provider's key

262

const key = await keystore.getKey('oauth-signing-key');

263

return keystore.sign(key, data);

264

},

265

266

async verifyIdentity(identity) {

267

// Verify OAuth token with provider

268

try {

269

const response = await fetch(`https://oauth-provider.com/verify`, {

270

method: 'POST',

271

headers: { 'Authorization': `Bearer ${identity.oauthToken}` }

272

});

273

return response.ok;

274

} catch (error) {

275

return false;

276

}

277

},

278

279

async createIdentity(options) {

280

// Create identity from OAuth token

281

return {

282

oauthId: options.userId,

283

oauthToken: options.token,

284

publicKey: options.publicKey

285

};

286

}

287

};

288

289

// Register the custom provider

290

useIdentityProvider(OAuthIdentityProvider);

291

292

// Use custom provider

293

const identities = await Identities({ ipfs });

294

const oauthIdentity = await identities.createIdentity({

295

provider: OAuthIdentityProvider,

296

userId: 'user123',

297

token: 'oauth-token',

298

publicKey: 'public-key-data'

299

});

300

```

301

302

### JWT Identity Provider Example

303

304

Example of a JWT-based identity provider.

305

306

```javascript

307

const JWTIdentityProvider = {

308

type: 'jwt',

309

310

getId(identity) {

311

return identity.sub; // JWT subject

312

},

313

314

async signIdentity(data, keystore) {

315

// Sign data with JWT private key

316

const key = await keystore.getKey('jwt-key');

317

return keystore.sign(key, JSON.stringify(data));

318

},

319

320

async verifyIdentity(identity) {

321

try {

322

// Verify JWT signature and expiration

323

const jwt = identity.token;

324

const decoded = this.decodeJWT(jwt);

325

326

// Check expiration

327

if (decoded.exp && decoded.exp < Date.now() / 1000) {

328

return false;

329

}

330

331

// Verify signature (simplified)

332

return this.verifyJWTSignature(jwt, identity.publicKey);

333

} catch (error) {

334

return false;

335

}

336

},

337

338

decodeJWT(token) {

339

const parts = token.split('.');

340

return JSON.parse(atob(parts[1]));

341

},

342

343

verifyJWTSignature(token, publicKey) {

344

// JWT signature verification logic

345

// Implementation depends on JWT library

346

return true; // Simplified

347

}

348

};

349

350

useIdentityProvider(JWTIdentityProvider);

351

```

352

353

### Identity Storage and Persistence

354

355

Identities can be stored and reused across sessions.

356

357

```javascript

358

import { Identities } from '@orbitdb/core';

359

360

const ipfs = await createHelia();

361

const identities = await Identities({ ipfs });

362

363

// Create identity

364

const identity = await identities.createIdentity();

365

366

// Store identity (serialize)

367

const identityData = JSON.stringify({

368

id: identity.id,

369

publicKey: identity.publicKey,

370

signatures: identity.signatures,

371

type: identity.type

372

});

373

localStorage.setItem('orbitdb-identity', identityData);

374

375

// Later: restore identity

376

const storedData = localStorage.getItem('orbitdb-identity');

377

const restoredIdentity = JSON.parse(storedData);

378

379

// Verify restored identity

380

const isValid = await identities.verifyIdentity(restoredIdentity);

381

if (isValid) {

382

const orbitdb = await createOrbitDB({

383

ipfs,

384

identity: restoredIdentity,

385

identities

386

});

387

}

388

```

389

390

### Identity Integration with OrbitDB

391

392

Identities are automatically integrated with OrbitDB operations.

393

394

```javascript

395

import { createHelia } from 'helia';

396

import { createOrbitDB, Identities } from '@orbitdb/core';

397

398

const ipfs = await createHelia();

399

400

// Create custom identity

401

const identities = await Identities({ ipfs });

402

const identity = await identities.createIdentity({ id: 'my-app-user' });

403

404

// Create OrbitDB with custom identity

405

const orbitdb = await createOrbitDB({

406

ipfs,

407

identity,

408

identities

409

});

410

411

// All database operations will use this identity

412

const db = await orbitdb.open('my-db');

413

await db.add('Hello from my custom identity');

414

415

// Check which identity created entries

416

const entries = db.log.entries;

417

entries.forEach(entry => {

418

console.log('Entry created by:', entry.identity);

419

console.log('Matches our identity:', entry.identity === identity.id);

420

});

421

```

422

423

### Multi-Identity Management

424

425

Manage multiple identities for different purposes.

426

427

```javascript

428

const ipfs = await createHelia();

429

const identities = await Identities({ ipfs });

430

431

// Create different identities for different roles

432

const adminIdentity = await identities.createIdentity({ id: 'admin' });

433

const userIdentity = await identities.createIdentity({ id: 'user' });

434

const guestIdentity = await identities.createIdentity({ id: 'guest' });

435

436

// Use different identities for different databases

437

const adminDB = await createOrbitDB({

438

ipfs,

439

identity: adminIdentity,

440

identities

441

});

442

443

const userDB = await createOrbitDB({

444

ipfs,

445

identity: userIdentity,

446

identities

447

});

448

449

// Admin database with strict access control

450

const adminData = await adminDB.open('admin-data', {

451

AccessController: IPFSAccessController({

452

write: [adminIdentity.id]

453

})

454

});

455

456

// User database with broader access

457

const userData = await userDB.open('user-data', {

458

AccessController: IPFSAccessController({

459

write: [adminIdentity.id, userIdentity.id]

460

})

461

});

462

```

463

464

### Error Handling

465

466

Handle identity-related errors appropriately.

467

468

```javascript

469

import { Identities, isIdentity } from '@orbitdb/core';

470

471

try {

472

const ipfs = await createHelia();

473

const identities = await Identities({ ipfs });

474

475

// Create identity

476

const identity = await identities.createIdentity();

477

478

// Verify identity

479

const isValid = await identities.verifyIdentity(identity);

480

if (!isValid) {

481

throw new Error('Identity verification failed');

482

}

483

484

// Use with OrbitDB

485

const orbitdb = await createOrbitDB({ ipfs, identity, identities });

486

487

} catch (error) {

488

if (error.message.includes('Identity')) {

489

console.error('Identity error:', error.message);

490

} else if (error.message.includes('KeyStore')) {

491

console.error('KeyStore error:', error.message);

492

} else {

493

console.error('Unexpected error:', error.message);

494

}

495

}

496

497

// Validate identity objects

498

function validateIdentity(identity) {

499

if (!isIdentity(identity)) {

500

throw new Error('Invalid identity object');

501

}

502

503

if (!identity.id || !identity.publicKey) {

504

throw new Error('Identity missing required fields');

505

}

506

507

return true;

508

}

509

```

510

511

The identity system provides the cryptographic foundation for secure, verifiable operations in OrbitDB's distributed environment.