@dxos/keys 0.5.8 → 0.5.9-main.2d0a5e6
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/dist/lib/browser/index.mjs +219 -10
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +207 -11
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/public-key.d.ts +3 -0
- package/dist/types/src/public-key.d.ts.map +1 -1
- package/dist/types/src/random-bytes.d.ts +2 -0
- package/dist/types/src/random-bytes.d.ts.map +1 -0
- package/dist/types/src/space-id.d.ts +16 -0
- package/dist/types/src/space-id.d.ts.map +1 -0
- package/dist/types/src/space-id.test.d.ts +2 -0
- package/dist/types/src/space-id.test.d.ts.map +1 -0
- package/dist/types/src/types.d.ts.map +1 -1
- package/package.json +8 -4
- package/src/index.ts +1 -0
- package/src/public-key.test.ts +7 -0
- package/src/public-key.ts +18 -10
- package/src/random-bytes.ts +13 -0
- package/src/space-id.test.ts +17 -0
- package/src/space-id.ts +45 -0
- package/src/types.ts +0 -1
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
1
7
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
8
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
9
|
}) : x)(function(x) {
|
|
@@ -5,11 +11,152 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
5
11
|
return require.apply(this, arguments);
|
|
6
12
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
7
13
|
});
|
|
14
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
15
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
16
|
+
};
|
|
17
|
+
var __copyProps = (to, from, except, desc) => {
|
|
18
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
19
|
+
for (let key of __getOwnPropNames(from))
|
|
20
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
21
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
22
|
+
}
|
|
23
|
+
return to;
|
|
24
|
+
};
|
|
25
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
26
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
27
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
28
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
29
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
30
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
31
|
+
mod
|
|
32
|
+
));
|
|
33
|
+
|
|
34
|
+
// node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js
|
|
35
|
+
var require_base32_decode = __commonJS({
|
|
36
|
+
"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js"(exports, module) {
|
|
37
|
+
var RFC46482 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
38
|
+
var RFC4648_HEX2 = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
|
39
|
+
var CROCKFORD2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
40
|
+
function readChar(alphabet, char) {
|
|
41
|
+
var idx = alphabet.indexOf(char);
|
|
42
|
+
if (idx === -1) {
|
|
43
|
+
throw new Error("Invalid character found: " + char);
|
|
44
|
+
}
|
|
45
|
+
return idx;
|
|
46
|
+
}
|
|
47
|
+
module.exports = function base32Decode3(input, variant) {
|
|
48
|
+
var alphabet;
|
|
49
|
+
switch (variant) {
|
|
50
|
+
case "RFC3548":
|
|
51
|
+
case "RFC4648":
|
|
52
|
+
alphabet = RFC46482;
|
|
53
|
+
input = input.replace(/=+$/, "");
|
|
54
|
+
break;
|
|
55
|
+
case "RFC4648-HEX":
|
|
56
|
+
alphabet = RFC4648_HEX2;
|
|
57
|
+
input = input.replace(/=+$/, "");
|
|
58
|
+
break;
|
|
59
|
+
case "Crockford":
|
|
60
|
+
alphabet = CROCKFORD2;
|
|
61
|
+
input = input.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1");
|
|
62
|
+
break;
|
|
63
|
+
default:
|
|
64
|
+
throw new Error("Unknown base32 variant: " + variant);
|
|
65
|
+
}
|
|
66
|
+
var length = input.length;
|
|
67
|
+
var bits = 0;
|
|
68
|
+
var value = 0;
|
|
69
|
+
var index = 0;
|
|
70
|
+
var output = new Uint8Array(length * 5 / 8 | 0);
|
|
71
|
+
for (var i = 0; i < length; i++) {
|
|
72
|
+
value = value << 5 | readChar(alphabet, input[i]);
|
|
73
|
+
bits += 5;
|
|
74
|
+
if (bits >= 8) {
|
|
75
|
+
output[index++] = value >>> bits - 8 & 255;
|
|
76
|
+
bits -= 8;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return output.buffer;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// packages/common/keys/src/public-key.ts
|
|
85
|
+
var import_base32_decode = __toESM(require_base32_decode());
|
|
86
|
+
|
|
87
|
+
// node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js
|
|
88
|
+
function toDataView(data) {
|
|
89
|
+
if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
|
|
90
|
+
return new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
91
|
+
}
|
|
92
|
+
if (data instanceof ArrayBuffer) {
|
|
93
|
+
return new DataView(data);
|
|
94
|
+
}
|
|
95
|
+
throw new TypeError("Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js
|
|
99
|
+
var RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
100
|
+
var RFC4648_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
|
101
|
+
var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
102
|
+
function base32Encode(data, variant, options) {
|
|
103
|
+
options = options || {};
|
|
104
|
+
let alphabet, defaultPadding;
|
|
105
|
+
switch (variant) {
|
|
106
|
+
case "RFC3548":
|
|
107
|
+
case "RFC4648":
|
|
108
|
+
alphabet = RFC4648;
|
|
109
|
+
defaultPadding = true;
|
|
110
|
+
break;
|
|
111
|
+
case "RFC4648-HEX":
|
|
112
|
+
alphabet = RFC4648_HEX;
|
|
113
|
+
defaultPadding = true;
|
|
114
|
+
break;
|
|
115
|
+
case "Crockford":
|
|
116
|
+
alphabet = CROCKFORD;
|
|
117
|
+
defaultPadding = false;
|
|
118
|
+
break;
|
|
119
|
+
default:
|
|
120
|
+
throw new Error("Unknown base32 variant: " + variant);
|
|
121
|
+
}
|
|
122
|
+
const padding = options.padding !== void 0 ? options.padding : defaultPadding;
|
|
123
|
+
const view = toDataView(data);
|
|
124
|
+
let bits = 0;
|
|
125
|
+
let value = 0;
|
|
126
|
+
let output = "";
|
|
127
|
+
for (let i = 0; i < view.byteLength; i++) {
|
|
128
|
+
value = value << 8 | view.getUint8(i);
|
|
129
|
+
bits += 8;
|
|
130
|
+
while (bits >= 5) {
|
|
131
|
+
output += alphabet[value >>> bits - 5 & 31];
|
|
132
|
+
bits -= 5;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (bits > 0) {
|
|
136
|
+
output += alphabet[value << 5 - bits & 31];
|
|
137
|
+
}
|
|
138
|
+
if (padding) {
|
|
139
|
+
while (output.length % 8 !== 0) {
|
|
140
|
+
output += "=";
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return output;
|
|
144
|
+
}
|
|
8
145
|
|
|
9
146
|
// packages/common/keys/src/public-key.ts
|
|
10
147
|
import { inspect } from "@dxos/node-std/util";
|
|
11
148
|
import { truncateKey, devtoolsFormatter, equalsSymbol } from "@dxos/debug";
|
|
12
149
|
import { invariant } from "@dxos/invariant";
|
|
150
|
+
|
|
151
|
+
// packages/common/keys/src/random-bytes.ts
|
|
152
|
+
var randomBytes = (length) => {
|
|
153
|
+
const webCrypto = globalThis.crypto ?? __require("@dxos/node-std/crypto").webcrypto;
|
|
154
|
+
const bytes = new Uint8Array(length);
|
|
155
|
+
webCrypto.getRandomValues(bytes);
|
|
156
|
+
return bytes;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// packages/common/keys/src/public-key.ts
|
|
13
160
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
|
|
14
161
|
var PUBLIC_KEY_LENGTH = 32;
|
|
15
162
|
var SECRET_KEY_LENGTH = 64;
|
|
@@ -22,7 +169,7 @@ var PublicKey = class _PublicKey {
|
|
|
22
169
|
static from(source) {
|
|
23
170
|
invariant(source, void 0, {
|
|
24
171
|
F: __dxlog_file,
|
|
25
|
-
L:
|
|
172
|
+
L: 34,
|
|
26
173
|
S: this,
|
|
27
174
|
A: [
|
|
28
175
|
"source",
|
|
@@ -77,6 +224,9 @@ var PublicKey = class _PublicKey {
|
|
|
77
224
|
static random() {
|
|
78
225
|
return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
79
226
|
}
|
|
227
|
+
static randomOfLength(length) {
|
|
228
|
+
return _PublicKey.from(randomBytes(length));
|
|
229
|
+
}
|
|
80
230
|
static *randomSequence() {
|
|
81
231
|
for (let i = 0; i < 1e4; i++) {
|
|
82
232
|
yield _PublicKey.random();
|
|
@@ -111,7 +261,7 @@ var PublicKey = class _PublicKey {
|
|
|
111
261
|
static bufferize(str) {
|
|
112
262
|
invariant(typeof str === "string", "Invalid type", {
|
|
113
263
|
F: __dxlog_file,
|
|
114
|
-
L:
|
|
264
|
+
L: 137,
|
|
115
265
|
S: this,
|
|
116
266
|
A: [
|
|
117
267
|
"typeof str === 'string'",
|
|
@@ -134,7 +284,7 @@ var PublicKey = class _PublicKey {
|
|
|
134
284
|
}
|
|
135
285
|
invariant(key instanceof Buffer, "Invalid type", {
|
|
136
286
|
F: __dxlog_file,
|
|
137
|
-
L:
|
|
287
|
+
L: 156,
|
|
138
288
|
S: this,
|
|
139
289
|
A: [
|
|
140
290
|
"key instanceof Buffer",
|
|
@@ -150,6 +300,18 @@ var PublicKey = class _PublicKey {
|
|
|
150
300
|
static hash(key) {
|
|
151
301
|
return key.toHex();
|
|
152
302
|
}
|
|
303
|
+
static fromMultibase32(encoded) {
|
|
304
|
+
invariant(encoded.startsWith("B"), "Invalid multibase32 encoding", {
|
|
305
|
+
F: __dxlog_file,
|
|
306
|
+
L: 169,
|
|
307
|
+
S: this,
|
|
308
|
+
A: [
|
|
309
|
+
"encoded.startsWith('B')",
|
|
310
|
+
"'Invalid multibase32 encoding'"
|
|
311
|
+
]
|
|
312
|
+
});
|
|
313
|
+
return new _PublicKey(new Uint8Array((0, import_base32_decode.default)(encoded.slice(1), "RFC4648")));
|
|
314
|
+
}
|
|
153
315
|
constructor(_value) {
|
|
154
316
|
this._value = _value;
|
|
155
317
|
if (!(_value instanceof Uint8Array)) {
|
|
@@ -171,6 +333,9 @@ var PublicKey = class _PublicKey {
|
|
|
171
333
|
toHex() {
|
|
172
334
|
return this.asBuffer().toString("hex");
|
|
173
335
|
}
|
|
336
|
+
toMultibase32() {
|
|
337
|
+
return "B" + base32Encode(this._value, "RFC4648");
|
|
338
|
+
}
|
|
174
339
|
truncate(length = void 0) {
|
|
175
340
|
return truncateKey(this, length);
|
|
176
341
|
}
|
|
@@ -275,15 +440,59 @@ var PublicKey = class _PublicKey {
|
|
|
275
440
|
return this.equals(other);
|
|
276
441
|
}
|
|
277
442
|
};
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
443
|
+
|
|
444
|
+
// packages/common/keys/src/space-id.ts
|
|
445
|
+
var import_base32_decode2 = __toESM(require_base32_decode());
|
|
446
|
+
import { invariant as invariant2 } from "@dxos/invariant";
|
|
447
|
+
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/keys/src/space-id.ts";
|
|
448
|
+
var SpaceId = Object.freeze({
|
|
449
|
+
byteLength: 20,
|
|
450
|
+
encode: (value) => {
|
|
451
|
+
invariant2(value instanceof Uint8Array, "Invalid type", {
|
|
452
|
+
F: __dxlog_file2,
|
|
453
|
+
L: 22,
|
|
454
|
+
S: void 0,
|
|
455
|
+
A: [
|
|
456
|
+
"value instanceof Uint8Array",
|
|
457
|
+
"'Invalid type'"
|
|
458
|
+
]
|
|
459
|
+
});
|
|
460
|
+
invariant2(value.length === SpaceId.byteLength, "Invalid length", {
|
|
461
|
+
F: __dxlog_file2,
|
|
462
|
+
L: 23,
|
|
463
|
+
S: void 0,
|
|
464
|
+
A: [
|
|
465
|
+
"value.length === SpaceId.byteLength",
|
|
466
|
+
"'Invalid length'"
|
|
467
|
+
]
|
|
468
|
+
});
|
|
469
|
+
return MULTIBASE_PREFIX + base32Encode(value, "RFC4648");
|
|
470
|
+
},
|
|
471
|
+
decode: (value) => {
|
|
472
|
+
invariant2(value.startsWith(MULTIBASE_PREFIX), "Invalid multibase32 encoding", {
|
|
473
|
+
F: __dxlog_file2,
|
|
474
|
+
L: 28,
|
|
475
|
+
S: void 0,
|
|
476
|
+
A: [
|
|
477
|
+
"value.startsWith(MULTIBASE_PREFIX)",
|
|
478
|
+
"'Invalid multibase32 encoding'"
|
|
479
|
+
]
|
|
480
|
+
});
|
|
481
|
+
return new Uint8Array((0, import_base32_decode2.default)(value.slice(1), "RFC4648"));
|
|
482
|
+
},
|
|
483
|
+
isValid: (value) => {
|
|
484
|
+
return typeof value === "string" && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;
|
|
485
|
+
},
|
|
486
|
+
random: () => {
|
|
487
|
+
return SpaceId.encode(randomBytes(SpaceId.byteLength));
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
var MULTIBASE_PREFIX = "B";
|
|
491
|
+
var ENCODED_LENGTH = 33;
|
|
284
492
|
export {
|
|
285
493
|
PUBLIC_KEY_LENGTH,
|
|
286
494
|
PublicKey,
|
|
287
|
-
SECRET_KEY_LENGTH
|
|
495
|
+
SECRET_KEY_LENGTH,
|
|
496
|
+
SpaceId
|
|
288
497
|
};
|
|
289
498
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/public-key.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n\nconst randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["inspect", "truncateKey", "devtoolsFormatter", "equalsSymbol", "invariant", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "Buffer", "Uint8Array", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomBytes", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "constructor", "_value", "toJSON", "toJSONL", "truncate", "
|
|
3
|
+
"sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts"],
|
|
4
|
+
"sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,QAAIA,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS,SAAU,UAAU,MAAM;AACjC,UAAI,MAAM,SAAS,QAAQ,IAAI;AAE/B,UAAI,QAAQ,IAAI;AACd,cAAM,IAAI,MAAM,8BAA8B,IAAI;AAAA,MACpD;AAEA,aAAO;AAAA,IACT;AAEA,WAAO,UAAU,SAASC,cAAc,OAAO,SAAS;AACtD,UAAI;AAEJ,cAAQ,SAAS;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AACH,qBAAWH;AACX,kBAAQ,MAAM,QAAQ,OAAO,EAAE;AAC/B;AAAA,QACF,KAAK;AACH,qBAAWC;AACX,kBAAQ,MAAM,QAAQ,OAAO,EAAE;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c,YAAYlB,QAAQG,UAAU,CAAA;EACtD;AACF,CAAA;AAKA,IAAMM,mBAAmB;AAEzB,IAAMO,iBAAiB;",
|
|
6
|
+
"names": ["RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "inspect", "truncateKey", "devtoolsFormatter", "equalsSymbol", "invariant", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "Uint8Array", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomBytes", "randomOfLength", "length", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "base32Decode", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "invariant", "SpaceId", "Object", "freeze", "byteLength", "encode", "value", "invariant", "Uint8Array", "length", "MULTIBASE_PREFIX", "base32Encode", "decode", "startsWith", "base32Decode", "slice", "isValid", "ENCODED_LENGTH", "random", "randomBytes"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":
|
|
1
|
+
{"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"@dxos/node-std/crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":667,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22643},"packages/common/keys/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/node-std/crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7653},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":214},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431}},"bytes":14705}}}
|
package/dist/lib/node/index.cjs
CHANGED
|
@@ -20,12 +20,20 @@ var node_exports = {};
|
|
|
20
20
|
__export(node_exports, {
|
|
21
21
|
PUBLIC_KEY_LENGTH: () => PUBLIC_KEY_LENGTH,
|
|
22
22
|
PublicKey: () => PublicKey,
|
|
23
|
-
SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH
|
|
23
|
+
SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH,
|
|
24
|
+
SpaceId: () => SpaceId
|
|
24
25
|
});
|
|
25
26
|
module.exports = __toCommonJS(node_exports);
|
|
26
27
|
var import_node_util = require("node:util");
|
|
27
28
|
var import_debug = require("@dxos/debug");
|
|
28
29
|
var import_invariant = require("@dxos/invariant");
|
|
30
|
+
var import_invariant2 = require("@dxos/invariant");
|
|
31
|
+
var __create = Object.create;
|
|
32
|
+
var __defProp2 = Object.defineProperty;
|
|
33
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
34
|
+
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
35
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
36
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
29
37
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
30
38
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
31
39
|
}) : x)(function(x) {
|
|
@@ -33,6 +41,135 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
33
41
|
return require.apply(this, arguments);
|
|
34
42
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
35
43
|
});
|
|
44
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
45
|
+
return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
46
|
+
};
|
|
47
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
48
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
49
|
+
for (let key of __getOwnPropNames2(from))
|
|
50
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
51
|
+
__defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
52
|
+
}
|
|
53
|
+
return to;
|
|
54
|
+
};
|
|
55
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps2(
|
|
56
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
57
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
58
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
59
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
60
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
|
|
61
|
+
mod
|
|
62
|
+
));
|
|
63
|
+
var require_base32_decode = __commonJS({
|
|
64
|
+
"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js"(exports, module2) {
|
|
65
|
+
var RFC46482 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
66
|
+
var RFC4648_HEX2 = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
|
67
|
+
var CROCKFORD2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
68
|
+
function readChar(alphabet, char) {
|
|
69
|
+
var idx = alphabet.indexOf(char);
|
|
70
|
+
if (idx === -1) {
|
|
71
|
+
throw new Error("Invalid character found: " + char);
|
|
72
|
+
}
|
|
73
|
+
return idx;
|
|
74
|
+
}
|
|
75
|
+
module2.exports = function base32Decode3(input, variant) {
|
|
76
|
+
var alphabet;
|
|
77
|
+
switch (variant) {
|
|
78
|
+
case "RFC3548":
|
|
79
|
+
case "RFC4648":
|
|
80
|
+
alphabet = RFC46482;
|
|
81
|
+
input = input.replace(/=+$/, "");
|
|
82
|
+
break;
|
|
83
|
+
case "RFC4648-HEX":
|
|
84
|
+
alphabet = RFC4648_HEX2;
|
|
85
|
+
input = input.replace(/=+$/, "");
|
|
86
|
+
break;
|
|
87
|
+
case "Crockford":
|
|
88
|
+
alphabet = CROCKFORD2;
|
|
89
|
+
input = input.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1");
|
|
90
|
+
break;
|
|
91
|
+
default:
|
|
92
|
+
throw new Error("Unknown base32 variant: " + variant);
|
|
93
|
+
}
|
|
94
|
+
var length = input.length;
|
|
95
|
+
var bits = 0;
|
|
96
|
+
var value = 0;
|
|
97
|
+
var index = 0;
|
|
98
|
+
var output = new Uint8Array(length * 5 / 8 | 0);
|
|
99
|
+
for (var i = 0; i < length; i++) {
|
|
100
|
+
value = value << 5 | readChar(alphabet, input[i]);
|
|
101
|
+
bits += 5;
|
|
102
|
+
if (bits >= 8) {
|
|
103
|
+
output[index++] = value >>> bits - 8 & 255;
|
|
104
|
+
bits -= 8;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return output.buffer;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
var import_base32_decode = __toESM(require_base32_decode());
|
|
112
|
+
function toDataView(data) {
|
|
113
|
+
if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
|
|
114
|
+
return new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
115
|
+
}
|
|
116
|
+
if (data instanceof ArrayBuffer) {
|
|
117
|
+
return new DataView(data);
|
|
118
|
+
}
|
|
119
|
+
throw new TypeError("Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray");
|
|
120
|
+
}
|
|
121
|
+
var RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
122
|
+
var RFC4648_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
|
123
|
+
var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
124
|
+
function base32Encode(data, variant, options) {
|
|
125
|
+
options = options || {};
|
|
126
|
+
let alphabet, defaultPadding;
|
|
127
|
+
switch (variant) {
|
|
128
|
+
case "RFC3548":
|
|
129
|
+
case "RFC4648":
|
|
130
|
+
alphabet = RFC4648;
|
|
131
|
+
defaultPadding = true;
|
|
132
|
+
break;
|
|
133
|
+
case "RFC4648-HEX":
|
|
134
|
+
alphabet = RFC4648_HEX;
|
|
135
|
+
defaultPadding = true;
|
|
136
|
+
break;
|
|
137
|
+
case "Crockford":
|
|
138
|
+
alphabet = CROCKFORD;
|
|
139
|
+
defaultPadding = false;
|
|
140
|
+
break;
|
|
141
|
+
default:
|
|
142
|
+
throw new Error("Unknown base32 variant: " + variant);
|
|
143
|
+
}
|
|
144
|
+
const padding = options.padding !== void 0 ? options.padding : defaultPadding;
|
|
145
|
+
const view = toDataView(data);
|
|
146
|
+
let bits = 0;
|
|
147
|
+
let value = 0;
|
|
148
|
+
let output = "";
|
|
149
|
+
for (let i = 0; i < view.byteLength; i++) {
|
|
150
|
+
value = value << 8 | view.getUint8(i);
|
|
151
|
+
bits += 8;
|
|
152
|
+
while (bits >= 5) {
|
|
153
|
+
output += alphabet[value >>> bits - 5 & 31];
|
|
154
|
+
bits -= 5;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (bits > 0) {
|
|
158
|
+
output += alphabet[value << 5 - bits & 31];
|
|
159
|
+
}
|
|
160
|
+
if (padding) {
|
|
161
|
+
while (output.length % 8 !== 0) {
|
|
162
|
+
output += "=";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return output;
|
|
166
|
+
}
|
|
167
|
+
var randomBytes = (length) => {
|
|
168
|
+
const webCrypto = globalThis.crypto ?? __require("node:crypto").webcrypto;
|
|
169
|
+
const bytes = new Uint8Array(length);
|
|
170
|
+
webCrypto.getRandomValues(bytes);
|
|
171
|
+
return bytes;
|
|
172
|
+
};
|
|
36
173
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
|
|
37
174
|
var PUBLIC_KEY_LENGTH = 32;
|
|
38
175
|
var SECRET_KEY_LENGTH = 64;
|
|
@@ -45,7 +182,7 @@ var PublicKey = class _PublicKey {
|
|
|
45
182
|
static from(source) {
|
|
46
183
|
(0, import_invariant.invariant)(source, void 0, {
|
|
47
184
|
F: __dxlog_file,
|
|
48
|
-
L:
|
|
185
|
+
L: 34,
|
|
49
186
|
S: this,
|
|
50
187
|
A: [
|
|
51
188
|
"source",
|
|
@@ -100,6 +237,9 @@ var PublicKey = class _PublicKey {
|
|
|
100
237
|
static random() {
|
|
101
238
|
return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
102
239
|
}
|
|
240
|
+
static randomOfLength(length) {
|
|
241
|
+
return _PublicKey.from(randomBytes(length));
|
|
242
|
+
}
|
|
103
243
|
static *randomSequence() {
|
|
104
244
|
for (let i = 0; i < 1e4; i++) {
|
|
105
245
|
yield _PublicKey.random();
|
|
@@ -134,7 +274,7 @@ var PublicKey = class _PublicKey {
|
|
|
134
274
|
static bufferize(str) {
|
|
135
275
|
(0, import_invariant.invariant)(typeof str === "string", "Invalid type", {
|
|
136
276
|
F: __dxlog_file,
|
|
137
|
-
L:
|
|
277
|
+
L: 137,
|
|
138
278
|
S: this,
|
|
139
279
|
A: [
|
|
140
280
|
"typeof str === 'string'",
|
|
@@ -157,7 +297,7 @@ var PublicKey = class _PublicKey {
|
|
|
157
297
|
}
|
|
158
298
|
(0, import_invariant.invariant)(key instanceof Buffer, "Invalid type", {
|
|
159
299
|
F: __dxlog_file,
|
|
160
|
-
L:
|
|
300
|
+
L: 156,
|
|
161
301
|
S: this,
|
|
162
302
|
A: [
|
|
163
303
|
"key instanceof Buffer",
|
|
@@ -173,6 +313,18 @@ var PublicKey = class _PublicKey {
|
|
|
173
313
|
static hash(key) {
|
|
174
314
|
return key.toHex();
|
|
175
315
|
}
|
|
316
|
+
static fromMultibase32(encoded) {
|
|
317
|
+
(0, import_invariant.invariant)(encoded.startsWith("B"), "Invalid multibase32 encoding", {
|
|
318
|
+
F: __dxlog_file,
|
|
319
|
+
L: 169,
|
|
320
|
+
S: this,
|
|
321
|
+
A: [
|
|
322
|
+
"encoded.startsWith('B')",
|
|
323
|
+
"'Invalid multibase32 encoding'"
|
|
324
|
+
]
|
|
325
|
+
});
|
|
326
|
+
return new _PublicKey(new Uint8Array((0, import_base32_decode.default)(encoded.slice(1), "RFC4648")));
|
|
327
|
+
}
|
|
176
328
|
constructor(_value) {
|
|
177
329
|
this._value = _value;
|
|
178
330
|
if (!(_value instanceof Uint8Array)) {
|
|
@@ -194,6 +346,9 @@ var PublicKey = class _PublicKey {
|
|
|
194
346
|
toHex() {
|
|
195
347
|
return this.asBuffer().toString("hex");
|
|
196
348
|
}
|
|
349
|
+
toMultibase32() {
|
|
350
|
+
return "B" + base32Encode(this._value, "RFC4648");
|
|
351
|
+
}
|
|
197
352
|
truncate(length = void 0) {
|
|
198
353
|
return (0, import_debug.truncateKey)(this, length);
|
|
199
354
|
}
|
|
@@ -298,16 +453,57 @@ var PublicKey = class _PublicKey {
|
|
|
298
453
|
return this.equals(other);
|
|
299
454
|
}
|
|
300
455
|
};
|
|
301
|
-
var
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
456
|
+
var import_base32_decode2 = __toESM(require_base32_decode());
|
|
457
|
+
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/keys/src/space-id.ts";
|
|
458
|
+
var SpaceId = Object.freeze({
|
|
459
|
+
byteLength: 20,
|
|
460
|
+
encode: (value) => {
|
|
461
|
+
(0, import_invariant2.invariant)(value instanceof Uint8Array, "Invalid type", {
|
|
462
|
+
F: __dxlog_file2,
|
|
463
|
+
L: 22,
|
|
464
|
+
S: void 0,
|
|
465
|
+
A: [
|
|
466
|
+
"value instanceof Uint8Array",
|
|
467
|
+
"'Invalid type'"
|
|
468
|
+
]
|
|
469
|
+
});
|
|
470
|
+
(0, import_invariant2.invariant)(value.length === SpaceId.byteLength, "Invalid length", {
|
|
471
|
+
F: __dxlog_file2,
|
|
472
|
+
L: 23,
|
|
473
|
+
S: void 0,
|
|
474
|
+
A: [
|
|
475
|
+
"value.length === SpaceId.byteLength",
|
|
476
|
+
"'Invalid length'"
|
|
477
|
+
]
|
|
478
|
+
});
|
|
479
|
+
return MULTIBASE_PREFIX + base32Encode(value, "RFC4648");
|
|
480
|
+
},
|
|
481
|
+
decode: (value) => {
|
|
482
|
+
(0, import_invariant2.invariant)(value.startsWith(MULTIBASE_PREFIX), "Invalid multibase32 encoding", {
|
|
483
|
+
F: __dxlog_file2,
|
|
484
|
+
L: 28,
|
|
485
|
+
S: void 0,
|
|
486
|
+
A: [
|
|
487
|
+
"value.startsWith(MULTIBASE_PREFIX)",
|
|
488
|
+
"'Invalid multibase32 encoding'"
|
|
489
|
+
]
|
|
490
|
+
});
|
|
491
|
+
return new Uint8Array((0, import_base32_decode2.default)(value.slice(1), "RFC4648"));
|
|
492
|
+
},
|
|
493
|
+
isValid: (value) => {
|
|
494
|
+
return typeof value === "string" && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;
|
|
495
|
+
},
|
|
496
|
+
random: () => {
|
|
497
|
+
return SpaceId.encode(randomBytes(SpaceId.byteLength));
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
var MULTIBASE_PREFIX = "B";
|
|
501
|
+
var ENCODED_LENGTH = 33;
|
|
307
502
|
// Annotate the CommonJS export names for ESM import in node:
|
|
308
503
|
0 && (module.exports = {
|
|
309
504
|
PUBLIC_KEY_LENGTH,
|
|
310
505
|
PublicKey,
|
|
311
|
-
SECRET_KEY_LENGTH
|
|
506
|
+
SECRET_KEY_LENGTH,
|
|
507
|
+
SpaceId
|
|
312
508
|
});
|
|
313
509
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/public-key.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n\nconst randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "
|
|
3
|
+
"sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts"],
|
|
4
|
+
"sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;AIF1B,IAAAA,oBAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ALP1B,IAAA,wBAAA,WAAA;EAAA,6EAAA,SAAAC,SAAA;AAAA,QAAIC,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS,SAAU,UAAU,MAAM;AACjC,UAAI,MAAM,SAAS,QAAQ,IAAI;AAE/B,UAAI,QAAQ,IAAI;AACd,cAAM,IAAI,MAAM,8BAA8B,IAAI;MACpD;AAEA,aAAO;IACT;AAEA,IAAAH,QAAO,UAAU,SAASI,cAAc,OAAO,SAAS;AACtD,UAAI;AAEJ,cAAQ,SAAS;QACf,KAAK;QACL,KAAK;AACH,qBAAWH;AACX,kBAAQ,MAAM,QAAQ,OAAO,EAAE;AAC/B;QACF,KAAK;AACH,qBAAWC;AACX,kBAAQ,MAAM,QAAQ,OAAO,EAAE;AAC/B;QACF,KAAK;AACH,qBAAWC;AACX,kBAAQ,MAAM,YAAY,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,SAAS,GAAG;AACnE;QACF;AACE,gBAAM,IAAI,MAAM,6BAA6B,OAAO;MACxD;AAEA,UAAI,SAAS,MAAM;AAEnB,UAAI,OAAO;AACX,UAAI,QAAQ;AAEZ,UAAI,QAAQ;AACZ,UAAI,SAAS,IAAI,WAAY,SAAS,IAAI,IAAK,CAAC;AAEhD,eAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,gBAAS,SAAS,IAAK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A,GAAQ;AACjC,aAAO;IACT;AAEA,WAAO,KAAK1C,OAAO0C,KAAAA;EACrB;AACF;AIlTA,IAAAI,wBAAyB,QAAA,sBAAA,CAAA;;AAclB,IAAMC,UAAUC,OAAOC,OAAO;EACnCtE,YAAY;EACZuE,QAAQ,CAACpD,UAAAA;AACPvB,0BAAAA,WAAUuB,iBAAiB9B,YAAY,gBAAA;;;;;;;;;AACvCO,0BAAAA,WAAUuB,MAAMrC,WAAWsF,QAAQpE,YAAY,kBAAA;;;;;;;;;AAE/C,WAAQwE,mBAAmBjC,aAAapB,OAAO,SAAA;EACjD;EACAsD,QAAQ,CAACtD,UAAAA;AACPvB,0BAAAA,WAAUuB,MAAMT,WAAW8D,gBAAAA,GAAmB,gCAAA;;;;;;;;;AAE9C,WAAO,IAAInF,YAAAA,GAAWT,sBAAAA,SAAauC,MAAMR,MAAM,CAAA,GAAI,SAAA,CAAA;EACrD;EACA+D,SAAS,CAACvD,UAAAA;AACR,WAAO,OAAOA,UAAU,YAAYA,MAAMT,WAAW8D,gBAAAA,KAAqBrD,MAAMrC,WAAW6F;EAC7F;EACA9D,QAAQ,MAAA;AACN,WAAOuD,QAAQG,OAAO1F,YAAYuF,QAAQpE,UAAU,CAAA;EACtD;AACF,CAAA;AAKA,IAAMwE,mBAAmB;AAEzB,IAAMG,iBAAiB;",
|
|
6
|
+
"names": ["import_invariant", "module", "RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomOfLength", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "SpaceId", "Object", "freeze", "encode", "MULTIBASE_PREFIX", "decode", "isValid", "ENCODED_LENGTH"]
|
|
7
7
|
}
|
package/dist/lib/node/meta.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":
|
|
1
|
+
{"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"node:crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":667,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22642},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7643},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":204},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431}},"bytes":14685}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC"}
|
|
@@ -35,6 +35,7 @@ export declare class PublicKey implements Equatable {
|
|
|
35
35
|
* Creates a new key.
|
|
36
36
|
*/
|
|
37
37
|
static random(): PublicKey;
|
|
38
|
+
static randomOfLength(length: number): PublicKey;
|
|
38
39
|
static randomSequence(): Generator<PublicKey>;
|
|
39
40
|
/**
|
|
40
41
|
* Tests if provided values is an instance of PublicKey.
|
|
@@ -65,12 +66,14 @@ export declare class PublicKey implements Equatable {
|
|
|
65
66
|
* Returns a scalar representation for this key.
|
|
66
67
|
*/
|
|
67
68
|
static hash(key: PublicKey): string;
|
|
69
|
+
static fromMultibase32(encoded: string): PublicKey;
|
|
68
70
|
constructor(_value: Uint8Array);
|
|
69
71
|
toString(): string;
|
|
70
72
|
toJSON(): string;
|
|
71
73
|
toJSONL(): string;
|
|
72
74
|
get length(): number;
|
|
73
75
|
toHex(): string;
|
|
76
|
+
toMultibase32(): string;
|
|
74
77
|
truncate(length?: undefined): string;
|
|
75
78
|
asBuffer(): Buffer;
|
|
76
79
|
asUint8Array(): Uint8Array;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public-key.d.ts","sourceRoot":"","sources":["../../../src/public-key.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"public-key.d.ts","sourceRoot":"","sources":["../../../src/public-key.ts"],"names":[],"mappings":";;AAMA,OAAO,EAAE,OAAO,EAAE,KAAK,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,EAAe,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;A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E,MAAM,GAAG,SAAS;gBAMrB,MAAM,EAAE,UAAU;IAM/C,QAAQ,IAAI,MAAM;IAIlB,MAAM;IAIN,OAAO,IAAI,MAAM;IAIjB,IAAI,MAAM,WAET;IAED,KAAK,IAAI,MAAM;IAIf,aAAa,IAAI,MAAM;IAIvB,QAAQ,CAAC,MAAM,YAAY;IAI3B,QAAQ,IAAI,MAAM;IAIlB,YAAY,IAAI,UAAU;IAI1B,eAAe,CAAC,MAAM,EAAE,MAAM;IAI9B;;OAEG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB;IAgC/D,IAAI,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,CA8B3C;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,EAAE,aAAa;IAc3B,CAAC,YAAY,CAAC,CAAC,KAAK,EAAE,GAAG;CAO1B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"random-bytes.d.ts","sourceRoot":"","sources":["../../../src/random-bytes.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,WAAW,WAAY,MAAM,eAQzC,CAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A unique identifier for a space.
|
|
3
|
+
* Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).
|
|
4
|
+
* @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE
|
|
5
|
+
*/
|
|
6
|
+
export type SpaceId = string & {
|
|
7
|
+
__SpaceId: true;
|
|
8
|
+
};
|
|
9
|
+
export declare const SpaceId: Readonly<{
|
|
10
|
+
byteLength: 20;
|
|
11
|
+
encode: (value: Uint8Array) => SpaceId;
|
|
12
|
+
decode: (value: SpaceId) => Uint8Array;
|
|
13
|
+
isValid: (value: string) => value is SpaceId;
|
|
14
|
+
random: () => SpaceId;
|
|
15
|
+
}>;
|
|
16
|
+
//# sourceMappingURL=space-id.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"space-id.d.ts","sourceRoot":"","sources":["../../../src/space-id.ts"],"names":[],"mappings":"AAWA;;;;GAIG;AACH,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG;IAAE,SAAS,EAAE,IAAI,CAAA;CAAE,CAAC;AAEnD,eAAO,MAAM,OAAO;;oBAEF,UAAU,KAAG,OAAO;oBAMpB,OAAO,KAAG,UAAU;qBAKnB,MAAM;kBAGX,OAAO;EAGnB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"space-id.test.d.ts","sourceRoot":"","sources":["../../../src/space-id.test.ts"],"names":[],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":";AAIA,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxos/keys",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9-main.2d0a5e6",
|
|
4
4
|
"description": "Key utils and definitions.",
|
|
5
5
|
"homepage": "https://dxos.org",
|
|
6
6
|
"bugs": "https://github.com/dxos/dxos/issues",
|
|
@@ -21,9 +21,13 @@
|
|
|
21
21
|
"src"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@dxos/
|
|
25
|
-
"@dxos/
|
|
26
|
-
"@dxos/
|
|
24
|
+
"@dxos/invariant": "0.5.9-main.2d0a5e6",
|
|
25
|
+
"@dxos/node-std": "0.5.9-main.2d0a5e6",
|
|
26
|
+
"@dxos/debug": "0.5.9-main.2d0a5e6"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"base32-decode": "^1.0.0",
|
|
30
|
+
"base32-encode": "^2.0.0"
|
|
27
31
|
},
|
|
28
32
|
"publishConfig": {
|
|
29
33
|
"access": "public"
|
package/src/index.ts
CHANGED
package/src/public-key.test.ts
CHANGED
|
@@ -60,4 +60,11 @@ describe('PublicKey', () => {
|
|
|
60
60
|
const key = PublicKey.random();
|
|
61
61
|
expect(PublicKey.equals(key, PublicKey.from(key.toHex()))).to.be.true;
|
|
62
62
|
});
|
|
63
|
+
|
|
64
|
+
test('base32', () => {
|
|
65
|
+
const key = PublicKey.randomOfLength(20); // Space keys will be cut to first 20 bytes of sha-256 hash.
|
|
66
|
+
const encoded = key.toMultibase32();
|
|
67
|
+
|
|
68
|
+
expect(PublicKey.fromMultibase32(encoded).toHex()).to.equal(key.toHex());
|
|
69
|
+
});
|
|
63
70
|
});
|
package/src/public-key.ts
CHANGED
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
// Copyright 2020 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
+
import base32Decode from 'base32-decode';
|
|
6
|
+
import base32Encode from 'base32-encode';
|
|
5
7
|
import { inspect, type InspectOptionsStylized } from 'node:util';
|
|
6
8
|
|
|
7
9
|
import { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';
|
|
8
10
|
import { invariant } from '@dxos/invariant';
|
|
9
11
|
|
|
12
|
+
import { randomBytes } from './random-bytes';
|
|
13
|
+
|
|
10
14
|
export const PUBLIC_KEY_LENGTH = 32;
|
|
11
15
|
export const SECRET_KEY_LENGTH = 64;
|
|
12
16
|
|
|
@@ -89,6 +93,10 @@ export class PublicKey implements Equatable {
|
|
|
89
93
|
return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
90
94
|
}
|
|
91
95
|
|
|
96
|
+
static randomOfLength(length: number): PublicKey {
|
|
97
|
+
return PublicKey.from(randomBytes(length));
|
|
98
|
+
}
|
|
99
|
+
|
|
92
100
|
static *randomSequence(): Generator<PublicKey> {
|
|
93
101
|
for (let i = 0; i < 1_0000; i++) {
|
|
94
102
|
// Counter just to protect against infinite loops.
|
|
@@ -157,6 +165,12 @@ export class PublicKey implements Equatable {
|
|
|
157
165
|
return key.toHex();
|
|
158
166
|
}
|
|
159
167
|
|
|
168
|
+
static fromMultibase32(encoded: string): PublicKey {
|
|
169
|
+
invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');
|
|
170
|
+
|
|
171
|
+
return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));
|
|
172
|
+
}
|
|
173
|
+
|
|
160
174
|
constructor(private readonly _value: Uint8Array) {
|
|
161
175
|
if (!(_value instanceof Uint8Array)) {
|
|
162
176
|
throw new TypeError(`Expected Uint8Array, got: ${_value}`);
|
|
@@ -183,6 +197,10 @@ export class PublicKey implements Equatable {
|
|
|
183
197
|
return this.asBuffer().toString('hex');
|
|
184
198
|
}
|
|
185
199
|
|
|
200
|
+
toMultibase32(): string {
|
|
201
|
+
return 'B' + base32Encode(this._value, 'RFC4648');
|
|
202
|
+
}
|
|
203
|
+
|
|
186
204
|
truncate(length = undefined) {
|
|
187
205
|
return truncateKey(this, length);
|
|
188
206
|
}
|
|
@@ -291,13 +309,3 @@ export class PublicKey implements Equatable {
|
|
|
291
309
|
return this.equals(other);
|
|
292
310
|
}
|
|
293
311
|
}
|
|
294
|
-
|
|
295
|
-
const randomBytes = (length: number) => {
|
|
296
|
-
// globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.
|
|
297
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
298
|
-
const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;
|
|
299
|
-
|
|
300
|
-
const bytes = new Uint8Array(length);
|
|
301
|
-
webCrypto.getRandomValues(bytes);
|
|
302
|
-
return bytes;
|
|
303
|
-
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
export const randomBytes = (length: number) => {
|
|
6
|
+
// globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
8
|
+
const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;
|
|
9
|
+
|
|
10
|
+
const bytes = new Uint8Array(length);
|
|
11
|
+
webCrypto.getRandomValues(bytes);
|
|
12
|
+
return bytes;
|
|
13
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { expect, test } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { SpaceId } from './space-id';
|
|
8
|
+
|
|
9
|
+
test('space-id', () => {
|
|
10
|
+
const id = SpaceId.random();
|
|
11
|
+
|
|
12
|
+
expect(SpaceId.isValid(id)).toBe(true);
|
|
13
|
+
expect(id.length).toBe(33);
|
|
14
|
+
const decoded = SpaceId.decode(id);
|
|
15
|
+
expect(decoded.length).toBe(SpaceId.byteLength);
|
|
16
|
+
expect(SpaceId.encode(decoded)).toBe(id);
|
|
17
|
+
});
|
package/src/space-id.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import base32Decode from 'base32-decode';
|
|
6
|
+
import base32Encode from 'base32-encode';
|
|
7
|
+
|
|
8
|
+
import { invariant } from '@dxos/invariant';
|
|
9
|
+
|
|
10
|
+
import { randomBytes } from './random-bytes';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A unique identifier for a space.
|
|
14
|
+
* Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).
|
|
15
|
+
* @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE
|
|
16
|
+
*/
|
|
17
|
+
export type SpaceId = string & { __SpaceId: true };
|
|
18
|
+
|
|
19
|
+
export const SpaceId = Object.freeze({
|
|
20
|
+
byteLength: 20,
|
|
21
|
+
encode: (value: Uint8Array): SpaceId => {
|
|
22
|
+
invariant(value instanceof Uint8Array, 'Invalid type');
|
|
23
|
+
invariant(value.length === SpaceId.byteLength, 'Invalid length');
|
|
24
|
+
|
|
25
|
+
return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;
|
|
26
|
+
},
|
|
27
|
+
decode: (value: SpaceId): Uint8Array => {
|
|
28
|
+
invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');
|
|
29
|
+
|
|
30
|
+
return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));
|
|
31
|
+
},
|
|
32
|
+
isValid: (value: string): value is SpaceId => {
|
|
33
|
+
return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;
|
|
34
|
+
},
|
|
35
|
+
random: (): SpaceId => {
|
|
36
|
+
return SpaceId.encode(randomBytes(SpaceId.byteLength));
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Denotes RFC4648 base-32 format.
|
|
42
|
+
*/
|
|
43
|
+
const MULTIBASE_PREFIX = 'B';
|
|
44
|
+
|
|
45
|
+
const ENCODED_LENGTH = 33;
|