@me2em/core 0.4.2-alpha.1 → 0.4.4-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.github/workflows/ci.yml +0 -0
  2. package/CODE_OF_CONDUCT.md +73 -0
  3. package/CONTRIBUTING.md +145 -0
  4. package/GOVERNANCE.md +132 -0
  5. package/README.md +374 -189
  6. package/SECURITY.md +70 -0
  7. package/package.json +12 -36
  8. package/packages/core/README.md +656 -0
  9. package/packages/core/package.json +44 -0
  10. package/{src → packages/core/src}/crypto/ed25519.ts +4 -0
  11. package/{src → packages/core/src}/handle.ts +42 -6
  12. package/{src → packages/core/src}/identity.ts +33 -0
  13. package/packages/core/src/index.ts +35 -0
  14. package/packages/core/src/seed.ts +138 -0
  15. package/packages/core/src/session.ts +47 -0
  16. package/packages/core/test/derivation.spec.ts +117 -0
  17. package/packages/core/tsconfig.json +9 -0
  18. package/pnpm-workspace.yaml +2 -0
  19. package/specs/core.md +44 -0
  20. package/specs/openapi/server-ref.yaml +10 -0
  21. package/specs/test-vectors.json +13 -0
  22. package/tsconfig.base.json +20 -0
  23. package/typedoc.json +18 -0
  24. package/dist/crypto/ed25519.d.ts +0 -8
  25. package/dist/crypto/ed25519.d.ts.map +0 -1
  26. package/dist/crypto/ed25519.js +0 -8
  27. package/dist/crypto/ed25519.js.map +0 -1
  28. package/dist/crypto/hkdf.d.ts +0 -13
  29. package/dist/crypto/hkdf.d.ts.map +0 -1
  30. package/dist/crypto/hkdf.js +0 -16
  31. package/dist/crypto/hkdf.js.map +0 -1
  32. package/dist/crypto/index.d.ts +0 -3
  33. package/dist/crypto/index.d.ts.map +0 -1
  34. package/dist/crypto/index.js +0 -3
  35. package/dist/crypto/index.js.map +0 -1
  36. package/dist/crypto/init.d.ts +0 -9
  37. package/dist/crypto/init.d.ts.map +0 -1
  38. package/dist/crypto/init.js +0 -16
  39. package/dist/crypto/init.js.map +0 -1
  40. package/dist/handle.d.ts +0 -53
  41. package/dist/handle.d.ts.map +0 -1
  42. package/dist/handle.js +0 -79
  43. package/dist/handle.js.map +0 -1
  44. package/dist/identity.d.ts +0 -10
  45. package/dist/identity.d.ts.map +0 -1
  46. package/dist/identity.js +0 -38
  47. package/dist/identity.js.map +0 -1
  48. package/dist/index.d.ts +0 -7
  49. package/dist/index.d.ts.map +0 -1
  50. package/dist/index.js +0 -8
  51. package/dist/index.js.map +0 -1
  52. package/dist/seed.d.ts +0 -24
  53. package/dist/seed.d.ts.map +0 -1
  54. package/dist/seed.js +0 -55
  55. package/dist/seed.js.map +0 -1
  56. package/dist/session.d.ts +0 -20
  57. package/dist/session.d.ts.map +0 -1
  58. package/dist/session.js +0 -16
  59. package/dist/session.js.map +0 -1
  60. package/src/index.ts +0 -15
  61. package/src/seed.ts +0 -65
  62. package/src/session.ts +0 -25
  63. /package/{src → packages/core/src}/crypto/hkdf.ts +0 -0
  64. /package/{src → packages/core/src}/crypto/index.ts +0 -0
  65. /package/{src → packages/core/src}/crypto/init.ts +0 -0
@@ -1,5 +1,9 @@
1
1
  import { ed } from './init.js';
2
2
 
3
+ /**
4
+ * @internal
5
+ * Low-level Ed25519 implementation wrapper.
6
+ */
3
7
  export const getPublicKey = ed.getPublicKey;
4
8
  export const sign = ed.sign;
5
9
  export const verify = ed.verify;
@@ -8,12 +8,30 @@ export interface HandleMetadata {
8
8
  [key: string]: unknown;
9
9
  }
