@me2em/core 0.7.0-alpha.1 → 1.0.0-rc.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 (92) hide show
  1. package/README.md +242 -47
  2. package/dist/attestation.d.ts +26 -17
  3. package/dist/attestation.d.ts.map +1 -1
  4. package/dist/attestation.js +76 -29
  5. package/dist/attestation.js.map +1 -1
  6. package/dist/canonical-name.d.ts +18 -0
  7. package/dist/canonical-name.d.ts.map +1 -1
  8. package/dist/canonical-name.js +28 -1
  9. package/dist/canonical-name.js.map +1 -1
  10. package/dist/crypto/derivation-paths.d.ts +33 -2
  11. package/dist/crypto/derivation-paths.d.ts.map +1 -1
  12. package/dist/crypto/derivation-paths.js +33 -2
  13. package/dist/crypto/derivation-paths.js.map +1 -1
  14. package/dist/crypto/derivation.d.ts +47 -0
  15. package/dist/crypto/derivation.d.ts.map +1 -0
  16. package/dist/crypto/derivation.js +68 -0
  17. package/dist/crypto/derivation.js.map +1 -0
  18. package/dist/crypto/ecdh.d.ts +19 -0
  19. package/dist/crypto/ecdh.d.ts.map +1 -0
  20. package/dist/crypto/ecdh.js +33 -0
  21. package/dist/crypto/ecdh.js.map +1 -0
  22. package/dist/crypto/ed25519.d.ts +24 -3
  23. package/dist/crypto/ed25519.d.ts.map +1 -1
  24. package/dist/crypto/ed25519.js +39 -6
  25. package/dist/crypto/ed25519.js.map +1 -1
  26. package/dist/crypto/hkdf.d.ts +11 -2
  27. package/dist/crypto/hkdf.d.ts.map +1 -1
  28. package/dist/crypto/hkdf.js +13 -1
  29. package/dist/crypto/hkdf.js.map +1 -1
  30. package/dist/crypto/index.d.ts +25 -0
  31. package/dist/crypto/index.d.ts.map +1 -1
  32. package/dist/crypto/index.js +25 -0
  33. package/dist/crypto/index.js.map +1 -1
  34. package/dist/disposed-error.d.ts +24 -0
  35. package/dist/disposed-error.d.ts.map +1 -0
  36. package/dist/disposed-error.js +39 -0
  37. package/dist/disposed-error.js.map +1 -0
  38. package/dist/errors.d.ts +67 -0
  39. package/dist/errors.d.ts.map +1 -0
  40. package/dist/errors.js +54 -0
  41. package/dist/errors.js.map +1 -0
  42. package/dist/handle.d.ts +300 -14
  43. package/dist/handle.d.ts.map +1 -1
  44. package/dist/handle.js +463 -54
  45. package/dist/handle.js.map +1 -1
  46. package/dist/identity.d.ts +55 -11
  47. package/dist/identity.d.ts.map +1 -1
  48. package/dist/identity.js +105 -35
  49. package/dist/identity.js.map +1 -1
  50. package/dist/index.d.ts +10 -5
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +8 -4
  53. package/dist/index.js.map +1 -1
  54. package/dist/seed.d.ts +33 -22
  55. package/dist/seed.d.ts.map +1 -1
  56. package/dist/seed.js +59 -31
  57. package/dist/seed.js.map +1 -1
  58. package/dist/session.d.ts +42 -5
  59. package/dist/session.d.ts.map +1 -1
  60. package/dist/session.js +248 -117
  61. package/dist/session.js.map +1 -1
  62. package/dist/subhandle.d.ts +1 -125
  63. package/dist/subhandle.d.ts.map +1 -1
  64. package/dist/subhandle.js +12 -179
  65. package/dist/subhandle.js.map +1 -1
  66. package/dist/types.d.ts +22 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +6 -0
  69. package/dist/types.js.map +1 -0
  70. package/dist/util.d.ts +47 -0
  71. package/dist/util.d.ts.map +1 -1
  72. package/dist/util.js +72 -20
  73. package/dist/util.js.map +1 -1
  74. package/package.json +12 -5
  75. package/src/attestation.ts +88 -38
  76. package/src/canonical-name.ts +33 -1
  77. package/src/crypto/derivation-paths.ts +37 -2
  78. package/src/crypto/derivation.ts +90 -0
  79. package/src/crypto/ecdh.ts +37 -0
  80. package/src/crypto/ed25519.ts +39 -6
  81. package/src/crypto/hkdf.ts +13 -1
  82. package/src/crypto/index.ts +28 -1
  83. package/src/disposed-error.ts +45 -0
  84. package/src/errors.ts +88 -0
  85. package/src/handle.ts +630 -65
  86. package/src/identity.ts +111 -64
  87. package/src/index.ts +13 -7
  88. package/src/seed.ts +75 -32
  89. package/src/session.ts +336 -132
  90. package/src/subhandle.ts +12 -251
  91. package/src/types.ts +26 -0
  92. package/src/util.ts +78 -20
package/src/subhandle.ts CHANGED
@@ -1,254 +1,15 @@
1
1
  // subhandle.ts
