@invictus-group-ai/core 0.5.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Invictus AI (invictusai.com.br)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # @invictus-group-ai/core
2
+
3
+ > **You do not install this package directly.** It arrives as a dependency of `@invictus-group-ai/orchestra` and `@invictus-group-ai/hooks` — start there: `npm install -D @invictus-group-ai/orchestra @invictus-group-ai/hooks` in your repository root, then `npx invi init`. This page is for people integrating against the codec itself.
4
+
5
+ Shared library of the Invictus AI kit: schemas, append-only event log, HMAC-signed commit-trailer codec, manifest helpers, and pseudonymous developer IDs.
6
+
7
+ Pure library — no CLI, no hooks, no side effects at import time. `@invictus-group-ai/hooks` and `@invictus-group-ai/orchestra` build on it. Runtime dependencies: `zod` only; everything else uses Node built-ins (`node:crypto`, `node:zlib`, `node:fs`). Node >= 20, ESM only.
8
+
9
+ Status: pre-1.0 — released to npm from 0.5.0 (lockstep with `@invictus-group-ai/hooks` and `@invictus-group-ai/orchestra`). Release runbook: `PUBLISHING.md` at the monorepo root.
10
+
11
+ ## Modules
12
+
13
+ | Subpath | What it does |
14
+ |---|---|
15
+ | `@invictus-group-ai/core/types` | TypeScript contracts: `Manifest`, `FragmentMeta`, `EventLogEntry`, `TrailerPayload`, `HookInput`/`HookOutput` |
16
+ | `@invictus-group-ai/core/schemas` | zod schemas for all of the above + `parseManifest`, `parseFragmentMeta`, `parseEventLogEntry`, `parseTrailerPayload`, `parseHookInput`, `parseHookOutput` (throw `InvictusValidationError` with per-path issues) |
17
+ | `@invictus-group-ai/core/eventlog` | Append-only per-dev JSONL log with a per-dev hash chain |
18
+ | `@invictus-group-ai/core/trailer` | Commit-trailer codec: encode / decode / verify / extract |
19
+ | `@invictus-group-ai/core/cbor` | Minimal in-house CBOR codec (RFC 8949 subset) |
20
+ | `@invictus-group-ai/core/manifest` | `.invictus/manifest.json` read / validate / write + fragment sha256 verification |
21
+ | `@invictus-group-ai/core/devid` | Pseudonymous dev IDs derived from git email + client salt |
22
+
23
+ The root export (`@invictus-group-ai/core`) re-exports everything, including the canonical-JSON/sha256 helpers (`canonicalJson`, `sha256Hex`, `sha256Prefix`).
24
+
25
+ ## Event log (`.invictus/log/<devId>.jsonl`)
26
+
27
+ One JSON object per line, append-only, one file per developer:
28
+
29
+ ```jsonc
30
+ { "v": 1, "ts": 1783468800, "dev": "d_7f3a2b9c", "sid": "ab12",
31
+ "type": "session.start|session.end|task.commit|decision|checkpoint|verify|gate|hook.error|journal.note|req.event",
32
+ "data": { /* metrics, never content */ },
33
+ "h": "…", // first 12 hex of sha256(canonical JSON of the entry without h)
34
+ "prev": "…" } // previous entry's h by this dev, or null at the chain head
35
+ ```
36
+
37
+ `appendEvent(dir, devId, { sid, type, data, ts? })` computes `h`, links `prev`, validates before writing. `verifyChain(dir, devId)` recomputes every hash and prev-link and reports each problem with line number and reason: `hash-mismatch` (edited entry), `chain-broken` (deletion / insertion / reordering), `dev-mismatch`, `invalid-json`, `invalid-schema`.
38
+
39
+ Honest limitation: truncating the *tail* of the file is not detectable from the log alone — the external anchor is the trailer's `j`/`prev` fields living in immutable git history. There is no cross-process file locking; the design assumption is one writer per dev file (the dev's own machine).
40
+
41
+ ## Commit trailer codec
42
+
43
+ Wire format of the value after `Invictus: `:
44
+
45
+ ```
46
+ v1.<base64url(deflateRaw(cbor(payload)))>.<hmac-sha256-trunc16-hex>
47
+ ```
48
+
49
+ - Payload: the short-key aggregate metrics object from `ARCHITECTURE.md` §6 / observability research §3 (tokens, cost in integer cents, model mix, AI/human LoC, accepts/rejects, REQ IDs, journal hash link, per-dev chain link). No free text, no email/name/hostname — git history is immutable (LGPD art. 18).
50
+ - Budget: **≤ 350 bytes of CBOR before compression**; `encodeTrailer` throws `TrailerBudgetError` with the actual size and which fields to trim.
51
+ - MAC: HMAC-SHA256 over the UTF-8 string `v1.<base64url-body>` (version-bound), hex-truncated to 16 chars. Keys are per-dev, derived via `deriveDevHmacKey(clientMasterKey, devId)` — the platform can verify, devs cannot forge each other. Comparison is constant-time.
52
+ - `verifyTrailer` returns `{ valid, payload?, reason? }` and withholds the payload on `hmac-mismatch`; `decodeTrailer` decodes without verification (payload is untrusted).
53
+ - `extractTrailers(message)` regex-extracts every trailer from a commit message, including GitHub squash-merge messages that concatenate several commit messages (bulleted lines and CRLF tolerated). An absent trailer is a signal (the "untracked commit" metric), not an error.
54
+
55
+ ```ts
56
+ import { deriveDevHmacKey, formatTrailerLine, extractTrailers, verifyTrailer } from '@invictus-group-ai/core';
57
+
58
+ const key = deriveDevHmacKey(process.env.INVICTUS_MASTER_KEY!, 'd_7f3a2b9c');
59
+ const line = formatTrailerLine(payload, key); // "Invictus: v1.…"
60
+ const [value] = extractTrailers(commitMessage);
61
+ const result = value ? verifyTrailer(value, key) : { valid: false };
62
+ ```
63
+
64
+ ### CBOR subset
65
+
66
+ `cborEncode`/`cborDecode` implement exactly what the payload needs: integers (safe range, both signs), UTF-8 strings, arrays, string-keyed maps, `true`/`false`/`null`. Floats are rejected on purpose (money is integer cents) with a clear error, as are byte strings, tags, indefinite-length items, duplicate and `__proto__` map keys. Verified against the RFC 8949 appendix-A vectors.
67
+
68
+ ## Manifest
69
+
70
+ `readManifest(rootDir)` / `writeManifest(rootDir, manifest)` handle `.invictus/manifest.json` (schema v1, strict zod validation both ways). `verifyFragmentHashes(rootDir, manifest)` compares every installed fragment file against its recorded sha256 — the key for the three-way merge on `invi update` (`ok: false` + `actual: null` = missing file; differing `actual` = client-edited fragment).
71
+
72
+ ## Dev IDs
73
+
74
+ ```
75
+ devId = "d_" + sha256(`${clientSalt}:${trim(lowercase(gitEmail))}`).slice(0, 8)
76
+ ```
77
+
78
+ Deterministic, so hooks, kit, and platform agree without exchanging the email. The email is a pure input: never stored, returned, or logged. `hashGitEmail` produces the `gitEmailHash` manifest field (full sha256 of the normalized email). Erasure is honored by deleting the client-side salt/map, orphaning historical IDs.
79
+
80
+ ## Development
81
+
82
+ ```bash
83
+ npm install # at the monorepo root (workspaces)
84
+ npm test # vitest — unit tests incl. RFC 8949 vectors, HMAC tamper
85
+ # detection, squash-merge survival, chain-edit detection
86
+ npm run build # tsc → dist/
87
+ ```
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Canonical JSON + sha256 helpers.
3
+ *
4
+ * Canonical form: object keys sorted recursively, no whitespace, `undefined`
5
+ * object entries dropped. Deterministic across runtimes, so hashes computed
6
+ * here are stable contract values (event-log `h`/`prev`, trailer `j`).
7
+ */
8
+ /** Length of the sha256 hex prefix used in event-log `h`/`prev` and trailer `j`/`prev`. */
9
+ export declare const HASH_PREFIX_LENGTH = 12;
10
+ /**
11
+ * Serialize a JSON-compatible value deterministically.
12
+ * Throws TypeError on non-finite numbers, functions, symbols, bigints and
13
+ * `undefined` (top-level or inside arrays) — those have no canonical form.
14
+ */
15
+ export declare function canonicalJson(value: unknown): string;
16
+ /** Full sha256 as lowercase hex (64 chars). */
17
+ export declare function sha256Hex(data: string | Uint8Array): string;
18
+ /** First HASH_PREFIX_LENGTH (12) hex chars of sha256. */
19
+ export declare function sha256Prefix(data: string | Uint8Array): string;
20
+ //# sourceMappingURL=canonical.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical.d.ts","sourceRoot":"","sources":["../src/canonical.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,2FAA2F;AAC3F,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAErC;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CA4BpD;AAED,+CAA+C;AAC/C,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAE3D;AAED,yDAAyD;AACzD,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAE9D"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Canonical JSON + sha256 helpers.
3
+ *
4
+ * Canonical form: object keys sorted recursively, no whitespace, `undefined`
5
+ * object entries dropped. Deterministic across runtimes, so hashes computed
6
+ * here are stable contract values (event-log `h`/`prev`, trailer `j`).
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ /** Length of the sha256 hex prefix used in event-log `h`/`prev` and trailer `j`/`prev`. */
10
+ export const HASH_PREFIX_LENGTH = 12;
11
+ /**
12
+ * Serialize a JSON-compatible value deterministically.
13
+ * Throws TypeError on non-finite numbers, functions, symbols, bigints and
14
+ * `undefined` (top-level or inside arrays) — those have no canonical form.
15
+ */
16
+ export function canonicalJson(value) {
17
+ if (value === null)
18
+ return 'null';
19
+ switch (typeof value) {
20
+ case 'number':
21
+ if (!Number.isFinite(value)) {
22
+ throw new TypeError('canonicalJson: non-finite numbers are not allowed');
23
+ }
24
+ return JSON.stringify(value);
25
+ case 'boolean':
26
+ case 'string':
27
+ return JSON.stringify(value);
28
+ case 'object': {
29
+ if (Array.isArray(value)) {
30
+ return '[' + value.map((item) => canonicalJson(item)).join(',') + ']';
31
+ }
32
+ const record = value;
33
+ const keys = Object.keys(record)
34
+ .filter((k) => record[k] !== undefined)
35
+ .sort();
36
+ return ('{' +
37
+ keys.map((k) => JSON.stringify(k) + ':' + canonicalJson(record[k])).join(',') +
38
+ '}');
39
+ }
40
+ default:
41
+ throw new TypeError(`canonicalJson: unsupported value of type ${typeof value}`);
42
+ }
43
+ }
44
+ /** Full sha256 as lowercase hex (64 chars). */
45
+ export function sha256Hex(data) {
46
+ return createHash('sha256').update(data).digest('hex');
47
+ }
48
+ /** First HASH_PREFIX_LENGTH (12) hex chars of sha256. */
49
+ export function sha256Prefix(data) {
50
+ return sha256Hex(data).slice(0, HASH_PREFIX_LENGTH);
51
+ }
52
+ //# sourceMappingURL=canonical.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical.js","sourceRoot":"","sources":["../src/canonical.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,2FAA2F;AAC3F,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAErC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAClC,QAAQ,OAAO,KAAK,EAAE,CAAC;QACrB,KAAK,QAAQ;YACX,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC5B,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAC;YAC3E,CAAC;YACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QAC/B,KAAK,SAAS,CAAC;QACf,KAAK,QAAQ;YACX,OAAO,IAAI,CAAC,SAAS,CAA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R codec (RFC 8949 subset) — no external dependency.
3
+ *
4
+ * Covers exactly what the Invictus trailer payload needs:
5
+ * - unsigned & negative integers (up to Number.MAX_SAFE_INTEGER magnitude)
6
+ * - UTF-8 text strings
7
+ * - arrays
8
+ * - string-keyed maps
9
+ * - true / false / null
10
+ *
11
+ * Deliberately unsupported (throws CborError with a clear message):
12
+ * - floats — the payload uses integer cents/counters by design
13
+ * - byte strings, tags, indefinite-length items, undefined/simple values
14
+ */
15
+ export declare class CborError extends Error {
16
+ constructor(message: string);
17
+ }
18
+ export declare function cborEncode(value: unknown): Buffer;
19
+ export declare function cborDecode(data: Buffer | Uint8Array): unknown;
20
+ //# sourceMappingURL=cbor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cbor.d.ts","sourceRoot":"","sources":["../src/cbor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM;CAI5B;AAeD,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAIjD;AAoGD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,OAAO,CAU7D"}
package/dist/cbor.js ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Minimal CBOR codec (RFC 8949 subset) — no external dependency.
3
+ *
4
+ * Covers exactly what the Invictus trailer payload needs:
5
+ * - unsigned & negative integers (up to Number.MAX_SAFE_INTEGER magnitude)
6
+ * - UTF-8 text strings
7
+ * - arrays
8
+ * - string-keyed maps
9
+ * - true / false / null
10
+ *
11
+ * Deliberately unsupported (throws CborError with a clear message):
12
+ * - floats — the payload uses integer cents/counters by design
13
+ * - byte strings, tags, indefinite-length items, undefined/simple values
14
+ */
15
+ export class CborError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = 'CborError';
19
+ }
20
+ }
21
+ const MAJOR_UNSIGNED = 0;
22
+ const MAJOR_NEGATIVE = 1;
23
+ const MAJOR_BYTES = 2;
24
+ const MAJOR_TEXT = 3;
25
+ const MAJOR_ARRAY = 4;
26
+ const MAJOR_MAP = 5;
27
+ const MAJOR_TAG = 6;
28
+ const MAJOR_SIMPLE = 7;
29
+ // ---------------------------------------------------------------------------
30
+ // Encoding
31
+ // ---------------------------------------------------------------------------
32
+ export function cborEncode(value) {
33
+ const chunks = [];
34
+ encodeValue(value, chunks);
35
+ return Buffer.concat(chunks);
36
+ }
37
+ function encodeValue(value, chunks) {
38
+ if (value === null) {
39
+ chunks.push(Buffer.from([0xf6]));
40
+ return;
41
+ }
42
+ if (value === true) {
43
+ chunks.push(Buffer.from([0xf5]));
44
+ return;
45
+ }
46
+ if (value === false) {
47
+ chunks.push(Buffer.from([0xf4]));
48
+ return;
49
+ }
50
+ switch (typeof value) {
51
+ case 'number': {
52
+ if (!Number.isInteger(value)) {
53
+ throw new CborError(`floats are not supported (got ${value}) — encode money as integer cents and durations as integer seconds`);
54
+ }
55
+ if (!Number.isSafeInteger(value)) {
56
+ throw new CborError(`integer out of safe range: ${value}`);
57
+ }
58
+ if (value >= 0) {
59
+ encodeTypeAndArgument(MAJOR_UNSIGNED, value, chunks);
60
+ }
61
+ else {
62
+ encodeTypeAndArgument(MAJOR_NEGATIVE, -1 - value, chunks);
63
+ }
64
+ return;
65
+ }
66
+ case 'string': {
67
+ const bytes = Buffer.from(value, 'utf8');
68
+ encodeTypeAndArgument(MAJOR_TEXT, bytes.length, chunks);
69
+ chunks.push(bytes);
70
+ return;
71
+ }
72
+ case 'object': {
73
+ if (Array.isArray(value)) {
74
+ encodeTypeAndArgument(MAJOR_ARRAY, value.length, chunks);
75
+ for (const item of value) {
76
+ if (item === undefined) {
77
+ throw new CborError('undefined array elements are not supported');
78
+ }
79
+ encodeValue(item, chunks);
80
+ }
81
+ return;
82
+ }
83
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined);
84
+ encodeTypeAndArgument(MAJOR_MAP, entries.length, chunks);
85
+ for (const [key, v] of entries) {
86
+ const keyBytes = Buffer.from(key, 'utf8');
87
+ encodeTypeAndArgument(MAJOR_TEXT, keyBytes.length, chunks);
88
+ chunks.push(keyBytes);
89
+ encodeValue(v, chunks);
90
+ }
91
+ return;
92
+ }
93
+ default:
94
+ throw new CborError(`unsupported value of type ${typeof value}`);
95
+ }
96
+ }
97
+ /** Write the initial byte(s): major type + argument (length or int value). */
98
+ function encodeTypeAndArgument(major, argument, chunks) {
99
+ const mt = major << 5;
100
+ if (argument < 24) {
101
+ chunks.push(Buffer.from([mt | argument]));
102
+ }
103
+ else if (argument < 0x100) {
104
+ chunks.push(Buffer.from([mt | 24, argument]));
105
+ }
106
+ else if (argument < 0x10000) {
107
+ const buf = Buffer.allocUnsafe(3);
108
+ buf[0] = mt | 25;
109
+ buf.writeUInt16BE(argument, 1);
110
+ chunks.push(buf);
111
+ }
112
+ else if (argument < 0x1_0000_0000) {
113
+ const buf = Buffer.allocUnsafe(5);
114
+ buf[0] = mt | 26;
115
+ buf.writeUInt32BE(argument, 1);
116
+ chunks.push(buf);
117
+ }
118
+ else {
119
+ const buf = Buffer.allocUnsafe(9);
120
+ buf[0] = mt | 27;
121
+ buf.writeBigUInt64BE(BigInt(argument), 1);
122
+ chunks.push(buf);
123
+ }
124
+ }
125
+ export function cborDecode(data) {
126
+ const state = {
127
+ buf: Buffer.isBuffer(data) ? data : Buffer.from(data),
128
+ pos: 0,
129
+ };
130
+ const value = decodeValue(state);
131
+ if (state.pos !== state.buf.length) {
132
+ throw new CborError(`trailing bytes after CBOR value (at offset ${state.pos})`);
133
+ }
134
+ return value;
135
+ }
136
+ function decodeValue(state) {
137
+ const initial = readByte(state);
138
+ const major = initial >> 5;
139
+ const additional = initial & 0x1f;
140
+ switch (major) {
141
+ case MAJOR_UNSIGNED:
142
+ return readArgument(state, additional);
143
+ case MAJOR_NEGATIVE:
144
+ return -1 - readArgument(state, additional);
145
+ case MAJOR_BYTES:
146
+ throw new CborError('byte strings are not supported by this codec');
147
+ case MAJOR_TEXT: {
148
+ const length = readArgument(state, additional);
149
+ return readBytes(state, length).toString('utf8');
150
+ }
151
+ case MAJOR_ARRAY: {
152
+ const length = readArgument(state, additional);
153
+ const arr = [];
154
+ for (let i = 0; i < length; i++)
155
+ arr.push(decodeValue(state));
156
+ return arr;
157
+ }
158
+ case MAJOR_MAP: {
159
+ const length = readArgument(state, additional);
160
+ const obj = {};
161
+ for (let i = 0; i < length; i++) {
162
+ const key = decodeValue(state);
163
+ if (typeof key !== 'string') {
164
+ throw new CborError('only string map keys are supported');
165
+ }
166
+ if (key === '__proto__') {
167
+ throw new CborError('forbidden map key: __proto__');
168
+ }
169
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
170
+ throw new CborError(`duplicate map key: ${JSON.stringify(key)}`);
171
+ }
172
+ obj[key] = decodeValue(state);
173
+ }
174
+ return obj;
175
+ }
176
+ case MAJOR_TAG:
177
+ throw new CborError('tags are not supported by this codec');
178
+ case MAJOR_SIMPLE: {
179
+ if (additional === 20)
180
+ return false;
181
+ if (additional === 21)
182
+ return true;
183
+ if (additional === 22)
184
+ return null;
185
+ if (additional === 25 || additional === 26 || additional === 27) {
186
+ throw new CborError('floats are not supported by this codec — use integers');
187
+ }
188
+ throw new CborError(`unsupported simple value (additional info ${additional})`);
189
+ }
190
+ default:
191
+ // unreachable: major is 3 bits
192
+ throw new CborError(`unsupported major type ${major}`);
193
+ }
194
+ }
195
+ /** Read the argument (int value or length) for the given additional-info bits. */
196
+ function readArgument(state, additional) {
197
+ if (additional < 24)
198
+ return additional;
199
+ if (additional === 24)
200
+ return readByte(state);
201
+ if (additional === 25) {
202
+ const buf = readBytes(state, 2);
203
+ return buf.readUInt16BE(0);
204
+ }
205
+ if (additional === 26) {
206
+ const buf = readBytes(state, 4);
207
+ return buf.readUInt32BE(0);
208
+ }
209
+ if (additional === 27) {
210
+ const buf = readBytes(state, 8);
211
+ const big = buf.readBigUInt64BE(0);
212
+ if (big > BigInt(Number.MAX_SAFE_INTEGER)) {
213
+ throw new CborError(`integer out of safe range: ${big}`);
214
+ }
215
+ return Number(big);
216
+ }
217
+ if (additional === 31) {
218
+ throw new CborError('indefinite-length items are not supported');
219
+ }
220
+ throw new CborError(`reserved additional info ${additional}`);
221
+ }
222
+ function readByte(state) {
223
+ if (state.pos >= state.buf.length) {
224
+ throw new CborError('unexpected end of CBOR data');
225
+ }
226
+ return state.buf[state.pos++];
227
+ }
228
+ function readBytes(state, length) {
229
+ if (state.pos + length > state.buf.length) {
230
+ throw new CborError('unexpected end of CBOR data');
231
+ }
232
+ const slice = state.buf.subarray(state.pos, state.pos + length);
233
+ state.pos += length;
234
+ return slice;
235
+ }
236
+ //# sourceMappingURL=cbor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cbor.js","sourceRoot":"","sources":["../src/cbor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;IAC1B,CAAC;CACF;AAED,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,8EAA8E;AAC9E,WAAW;AACX,8EAA8E;AAE9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC3B,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,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,IAAI,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,SAAS,CAAC,8BAA8B,GAAG,EAAE,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,IAAI,UAAU,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,SAAS,CAAC,2CAA2C,CAAC,CAAC;IACnE,CAAC;IACD,MAAM,IAAI,SAAS,CAAC,4BAA4B,UAAU,EAAE,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAkB;IAClC,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAClC,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,CAAE,CAAC;AACjC,CAAC;AAED,SAAS,SAAS,CAAC,KAAkB,EAAE,MAAc;IACnD,IAAI,KAAK,CAAC,GAAG,GAAG,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAC1C,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAC;IACrD,CAAC;IACD,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;IAChE,KAAK,CAAC,GAAG,IAAI,MAAM,CAAC;IACpB,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Pseudonymous developer IDs (ARCHITECTURE §1 tenet 5, §3 `devs[]`).
3
+ *
4
+ * `d_` + first 8 hex chars of sha256(`<clientSalt>:<normalized git email>`).
5
+ *
6
+ * The email is a pure input — it is never stored, returned, or logged by
7
+ * this module. The email↔id map (when a client needs one) stays client-side.
8
+ * Anything entering git history is immutable, so only the pseudonymous ID
9
+ * may ever appear in trailers or logs (LGPD art. 18 — right to erasure is
10
+ * honored by deleting the client-side salt/map, orphaning historical IDs).
11
+ */
12
+ import type { DevId } from './types.js';
13
+ /** Trim + lowercase. Throws on empty input. */
14
+ export declare function normalizeGitEmail(gitEmail: string): string;
15
+ /**
16
+ * Derive the pseudonymous dev ID. Deterministic: the same (salt, email)
17
+ * pair always yields the same ID, so hooks, kit, and platform agree without
18
+ * ever exchanging the email.
19
+ *
20
+ * The salt is per-client and secret-ish: without it, the 8-hex ID cannot be
21
+ * brute-forced back to an email from git history alone.
22
+ */
23
+ export declare function deriveDevId(clientSalt: string, gitEmail: string): DevId;
24
+ /**
25
+ * Fixed HKDF `info` string for {@link deriveClientSalt}. Version-tagged so a
26
+ * future derivation change cannot silently collide with v1 salts.
27
+ */
28
+ export declare const CLIENT_SALT_HKDF_INFO = "invictus-client-salt-v1";
29
+ /**
30
+ * Derive the CLIENT-STABLE dev-id salt from the platform-issued master key
31
+ * (docs/PLATFORM-API.md §"stable dev IDs"): HKDF-SHA256 with a zero-length
32
+ * extract salt (RFC 5869 default) and the fixed info string
33
+ * {@link CLIENT_SALT_HKDF_INFO}, 32-byte output, hex-encoded.
34
+ *
35
+ * Deterministic: every machine provisioned with the same master key derives
36
+ * the same salt, hence `deriveDevId(salt, email)` yields the same
37
+ * pseudonymous ID for the same git email everywhere. The LGPD posture is
38
+ * unchanged — the salt (like the master-key-derived HMAC keys) stays
39
+ * client-side, and erasure is still "delete the local salt/map".
40
+ *
41
+ * The output is NOT the master key and cannot be inverted to it (HKDF), but
42
+ * it is derived 1:1 from it — treat it with the same care as the dev HMAC
43
+ * keys (gitignored `.invictus/local/`, never committed, never logged).
44
+ */
45
+ export declare function deriveClientSalt(masterKeyHex: string): string;
46
+ /**
47
+ * Full sha256 hex of the normalized email — the `gitEmailHash` field of
48
+ * `manifest.devs[]` (§3). Used client-side to re-associate a git identity
49
+ * with its dev ID without storing the email in the manifest.
50
+ */
51
+ export declare function hashGitEmail(gitEmail: string): string;
52
+ /** Type guard for the `d_xxxxxxxx` format. */
53
+ export declare function isDevId(value: string): value is DevId;
54
+ //# sourceMappingURL=devid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devid.d.ts","sourceRoot":"","sources":["../src/devid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,+CAA+C;AAC/C,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAM1D;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,KAAK,CAMvE;AAED;;;GAGG;AACH,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAI/D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAS7D;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,8CAA8C;AAC9C,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,KAAK,CAErD"}
package/dist/devid.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pseudonymous developer IDs (ARCHITECTURE §1 tenet 5, §3 `devs[]`).
3
+ *
4
+ * `d_` + first 8 hex chars of sha256(`<clientSalt>:<normalized git email>`).
5
+ *
6
+ * The email is a pure input — it is never stored, returned, or logged by
7
+ * this module. The email↔id map (when a client needs one) stays client-side.
8
+ * Anything entering git history is immutable, so only the pseudonymous ID
9
+ * may ever appear in trailers or logs (LGPD art. 18 — right to erasure is
10
+ * honored by deleting the client-side salt/map, orphaning historical IDs).
11
+ */
12
+ import { hkdfSync } from 'node:crypto';
13
+ import { sha256Hex } from './canonical.js';
14
+ import { DEV_ID_RE } from './schemas.js';
15
+ /** Trim + lowercase. Throws on empty input. */
16
+ export function normalizeGitEmail(gitEmail) {
17
+ const normalized = gitEmail.trim().toLowerCase();
18
+ if (normalized.length === 0) {
19
+ throw new TypeError('git email must not be empty');
20
+ }
21
+ return normalized;
22
+ }
23
+ /**
24
+ * Derive the pseudonymous dev ID. Deterministic: the same (salt, email)
25
+ * pair always yields the same ID, so hooks, kit, and platform agree without
26
+ * ever exchanging the email.
27
+ *
28
+ * The salt is per-client and secret-ish: without it, the 8-hex ID cannot be
29
+ * brute-forced back to an email from git history alone.
30
+ */
31
+ export function deriveDevId(clientSalt, gitEmail) {
32
+ if (clientSalt.length === 0) {
33
+ throw new TypeError('clientSalt must not be empty — dev ids must not be derivable from the email alone');
34
+ }
35
+ const digest = sha256Hex(`${clientSalt}:${normalizeGitEmail(gitEmail)}`);
36
+ return `d_${digest.slice(0, 8)}`;
37
+ }
38
+ /**
39
+ * Fixed HKDF `info` string for {@link deriveClientSalt}. Version-tagged so a
40
+ * future derivation change cannot silently collide with v1 salts.
41
+ */
42
+ export const CLIENT_SALT_HKDF_INFO = 'invictus-client-salt-v1';
43
+ const MASTER_KEY_HEX_RE = /^[0-9a-f]{64}$/;
44
+ /**
45
+ * Derive the CLIENT-STABLE dev-id salt from the platform-issued master key
46
+ * (docs/PLATFORM-API.md §"stable dev IDs"): HKDF-SHA256 with a zero-length
47
+ * extract salt (RFC 5869 default) and the fixed info string
48
+ * {@link CLIENT_SALT_HKDF_INFO}, 32-byte output, hex-encoded.
49
+ *
50
+ * Deterministic: every machine provisioned with the same master key derives
51
+ * the same salt, hence `deriveDevId(salt, email)` yields the same
52
+ * pseudonymous ID for the same git email everywhere. The LGPD posture is
53
+ * unchanged — the salt (like the master-key-derived HMAC keys) stays
54
+ * client-side, and erasure is still "delete the local salt/map".
55
+ *
56
+ * The output is NOT the master key and cannot be inverted to it (HKDF), but
57
+ * it is derived 1:1 from it — treat it with the same care as the dev HMAC
58
+ * keys (gitignored `.invictus/local/`, never committed, never logged).
59
+ */
60
+ export function deriveClientSalt(masterKeyHex) {
61
+ const normalized = masterKeyHex.trim().toLowerCase();
62
+ if (!MASTER_KEY_HEX_RE.test(normalized)) {
63
+ throw new TypeError('deriveClientSalt: masterKeyHex must be the 64-hex-char (32-byte) client master key');
64
+ }
65
+ const okm = hkdfSync('sha256', Buffer.from(normalized, 'hex'), Buffer.alloc(0), CLIENT_SALT_HKDF_INFO, 32);
66
+ return Buffer.from(okm).toString('hex');
67
+ }
68
+ /**
69
+ * Full sha256 hex of the normalized email — the `gitEmailHash` field of
70
+ * `manifest.devs[]` (§3). Used client-side to re-associate a git identity
71
+ * with its dev ID without storing the email in the manifest.
72
+ */
73
+ export function hashGitEmail(gitEmail) {
74
+ return sha256Hex(normalizeGitEmail(gitEmail));
75
+ }
76
+ /** Type guard for the `d_xxxxxxxx` format. */
77
+ export function isDevId(value) {
78
+ return DEV_ID_RE.test(value);
79
+ }
80
+ //# sourceMappingURL=devid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devid.js","sourceRoot":"","sources":["../src/devid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,+CAA+C;AAC/C,MAAM,UAAU,iBAAiB,CAAC,QAAgB;IAChD,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACjD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB,EAAE,QAAgB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