@me2em/core 0.4.4-alpha.2 → 0.7.0-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 (70) hide show
  1. package/README.md +294 -546
  2. package/dist/attestation.d.ts +151 -0
  3. package/dist/attestation.d.ts.map +1 -0
  4. package/dist/attestation.js +279 -0
  5. package/dist/attestation.js.map +1 -0
  6. package/dist/canonical-name.d.ts +3 -0
  7. package/dist/canonical-name.d.ts.map +1 -0
  8. package/dist/canonical-name.js +12 -0
  9. package/dist/canonical-name.js.map +1 -0
  10. package/dist/crypto/derivation-paths.d.ts +41 -0
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -0
  12. package/dist/crypto/derivation-paths.js +50 -0
  13. package/dist/crypto/derivation-paths.js.map +1 -0
  14. package/dist/crypto/ed25519.d.ts +48 -8
  15. package/dist/crypto/ed25519.d.ts.map +1 -1
  16. package/dist/crypto/ed25519.js +63 -8
  17. package/dist/crypto/ed25519.js.map +1 -1
  18. package/dist/crypto/hkdf.d.ts.map +1 -1
  19. package/dist/crypto/hkdf.js +1 -0
  20. package/dist/crypto/hkdf.js.map +1 -1
  21. package/dist/crypto/index.d.ts +1 -0
  22. package/dist/crypto/index.d.ts.map +1 -1
  23. package/dist/crypto/index.js +2 -0
  24. package/dist/crypto/index.js.map +1 -1
  25. package/dist/crypto/init.d.ts.map +1 -1
  26. package/dist/crypto/init.js +1 -0
  27. package/dist/crypto/init.js.map +1 -1
  28. package/dist/handle.d.ts +149 -35
  29. package/dist/handle.d.ts.map +1 -1
  30. package/dist/handle.js +180 -40
  31. package/dist/handle.js.map +1 -1
  32. package/dist/identity.d.ts +99 -19
  33. package/dist/identity.d.ts.map +1 -1
  34. package/dist/identity.js +128 -32
  35. package/dist/identity.js.map +1 -1
  36. package/dist/index.d.ts +5 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/seed.d.ts +38 -39
  41. package/dist/seed.d.ts.map +1 -1
  42. package/dist/seed.js +36 -41
  43. package/dist/seed.js.map +1 -1
  44. package/dist/session.d.ts +207 -17
  45. package/dist/session.d.ts.map +1 -1
  46. package/dist/session.js +428 -11
  47. package/dist/session.js.map +1 -1
  48. package/dist/subhandle.d.ts +126 -0
  49. package/dist/subhandle.d.ts.map +1 -0
  50. package/dist/subhandle.js +182 -0
  51. package/dist/subhandle.js.map +1 -0
  52. package/dist/util.d.ts +9 -0
  53. package/dist/util.d.ts.map +1 -0
  54. package/dist/util.js +34 -0
  55. package/dist/util.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/attestation.ts +364 -0
  58. package/src/canonical-name.ts +12 -0
  59. package/src/crypto/derivation-paths.ts +56 -0
  60. package/src/crypto/ed25519.ts +82 -8
  61. package/src/crypto/hkdf.ts +2 -0
  62. package/src/crypto/index.ts +3 -1
  63. package/src/crypto/init.ts +1 -0
  64. package/src/handle.ts +227 -42
  65. package/src/identity.ts +164 -35
  66. package/src/index.ts +5 -1
  67. package/src/seed.ts +59 -59
  68. package/src/session.ts +637 -24
  69. package/src/subhandle.ts +254 -0
  70. package/src/util.ts +35 -0