2
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
- }
3
+ // Public import path for SubHandle. Since PR-10 (D4) the class pair
4
+ // `Handle`/`SubHandle` lives in `handle.ts`: `SubHandle extends Handle`,
5
+ // and a static cross-file import of the subclass would create an ESM
6
+ // module cycle that crashes at import time depending on the graph root
7
+ // (reproduced: "Cannot access 'Handle' before initialization"). The
8
+ // pre-PR-10 dynamic `import()` dodge is gone; co-location keeps the
9
+ // module graph acyclic and 100% static.
10
+ //
11
+ // This facade re-exports the class and its metadata type unchanged, so
12
+ // `import { SubHandle } from '@me2em/core'` and internal imports of
13
+ // `./subhandle.js` keep working exactly as before.
245
14
 
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
- }
15
+ export { SubHandle, type SubHandleMetadata } from './handle.js';
package/src/types.ts ADDED
@@ -0,0 +1,26 @@
1
+ // types.ts
2
+ //
3
+ // Cross-cutting public interfaces of @me2em/core that are not tied to a
4
+ // single class file (PLAN-LTS-v1 PR-6, task 1.2 / DR D2).
5
+
6
+ /**
7
+ * An object capable of producing Ed25519 signatures.
8
+ *
9
+ * The normative v1.0 issuance contract (specs/v1.0.md §8): raw private
10
+ * keys never cross a trust boundary as function arguments —
11
+ * `Attestation.issue` accepts a `Signer`, not key bytes. `Identity` and
12
+ * `Handle` implement this interface; custom implementations (e.g.
13
+ * remote- or HSM-backed signing) are accepted structurally — no
14
+ * inheritance from a base class is required.
15
+ *
16
+ * @category Types
17
+ */
18
+ export interface Signer {
19
+ /**
20
+ * Signs `data` with the signer's own private key.
21
+ *
22
+ * @param data - The bytes to sign.
23
+ * @returns A promise resolving to the 64-byte Ed25519 signature.
24
+ */
25
+ sign(data: Uint8Array): Promise<Uint8Array>;
26
+ }
package/src/util.ts CHANGED
@@ -1,35 +1,93 @@
1
1
  // util.ts
2
2
  //
3
- // Shared utility functions for the Me2em protocol.
3
+ // Shared utility functions for the Me2eM protocol.
4
+
5
+ import { base64urlnopad } from '@scure/base';
6
+
7
+ /**
8
+ * Node.js console/inspect hook (`util.inspect.custom`), referenced by
9
+ * `Symbol.for` so that no `node:util` import — and therefore no Node
10
+ * dependency — leaks into browser bundles. In non-Node runtimes the
11
+ * symbol simply has no meaning and the method is never called.
12
+ */
13
+ export const INSPECT_SYMBOL = Symbol.for('nodejs.util.inspect.custom');
4
14
 
5
15
  /**
6
16
  * Encodes a Uint8Array to a URL-safe Base64 string (no padding).
17
+ *
18
+ * Implemented on top of the audited `@scure/base` codec (A3) — a crypto
19
+ * library must not hand-roll its own base64 alphabet handling. The
20
+ * output is byte-identical to the previous hand-rolled encoder
21
+ * (unpadded URL-safe Base64), so token serialization does not change.
22
+ *
23
+ * @param bytes - The bytes to encode.
24
+ * @returns The unpadded URL-safe Base64 string (`''` for empty input).
7
25
  */
8
26
  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(/=+$/, '');
27
+ return base64urlnopad.encode(bytes);
17
28
  }
18
29
 
19
30
  /**
20
31
  * Decodes a URL-safe Base64 string to a Uint8Array.
32
+ *
33
+ * Implemented on top of the audited `@scure/base` codec (A3). Throws a
34
+ * generic `Error` on inputs with characters outside the URL-safe
35
+ * alphabet or an impossible length — token parsers wrap this call and
36
+ * translate failures into `AttestationError` `MALFORMED`/`FORMAT`.
37
+ *
38
+ * @param input - The unpadded URL-safe Base64 string.
39
+ * @returns The decoded bytes.
21
40
  */
22
41
  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);
42
+ return base64urlnopad.decode(input);
43
+ }
44
+
45
+ /**
46
+ * RFC 4122 version-4 UUID with a runtime-portability fallback (PR-7):
47
+ * uses `crypto.randomUUID` where available (Node ≥14.17, modern
48
+ * browsers) and otherwise builds the UUID from
49
+ * `crypto.getRandomValues` bytes with the version/variant bits set.
50
+ * Keeps `Attestation.issue` and `Session.create` working on runtimes
51
+ * without `randomUUID` (older React Native JS engines, non-secure
52
+ * browser contexts).
53
+ *
54
+ * @returns A random UUID in the canonical 8-4-4-4-12 hex form.
55
+ */
56
+ export function randomUUID(): string {
57
+ const c = globalThis.crypto;
58
+ if (typeof c?.randomUUID === 'function') {
59
+ return c.randomUUID();
33
60
  }
34
- return bytes;
61
+ const bytes = new Uint8Array(16);
62
+ c.getRandomValues(bytes);
63
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
64
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx
65
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0'));
66
+ return (
67
+ hex.slice(0, 4).join('') + '-' +
68
+ hex.slice(4, 6).join('') + '-' +
69
+ hex.slice(6, 8).join('') + '-' +
70
+ hex.slice(8, 10).join('') + '-' +
71
+ hex.slice(10, 16).join('')
72
+ );
73
+ }
74
+
75
+ /**
76
+ * `JSON.parse` hardened against prototype pollution (PR-7): parsing
77
+ * aborts when any key named `__proto__` appears in the payload, so a
78
+ * hostile token can never plant properties on `Object.prototype` —
79
+ * neither directly (the parse is aborted) nor via later spreads of the
80
+ * parsed value into fresh objects.
81
+ *
82
+ * @param input - The JSON text to parse.
83
+ * @returns The parsed value.
84
+ * @throws {SyntaxError} On invalid JSON or a forbidden `__proto__` key.
85
+ */
86
+ export function safeJsonParse(input: string): unknown {
87
+ return JSON.parse(input, (key: string, value: unknown) => {
88
+ if (key === '__proto__') {
89
+ throw new SyntaxError('payload contains the forbidden key "__proto__"');
90
+ }
91
+ return value;
92
+ });
35
93
  }