10
10
 
11
+ /**
12
+ * Represents a context-specific cryptographic handle derived from an {@link Identity}.
13
+ *
14
+ * A Handle encapsulates a private key tied to a specific name (context).
15
+ * It provides methods for signing data, verifying signatures, and deriving
16
+ * secondary secrets (like passwords or channel keys) without ever exposing
17
+ * the underlying private key.
18
+ *
19
+ * @category Core Primitives
20
+ */
11
21
  export class Handle {
12
22
  private readonly privateKey: Uint8Array;
13
23
  private readonly publicKey: Uint8Array;
14
24
  private readonly _name: string;
15
25
  private readonly _metadata?: HandleMetadata;
16
26
 
27
+ /**
28
+ * Creates a new Handle instance.
29
+ * @internal Typically created via {@link Identity.deriveHandle}.
30
+ *
31
+ * @param privateKey - The 32-byte Ed25519 private key for this handle.
32
+ * @param name - The context name this handle represents.
33
+ * @param metadata - Optional metadata associated with this handle.
34
+ */
17
35
  constructor(privateKey: Uint8Array, name: string, metadata?: HandleMetadata) {
18
36
  this.privateKey = privateKey;
19
37
  this.publicKey = ed.getPublicKey(privateKey);
@@ -21,6 +39,7 @@ export class Handle {
21
39
  this._metadata = metadata;
22
40
  }
23
41
 
42
+ /** @returns The unique context identifier for this Handle. */
24
43
  getId(): string {
25
44
  return btoa(String.fromCharCode(...this.publicKey))
26
45
  .replace(/\+/g, '-')
@@ -28,16 +47,33 @@ export class Handle {
28
47
  .replace(/=+$/, '');
29
48
  }
30
49
 
50
+ /**
51
+ * Cryptographically signs arbitrary data using the Handle's private key.
52
+ * @param data - The data to be signed, as a Uint8Array.
53
+ * @returns A Promise resolving to the Ed25519 signature as a Uint8Array.
54
+ */
31
55
  async sign(data: Uint8Array): Promise<Uint8Array> {
32
56
  return ed.sign(data, this.privateKey);
33
57
  }
34
58
 
59
+ /**
60
+ * Verifies an Ed25519 signature against the provided data and public key.
61
+ * @param signature - The signature to verify (Uint8Array).
62
+ * @param data - The original data that was signed (Uint8Array).
63
+ * @param publicKey - The public key to verify against (Uint8Array).
64
+ * @returns A Promise resolving to true if the signature is valid, false otherwise.
65
+ */
35
66
  static async verify(signature: Uint8Array, data: Uint8Array, publicKey: Uint8Array): Promise<boolean> {
36
67
  return ed.verify(signature, data, publicKey);
37
68
  }
38
69
 
70
+ /** @returns The context name associated with this Handle. */
39
71
  getName(): string { return this._name; }
72
+
73
+ /** @returns The metadata object associated with this Handle. */
40
74
  getMetadata(): HandleMetadata | undefined { return this._metadata; }
75
+
76
+ /** @returns A Uint8Array containing the 32-byte Ed25519 public key. */
41
77
  getPublicKey(): Uint8Array { return this.publicKey; }
42
78
 
43
79
  /**
@@ -67,16 +103,15 @@ export class Handle {
67
103
  * the Identity (controller) and this Handle (device/context).
68
104
  *
69
105
  * Both parties can independently compute this key because:
70
- * - The Handle possesses its own private key directly
71
- * - The Identity can derive the same private key via `identity.deriveHandle(name)`
106
+ * 1. The Handle possesses its own private key directly.
107
+ * 2. The Identity can derive the same private key via `identity.deriveHandle(name)`.
72
108
  *
73
109
  * This enables zero-knowledge encrypted channels without key exchange protocols.
74
110
  *
75
- * @param context - Channel identifier for domain separation (e.g., 'drone-001', 'session-abc').
76
- * Both parties MUST use the same context to derive the same key.
77
- * @returns 32-byte Uint8Array suitable for AES-256-GCM encryption.
78
- *
111
+ * @param context - Channel identifier for domain separation (e.g., 'drone-001', 'session-abc'). Both parties MUST use the same context.
112
+ * @returns A 32-byte Uint8Array suitable for AES-256-GCM encryption.
79
113
  * @example
114
+ * ```typescript
80
115
  * // On the drone (Handle side):
81
116
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
82
117
  * const encrypted = await encryptAESGCM(telemetry, channelKey);
@@ -85,6 +120,7 @@ export class Handle {
85
120
  * const droneHandle = await centerIdentity.deriveHandle('drone-001');
86
121
  * const channelKey = droneHandle.deriveChannelKey('telemetry-v1');
87
122
  * const decrypted = await decryptAESGCM(encrypted, channelKey);
123
+ * ```
88
124
  */
89
125
  deriveChannelKey(context: string): Uint8Array {
90
126
  const salt = new TextEncoder().encode(`me2em/channel/${context.toLowerCase().trim()}`);
@@ -5,6 +5,16 @@ import { Handle, type HandleMetadata } from './handle.js';
5
5
 
6
6
  const ME2EM_HKDF_INFO_PREFIX = 'me2em/handle/v1/';
7
7
 
8
+ /**
9
+ * Represents the root cryptographic identity derived from a seed phrase.
10
+ *
11
+ * An Identity is the foundation of the Me2em protocol. It allows for the
12
+ * hierarchical derivation of isolated {@link Handle}s for different contexts
13
+ * (e.g., email, social, specific devices) from a single master seed,
14
+ * ensuring zero cross-contamination of cryptographic material.
15
+ *
16
+ * @category Core Primitives
17
+ */
8
18
  export class Identity {
9
19
  private readonly privateKey: Uint8Array;
10
20
  private readonly publicKey: Uint8Array;
@@ -14,6 +24,13 @@ export class Identity {
14
24
  this.publicKey = ed.getPublicKey(privateKey); // Теперь работает синхронно
15
25
  }
16
26
 
27
+ /**
28
+ * Initializes a new Identity from a BIP39 mnemonic seed phrase or raw seed bytes.
29
+ *
30
+ * @param seed - A 12 or 24-word BIP39 mnemonic string, or a raw Uint8Array seed.
31
+ * @returns A Promise resolving to a new Identity instance.
32
+ * @throws {Error} If the provided seed is invalid or cannot be processed.
33
+ */
17
34
  static async fromSeed(seed: Uint8Array | string): Promise<Identity> {
18
35
  const seedBytes = typeof seed === 'string'
19
36
  ? Uint8Array.from(Buffer.from(seed, 'hex'))
@@ -34,6 +51,17 @@ export class Identity {
34
51
  return new Identity(key);
35
52
  }
36
53
 
54
+ /**
55
+ * Derives a new, cryptographically isolated {@link Handle} for a specific context.
56
+ *
57
+ * Each Handle is derived deterministically. The same name and metadata will
58
+ * always produce the same Handle from the same Identity, but different names
59
+ * produce completely unrelated keys.
60
+ *
61
+ * @param name - The context identifier (e.g., 'alice@example.com', 'device-1').
62
+ * @param metadata - Optional metadata to associate with this Handle.
63
+ * @returns A Promise resolving to the derived Handle.
64
+ */
37
65
  async deriveHandle(name: string, metadata?: HandleMetadata): Promise<Handle> {
38
66
  const info = new TextEncoder().encode(ME2EM_HKDF_INFO_PREFIX + name.toLowerCase().trim());
39
67
 
@@ -50,6 +78,11 @@ export class Identity {
50
78
  return new Handle(handleKey, name, metadata);
51
79
  }
52
80
 
81
+ /**
82
+ * Retrieves the public key of the root Identity.
83
+ *
84
+ * @returns A Uint8Array containing the 32-byte Ed25519 public key.
85
+ */
53
86
  getPublicKey(): Uint8Array {
54
87
  return this.publicKey;
55
88
  }
@@ -0,0 +1,35 @@
1
+ export { Identity } from './identity.js';
2
+ export { Handle, type HandleMetadata } from './handle.js';
3
+ export { Session, type SessionOptions, type SessionToken } from './session.js';
4
+ export * as crypto from './crypto/index.js';
5
+
6
+ /**
7
+ * @module @me2em/core
8
+ * @packageDocumentation
9
+ *
10
+ * Core cryptographic primitives for the Me2em authorization protocol.
11
+ *
12
+ * This package provides the foundation for decentralized, multi-context
13
+ * identity management and secure, stateless authentication.
14
+ *
15
+ * ## Key Features
16
+ * - **Hierarchical Identities**: Derive multiple isolated {@link Handle}s from a single seed.
17
+ * - **Stateless Auth**: Cryptographic proof without server-side session storage via {@link Session}.
18
+ * - **Zero-Knowledge Secrets**: Deterministic password derivation without storage.
19
+ *
20
+ * @example Basic usage
21
+ * ```typescript
22
+ * import { Identity } from '@me2em/core';
23
+ *
24
+ * const identity = await Identity.fromSeed('your twelve word mnemonic phrase here...');
25
+ * const handle = await identity.deriveHandle('user@example.com');
26
+ * const signature = await handle.sign(new TextEncoder().encode('data'));
27
+ * ```
28
+ */
29
+ export {
30
+ generateSeedPhrase,
31
+ normalizeSeedPhrase,
32
+ validateSeedPhrase,
33
+ get32ByteSeedFromMnemonic,
34
+ type SeedStrength
35
+ } from './seed.js';
@@ -0,0 +1,138 @@
1
+ import { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';
2
+ import { wordlist } from '@scure/bip39/wordlists/english';
3
+ import { sha256 } from './crypto/hkdf.js';
4
+
5
+ export type SeedStrength = 128 | 256; // 128 bits = 12 words, 256 bits = 24 words
6
+
7
+ /**
8
+ * Utilities for BIP39 mnemonic seed phrase generation and validation.
9
+ *
10
+ * These functions provide secure, deterministic seed phrase handling
11
+ * compatible with the BIP39 standard.
12
+ *
13
+ * @category Seed Utilities
14
+ * @packageDocumentation
15
+ */
16
+
17
+ /**
18
+ * Generates a cryptographically secure random mnemonic seed phrase.
19
+ *
20
+ * @param strength - The entropy strength in bits.
21
+ * - 128 bits = 12 words (standard security)
22
+ * - 160 bits = 15 words
23
+ * - 192 bits = 18 words
24
+ * - 224 bits = 21 words
25
+ * - 256 bits = 24 words (maximum security)
26
+ *
27
+ * @returns A Promise resolving to a space-separated mnemonic string.
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const mnemonic12 = await generateSeedPhrase(128);
32
+ * // "abandon abandon abandon ... art"
33
+ *
34
+ * const mnemonic24 = await generateSeedPhrase(256);
35
+ * // "abandon abandon abandon ... zoo" (24 words)
36
+ * ```
37
+ */
38
+ export function generateSeedPhrase(strength: SeedStrength = 128): string[] {
39
+ if (strength !== 128 && strength !== 256) {
40
+ throw new Error('Seed strength must be 128 (12 words) or 256 (24 words)');
41
+ }
42
+ const mnemonic = generateMnemonic(wordlist, strength);
43
+ return mnemonic.split(' ');
44
+ }
45
+
46
+ /**
47
+ * Normalizes a mnemonic seed phrase by trimming whitespace and converting to lowercase.
48
+ *
49
+ * @param phrase - The mnemonic phrase to normalize (string or array of words).
50
+ * @returns A normalized string of lowercase words separated by single spaces.
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const normalized = normalizeSeedPhrase(' ABANDON abandon ART ');
55
+ * // "abandon abandon art"
56
+ *
57
+ * const normalized2 = normalizeSeedPhrase(['abandon', ' ART ', 'zoo']);
58
+ * // "abandon art zoo"
59
+ * ```
60
+ */
61
+ export function normalizeSeedPhrase(seedPhrase: string | string[]): string[] {
62
+ const words = Array.isArray(seedPhrase) ? seedPhrase : seedPhrase.trim().split(/\s+/);
63
+ return words.map(word => word.toLowerCase().trim()).filter(word => word.length > 0);
64
+ }
65
+
66
+ /**
67
+ * Validates a mnemonic seed phrase against the BIP39 standard.
68
+ *
69
+ * Checks:
70
+ * - Correct word count (12, 15, 18, 21, or 24 words)
71
+ * - All words exist in the BIP39 wordlist
72
+ * - Valid checksum
73
+ *
74
+ * @param phrase - The mnemonic phrase to validate.
75
+ * @returns `true` if the phrase is valid, `false` otherwise.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const isValid = await validateSeedPhrase('abandon abandon ... art');
80
+ * // true
81
+ *
82
+ * const isInvalid = await validateSeedPhrase('invalid word list ...');
83
+ * // false
84
+ * ```
85
+ */
86
+ export function validateSeedPhrase(words: string[]): { isValid: boolean; error?: string } {
87
+ const wordCount = words.length;
88
+ if (wordCount !== 12 && wordCount !== 24) {
89
+ return { isValid: false, error: `Seed phrase must be 12 or 24 words, got ${wordCount}` };
90
+ }
91
+
92
+ const normalized = normalizeSeedPhrase(words);
93
+ for (const word of normalized) {
94
+ if (!wordlist.includes(word)) {
95
+ return { isValid: false, error: `Invalid word: ${word}` };
96
+ }
97
+ }
98
+
99
+ const isValid = validateMnemonic(normalized.join(' '), wordlist);
100
+ return { isValid, error: isValid ? undefined : 'Invalid seed phrase checksum' };
101
+ }
102
+
103
+ /**
104
+ * Derives a 32-byte cryptographic seed from a BIP39 mnemonic phrase using PBKDF2.
105
+ *
106
+ * This is the standard BIP39 derivation function that converts a human-readable
107
+ * mnemonic into a binary seed suitable for key generation.
108
+ *
109
+ * @param phrase - The BIP39 mnemonic phrase (will be normalized automatically).
110
+ * @param passphrase - Optional passphrase for additional security (BIP39 "25th word").
111
+ * @returns A Promise resolving to a 32-byte Uint8Array seed.
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * const seed = await get32ByteSeedFromMnemonic('abandon abandon ... art');
116
+ * // Uint8Array(32) [123, 45, 67, ...]
117
+ *
118
+ * const seedWithPassphrase = await get32ByteSeedFromMnemonic(
119
+ * 'abandon abandon ... art',
120
+ * 'mySecretPassphrase'
121
+ * );
122
+ * // Different seed even with same mnemonic
123
+ * ```
124
+ */
125
+ export async function get32ByteSeedFromMnemonic(seedPhrase: string | string[]): Promise<Uint8Array> {
126
+ const words = normalizeSeedPhrase(seedPhrase);
127
+ const validation = validateSeedPhrase(words);
128
+
129
+ if (!validation.isValid) {
130
+ throw new Error(`Invalid seed phrase: ${validation.error}`);
131
+ }
132
+
133
+ const mnemonic = words.join(' ');
134
+ const seed64 = await mnemonicToSeed(mnemonic);
135
+
136
+ // Hash the 64-byte seed to get a deterministic 32-byte seed for Ed25519
137
+ return sha256(seed64);
138
+ }
@@ -0,0 +1,47 @@
1
+ export interface SessionOptions {
2
+ audience: string;
3
+ scopes: string[];
4
+ ttl?: number; // в секундах
5
+ }
6
+
7
+ export interface SessionToken {
8
+ handleId: string;
9
+ scopes: string[];
10
+ expiresAt: number;
11
+ token: string;
12
+ }
13
+
14
+ /**
15
+ * Represents a stateless, cryptographically verifiable session token.
16
+ *
17
+ * Instead of storing session state on the server, the Session object
18
+ * encapsulates all necessary authorization data (handle ID, scopes, expiration)
19
+ * into a self-contained structure that can be verified using the Handle's public key.
20
+ *
21
+ * @category Core Primitives
22
+ */
23
+ export class Session {
24
+
25
+ /**
26
+ * Creates a new Session instance.
27
+ *
28
+ * @param handleId - The ID of the Handle that authorized this session.
29
+ * @param scopes - An array of permission scopes granted in this session (e.g., ['read', 'write']).
30
+ * @param expiresAt - Unix timestamp (in milliseconds) when this session expires.
31
+ * @param token - The cryptographic token string (e.g., JWT or custom signature format).
32
+ */
33
+ constructor(
34
+ public readonly handleId: string,
35
+ public readonly scopes: string[],
36
+ public readonly expiresAt: number,
37
+ public readonly token: string
38
+ ) {}
39
+
40
+ /**
41
+ * Checks if the session has expired based on the current time.
42
+ * @returns `true` if the current time is past the `expiresAt` timestamp, `false` otherwise.
43
+ */
44
+ isExpired(): boolean {
45
+ return Date.now() >= this.expiresAt * 1000;
46
+ }
47
+ }
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Identity, Handle, generateSeedPhrase, get32ByteSeedFromMnemonic, validateSeedPhrase } from '../src/index.js';
3
+
4
+ describe('Me2em Core Functionality', () => {
5
+ const testSeed = new Uint8Array(32).fill(42);
6
+
7
+ describe('Identity & Handle Derivation', () => {
8
+ it('should derive same HandleId from same seed + name', async () => {
9
+ const identity1 = await Identity.fromSeed(testSeed);
10
+ const handle1a = await identity1.deriveHandle('work');
11
+ const handle1b = await identity1.deriveHandle('private');
12
+
13
+ const identity2 = await Identity.fromSeed(testSeed);
14
+ const handle2a = await identity2.deriveHandle('work');
15
+
16
+ expect(handle1a.getId()).toBe(handle2a.getId());
17
+ expect(handle1a.getId()).not.toBe(handle1b.getId());
18
+ });
19
+
20
+ it('should attach and retrieve metadata', async () => {
21
+ const identity = await Identity.fromSeed(testSeed);
22
+ const metadata = { displayName: 'Alice', role: 'admin' };
23
+ const handle = await identity.deriveHandle('work', metadata);
24
+
25
+ expect(handle.getName()).toBe('work');
26
+ expect(handle.getMetadata()).toEqual(metadata);
27
+ });
28
+ });
29
+
30
+ describe('Handle.derivePassword', () => {
31
+ it('should deterministically derive the same password', async () => {
32
+ const identity = await Identity.fromSeed(testSeed);
33
+ const handle = await identity.deriveHandle('google');
34
+
35
+ const pwd1 = handle.derivePassword('google', 16);
36
+ const pwd2 = handle.derivePassword('google', 16);
37
+
38
+ expect(pwd1).toBe(pwd2);
39
+ expect(pwd1.length).toBeGreaterThan(0);
40
+ expect(pwd1).toMatch(/^[A-Za-z0-9_-]{22}$/);
41
+ });
42
+
43
+ it('should derive different passwords for different contexts', async () => {
44
+ const identity = await Identity.fromSeed(testSeed);
45
+ const handle = await identity.deriveHandle('google');
46
+
47
+ const pwdGoogle = handle.derivePassword('google');
48
+ const pwdGithub = handle.derivePassword('github');
49
+
50
+ expect(pwdGoogle).not.toBe(pwdGithub);
51
+ });
52
+ });
53
+
54
+ describe('Handle.deriveChannelKey', () => {
55
+ it('should deterministically derive a 32-byte channel key', async () => {
56
+ const identity = await Identity.fromSeed(testSeed);
57
+ const handle = await identity.deriveHandle('drone-001');
58
+
59
+ const key1 = handle.deriveChannelKey('telemetry-v1');
60
+ const key2 = handle.deriveChannelKey('telemetry-v1');
61
+
62
+ expect(key1).toEqual(key2);
63
+ expect(key1.length).toBe(32);
64
+ expect(key1).toBeInstanceOf(Uint8Array);
65
+ });
66
+
67
+ it('should derive different keys for different contexts', async () => {
68
+ const identity = await Identity.fromSeed(testSeed);
69
+ const handle = await identity.deriveHandle('drone-001');
70
+
71
+ const keyTelemetry = handle.deriveChannelKey('telemetry');
72
+ const keyCommand = handle.deriveChannelKey('command');
73
+
74
+ expect(keyTelemetry).not.toEqual(keyCommand);
75
+ });
76
+ });
77
+
78
+ describe('BIP39 Seed Utilities', () => {
79
+ it('should generate valid 12-word and 24-word phrases', () => {
80
+ const phrase12 = generateSeedPhrase(128);
81
+ expect(phrase12.length).toBe(12);
82
+ expect(validateSeedPhrase(phrase12).isValid).toBe(true);
83
+
84
+ const phrase24 = generateSeedPhrase(256);
85
+ expect(phrase24.length).toBe(24);
86
+ expect(validateSeedPhrase(phrase24).isValid).toBe(true);
87
+ });
88
+
89
+ it('should reject invalid seed phrases', () => {
90
+ const invalid = ['apple', 'banana', 'cherry'];
91
+ const result = validateSeedPhrase(invalid);
92
+ expect(result.isValid).toBe(false);
93
+ expect(result.error).toContain('must be 12 or 24 words');
94
+ });
95
+
96
+ it('should convert mnemonic to deterministic 32-byte seed', async () => {
97
+ const phrase = generateSeedPhrase(128);
98
+ const seedBytes = await get32ByteSeedFromMnemonic(phrase);
99
+
100
+ expect(seedBytes.length).toBe(32);
101
+ expect(seedBytes).toBeInstanceOf(Uint8Array);
102
+
103
+ const identity = await Identity.fromSeed(seedBytes);
104
+ expect(identity.getPublicKey().length).toBe(32);
105
+ });
106
+
107
+ it('should produce identical Identity from string and array mnemonic', async () => {
108
+ const phraseArray = generateSeedPhrase(128);
109
+ const phraseString = phraseArray.join(' ');
110
+
111
+ const seed1 = await get32ByteSeedFromMnemonic(phraseArray);
112
+ const seed2 = await get32ByteSeedFromMnemonic(phraseString);
113
+
114
+ expect(seed1).toEqual(seed2);
115
+ });
116
+ });
117
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "dist", "test"]
9
+ }
@@ -0,0 +1,2 @@
1
+ packages:
2
+ - 'packages/*'
@@ -0,0 +1,44 @@
1
+ # Me2em Protocol Specification v0.1
2
+
3
+ ## 1. Cryptographic Primitives
4
+ - **Root Key**: Ed25519
5
+ - **Derivation**: HKDF-SHA256
6
+ - **Handle Key**: Ed25519 (independent pair per handle)
7
+ - **Signature**: Ed25519 pure
8
+
9
+ ## 2. Identity Derivation
10
+ ```
11
+ RootPrivateKey = HKDF-SHA256(
12
+ InputKeyMaterial = Seed (32 bytes)
13
+ Info = "me2em/identity/v1/root"
14
+ Length = 32
15
+ )
16
+ ```
17
+
18
+ ## 3. Handle Derivation
19
+ ```
20
+ HandlePrivateKey = HKDF-SHA256(
21
+ InputKeyMaterial = RootPrivateKey
22
+ Info = "me2em/handle/v1/<lowercase_name>"
23
+ Length = 32
24
+ )
25
+ HandleId = Base64Url(Ed25519.PublicKey(HandlePrivateKey))
26
+ ```
27
+
28
+ ## 4. Authentication Flow
29
+ 1. Client sends `handleId` → requests challenge
30
+ 2. Server returns `nonce` (256-bit random, TTL 2m)
31
+ 3. Client signs `nonce` with `HandlePrivateKey`
32
+ 4. Client sends `signature`
33
+ 5. Server verifies with `HandlePublicKey` (from registry)
34
+ 6. On success: issues `SessionToken(handleId, scopes, expires)`
35
+
36
+ ## 5. Session Token Structure
37
+ ```json
38
+ {
39
+ "handleId": "base64url_pubkey",
40
+ "scopes": ["read:messages", "write:profile"],
41
+ "expiresAt": 1716912000,
42
+ "sig": "ed25519_signature_of_payload"
43
+ }
44
+ ```
@@ -0,0 +1,10 @@
1
+ paths:
2
+ /handles/register:
3
+ post:
4
+ summary: Register a new handle (public key + metadata)
5
+ /auth/challenge:
6
+ post:
7
+ summary: Request challenge for authentication
8
+ /auth/verify:
9
+ post:
10
+ summary: Verify challenge signature and issue session token
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "algorithm": "HKDF-SHA256 + Ed25519",
4
+ "vectors": [
5
+ {
6
+ "description": "Basic derivation: seed + 'work'",
7
+ "seed_hex": "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a",
8
+ "handle_name": "work",
9
+ "expected_handle_id": "Ab3...Xy9",
10
+ "expected_public_key_hex": "deadbeef..."
11
+ }
12
+ ]
13
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022", "DOM"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "declaration": true,
13
+ "declarationMap": true,
14
+ "sourceMap": true,
15
+ "resolveJsonModule": true,
16
+ "isolatedModules": true,
17
+ "allowImportingTsExtensions": false
18
+ },
19
+ "exclude": ["node_modules", "dist", "**/*.test.ts"]
20
+ }
package/typedoc.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "https://typedoc.org/schema.json",
3
+ "entryPoints": ["packages/core/src/index.ts"],
4
+ "out": "docs",
5
+ "name": "me2em Protocol API Reference",
6
+ "includeVersion": true,
7
+ "excludePrivate": true,
8
+ "excludeProtected": true,
9
+ "excludeInternal": true,
10
+ "readme": "packages/core/README.md",
11
+ "skipErrorChecking": true,
12
+ "navigation": {
13
+ "includeCategories": true,
14
+ "includeGroups": true
15
+ },
16
+ "categorizeByGroup": true,
17
+ "sort": ["source-order", "alphabetical"]
18
+ }
@@ -1,8 +0,0 @@
1
- import { ed } from './init.js';
2
- export declare const getPublicKey: (secretKey: ed.TArg<Uint8Array>) => ed.TRet<Uint8Array>;
3
- export declare const sign: (message: ed.TArg<Uint8Array>, secretKey: ed.TArg<Uint8Array>) => ed.TRet<Uint8Array>;
4
- export declare const verify: (signature: ed.TArg<Uint8Array>, message: ed.TArg<Uint8Array>, publicKey: ed.TArg<Uint8Array>, opts?: ed.TArg<ed.EdDSAVerifyOpts>) => boolean;
5
- export declare const getPublicKeyAsync: (secretKey: ed.TArg<Uint8Array>) => Promise<ed.TRet<Uint8Array>>;
6
- export declare const signAsync: (message: ed.TArg<Uint8Array>, secretKey: ed.TArg<Uint8Array>) => Promise<ed.TRet<Uint8Array>>;
7
- export declare const verifyAsync: (signature: ed.TArg<Uint8Array>, message: ed.TArg<Uint8Array>, publicKey: ed.TArg<Uint8Array>, opts?: ed.TArg<ed.EdDSAVerifyOpts>) => Promise<boolean>;
8
- //# sourceMappingURL=ed25519.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["../../src/crypto/ed25519.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,WAAW,CAAC;AAE/B,eAAO,MAAM,YAAY,yDAAkB,CAAC;AAC5C,eAAO,MAAM,IAAI,uFAAU,CAAC;AAC5B,eAAO,MAAM,MAAM,+IAAY,CAAC;AAChC,eAAO,MAAM,iBAAiB,kEAAuB,CAAC;AACtD,eAAO,MAAM,SAAS,gGAAe,CAAC;AACtC,eAAO,MAAM,WAAW,wJAAiB,CAAC"}
@@ -1,8 +0,0 @@
1
- import { ed } from './init.js';
2
- export const getPublicKey = ed.getPublicKey;
3
- export const sign = ed.sign;
4
- export const verify = ed.verify;
5
- export const getPublicKeyAsync = ed.getPublicKeyAsync;
6
- export const signAsync = ed.signAsync;
7
- export const verifyAsync = ed.verifyAsync;
8
- //# sourceMappingURL=ed25519.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ed25519.js","sourceRoot":"","sources":["../../src/crypto/ed25519.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,WAAW,CAAC;AAE/B,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC;AAC5C,MAAM,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC;AAC5B,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,CAAC,MAAM,CAAC;AAChC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC,iBAAiB,CAAC;AACtD,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC;AACtC,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC,WAAW,CAAC"}