@@ -0,0 +1,254 @@
1
+ // subhandle.ts
2
+ //
3
+ // SubHandle is a leaf node in the Me2em derivation tree.
4
+ // With MAX_DEPTH = 2, a SubHandle CANNOT derive children.
5
+ // It inherits from Handle for polymorphism in Session handling.
6
+
7
+ import { Handle, type HandleMetadata } from './handle.js';
8
+ import { normalizeName } from './canonical-name.js';
9
+
10
+ /**
11
+ * Metadata for a {@link SubHandle}, extending {@link HandleMetadata} with
12
+ * constraints that govern session creation.
13
+ *
14
+ * All constraint fields are optional. When present, they are enforced by
15
+ * {@link SubHandle.validateSessionOptions} at session creation time.
16
+ *
17
+ * @category Types
18
+ */
19
+ export interface SubHandleMetadata extends HandleMetadata {
20
+ /**
21
+ * Restricts the set of audiences this SubHandle may create sessions for.
22
+ * `undefined` = unrestricted; `[]` = deny all.
23
+ */
24
+ allowedAudiences?: string[];
25
+
26
+ /**
27
+ * Restricts the set of scopes this SubHandle may request in sessions.
28
+ * `undefined` = unrestricted; `[]` = deny all.
29
+ */
30
+ allowedScopes?: string[];
31
+
32
+ /**
33
+ * Maximum allowed TTL (in seconds) for sessions created by this SubHandle.
34
+ * Attempts to create a session with a larger TTL will be rejected.
35
+ */
36
+ maxSessionTtl?: number;
37
+
38
+ /**
39
+ * Unix timestamp (in seconds) at which this SubHandle itself expires.
40
+ * After this time, any attempt to create a session will fail.
41
+ * Useful for temporary access grants (e.g., contractor access for 2 weeks).
42
+ */
43
+ expiresAt?: number;
44
+ }
45
+
46
+ /**
47
+ * Extracts only display-safe fields for the base Handle metadata.
48
+ * Constraint fields stay in SubHandle's own storage and must never
49
+ * leak through Handle.getMetadata().
50
+ */
51
+ function extractDisplayFields(
52
+ meta?: SubHandleMetadata
53
+ ): HandleMetadata | undefined {
54
+ if (!meta) return undefined;
55
+ const display: HandleMetadata = {};
56
+ if (meta.displayName !== undefined) display.displayName = meta.displayName;
57
+ if (meta.avatar !== undefined) display.avatar = meta.avatar;
58
+ // copy any other custom fields, but never the constraint ones
59
+ const CONSTRAINT_KEYS = new Set([
60
+ 'allowedAudiences', 'allowedScopes', 'maxSessionTtl', 'expiresAt',
61
+ ]);
62
+ for (const [k, v] of Object.entries(meta)) {
63
+ if (!CONSTRAINT_KEYS.has(k)) {
64
+ (display as Record<string, unknown>)[k] = v;
65
+ }
66
+ }
67
+ return display;
68
+ }
69
+
70
+ /**
71
+ * Represents a context-isolated child Handle in the Me2em hierarchy.
72
+ *
73
+ * A SubHandle is always derived from a parent {@link Handle} and represents
74
+ * a leaf node in the derivation tree (MAX_DEPTH = 2). It inherits all
75
+ * cryptographic capabilities of Handle (signing, key derivation, etc.) but
76
+ * adds:
77
+ *
78
+ * - A **derivation path** (`[handleName, subName]`) carried in session tokens.
79
+ * - **Constraint enforcement** on audience, scopes, and TTL at session creation.
80
+ * - An optional **expiration timestamp** for temporary access grants.
81
+ *
82
+ * SubHandle is used for polymorphism in {@link Session}: both Handle and
83
+ * SubHandle can create and verify sessions, but SubHandle sessions carry
84
+ * the additional `hPath` field for hierarchical auditing.
85
+ *
86
+ * @category Core Primitives
87
+ */
88
+ export class SubHandle extends Handle {
89
+ private readonly _path: string[];
90
+ private readonly _subMetadata: SubHandleMetadata;
91
+
92
+ /**
93
+ * Creates a new SubHandle instance.
94
+ *
95
+ * @internal Typically created via {@link Handle.deriveSubHandle} or
96
+ * {@link Identity.deriveSubHandle}. Direct construction is discouraged.
97
+ *
98
+ * @param privateKey - The 32-byte Ed25519 private key for this SubHandle.
99
+ * @param name - The SubHandle name.
100
+ * @param path - The derivation path, must have exactly 2 elements: `[handleName, subName]`.
101
+ * @param subMetadata - Optional constraints and metadata.
102
+ * @throws {Error} If the path does not have exactly 2 elements.
103
+ */
104
+ constructor(
105
+ privateKey: Uint8Array,
106
+ name: string,
107
+ path: string[],
108
+ subMetadata?: SubHandleMetadata
109
+ ) {
110
+ super(privateKey, name, extractDisplayFields(subMetadata));
111
+
112
+ if (path.length !== 2) {
113
+ throw new Error(
114
+ `SubHandle path must have exactly 2 elements: [handleName, subName]. Got ${path.length}.`
115
+ );
116
+ }
117
+
118
+ const normalizedName = normalizeName(name);
119
+ if (path[1] !== normalizedName) {
120
+ throw new Error(`path[1] must equal normalized name: path[1]=${JSON.stringify(path[1])}, name=${JSON.stringify(normalizedName)}`);
121
+ }
122
+
123
+ this._path = path;
124
+ this._subMetadata = subMetadata ?? {};
125
+ }
126
+
127
+ /**
128
+ * Returns the full derivation path of this SubHandle.
129
+ *
130
+ * @returns A copy of the path array, e.g. `["station-001", "connector-1"]`.
131
+ */
132
+ getPath(): string[] {
133
+ return [...this._path];
134
+ }
135
+
136
+ /**
137
+ * Returns the derivation path as a slash-separated string.
138
+ *
139
+ * @returns The path string, e.g. `"station-001/connector-1"`.
140
+ */
141
+ getPathString(): string {
142
+ return this._path.join('/');
143
+ }
144
+
145
+ /**
146
+ * Returns the depth of this SubHandle in the derivation hierarchy.
147
+ *
148
+ * With MAX_DEPTH = 2, this is always `2` (Identity = 0, Handle = 1, SubHandle = 2).
149
+ *
150
+ * @returns The depth, always `2`.
151
+ */
152
+ getDepth(): number {
153
+ return 2;
154
+ }
155
+
156
+ /**
157
+ * Returns whether this SubHandle is a leaf node.
158
+ *
159
+ * With MAX_DEPTH = 2, a SubHandle is **always** a leaf and cannot derive children.
160
+ *
161
+ * @returns Always `true`.
162
+ */
163
+ isLeaf(): boolean {
164
+ return true;
165
+ }
166
+
167
+ /**
168
+ * SubHandle is a leaf node (depth = 2) and cannot derive children.
169
+ * Overrides the inherited `Handle.deriveSubHandle` to throw an error.
170
+ */
171
+ override async deriveSubHandle(): Promise<never> {
172
+ throw new Error('Cannot derive child: maximum depth (2) reached or this SubHandle is marked as leaf');
173
+ }
174
+
175
+ /**
176
+ * Returns the SubHandle-specific metadata (constraints).
177
+ *
178
+ * @returns The SubHandleMetadata object.
179
+ */
180
+ getSubMetadata(): SubHandleMetadata {
181
+ return {
182
+ ...this._subMetadata,
183
+ allowedAudiences: this._subMetadata.allowedAudiences !== undefined
184
+ ? [...this._subMetadata.allowedAudiences]
185
+ : undefined,
186
+ allowedScopes: this._subMetadata.allowedScopes !== undefined
187
+ ? [...this._subMetadata.allowedScopes]
188
+ : undefined,
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Validates session options against this SubHandle's constraints.
194
+ *
195
+ * Called internally by {@link Session.create} before signing. Throws if
196
+ * any constraint is violated:
197
+ * - `audience` not in `allowedAudiences`
198
+ * - any `scope` not in `allowedScopes`
199
+ * - `ttl` exceeds `maxSessionTtl`
200
+ * - current time is past `expiresAt`
201
+ *
202
+ * @param options - The session options to validate.
203
+ * @throws {Error} If any constraint is violated.
204
+ */
205
+ validateSessionOptions(options: {
206
+ audience: string;
207
+ scopes: string[];
208
+ ttl: number;
209
+ }): void {
210
+ // Audience check: undefined = unrestricted, [] = deny all
211
+ if (this._subMetadata.allowedAudiences !== undefined) {
212
+ if (!this._subMetadata.allowedAudiences.includes(options.audience)) {
213
+ throw new Error(
214
+ `Audience "${options.audience}" not allowed for this SubHandle. ` +
215
+ `Allowed: ${this._subMetadata.allowedAudiences.length === 0
216
+ ? '(none — empty list denies all)'
217
+ : this._subMetadata.allowedAudiences.join(', ')}`
218
+ );
219
+ }
220
+ }
221
+
222
+ // Scopes check: undefined = unrestricted, [] = deny all
223
+ if (this._subMetadata.allowedScopes !== undefined) {
224
+ const forbidden = options.scopes.filter(
225
+ s => !this._subMetadata.allowedScopes!.includes(s)
226
+ );
227
+ // An empty allow-list denies every requested scope.
228
+ if (forbidden.length > 0) {
229
+ throw new Error(
230
+ `Scopes not allowed for this SubHandle: ${forbidden.join(', ')}`
231
+ );
232
+ }
233
+ }
234
+
235
+ // TTL check
236
+ if (
237
+ this._subMetadata.maxSessionTtl !== undefined &&
238
+ options.ttl > this._subMetadata.maxSessionTtl
239
+ ) {
240
+ throw new Error(
241
+ `TTL ${options.ttl}s exceeds max allowed ` +
242
+ `${this._subMetadata.maxSessionTtl}s for this SubHandle`
243
+ );
244
+ }
245
+
246
+ // SubHandle expiration check
247
+ if (this._subMetadata.expiresAt !== undefined) {
248
+ const now = Math.floor(Date.now() / 1000);
249
+ if (now >= this._subMetadata.expiresAt) {
250
+ throw new Error('SubHandle has expired');
251
+ }
252
+ }
253
+ }
254
+ }
package/src/util.ts ADDED
@@ -0,0 +1,35 @@
1
+ // util.ts
2
+ //
3
+ // Shared utility functions for the Me2em protocol.
4
+
5
+ /**
6
+ * Encodes a Uint8Array to a URL-safe Base64 string (no padding).
7
+ */
8
+ export function base64urlEncode(bytes: Uint8Array): string {
9
+ let binary = '';
10
+ for (const byte of bytes) {
11
+ binary += String.fromCharCode(byte);
12
+ }
13
+ return btoa(binary)
14
+ .replace(/\+/g, '-')
15
+ .replace(/\//g, '_')
16
+ .replace(/=+$/, '');
17
+ }
18
+
19
+ /**
20
+ * Decodes a URL-safe Base64 string to a Uint8Array.
21
+ */
22
+ export function base64urlDecode(input: string): Uint8Array {
23
+ let base64 = input
24
+ .replace(/-/g, '+')
25
+ .replace(/_/g, '/');
26
+ while (base64.length % 4 !== 0) {
27
+ base64 += '=';
28
+ }
29
+ const binary = atob(base64);
30
+ const bytes = new Uint8Array(binary.length);
31
+ for (let i = 0; i < binary.length; i++) {
32
+ bytes[i] = binary.charCodeAt(i);
33
+ }
34
+ return bytes;
35
+ }