@dxos/keys 0.5.8-main.e343621 → 0.5.8-next.4b7fabd
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 +10 -219
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +11 -207
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/index.d.ts +0 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/public-key.d.ts +0 -3
- package/dist/types/src/public-key.d.ts.map +1 -1
- package/dist/types/src/types.d.ts.map +1 -1
- package/package.json +4 -8
- package/src/index.ts +0 -1
- package/src/public-key.test.ts +0 -7
- package/src/public-key.ts +10 -18
- package/src/types.ts +1 -0
- package/dist/types/src/random-bytes.d.ts +0 -2
- package/dist/types/src/random-bytes.d.ts.map +0 -1
- package/dist/types/src/space-id.d.ts +0 -16
- package/dist/types/src/space-id.d.ts.map +0 -1
- package/dist/types/src/space-id.test.d.ts +0 -2
- package/dist/types/src/space-id.test.d.ts.map +0 -1
- package/src/random-bytes.ts +0 -13
- package/src/space-id.test.ts +0 -17
- package/src/space-id.ts +0 -45
|
@@ -1,9 +1,3 @@
|
|
|
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;
|
|
7
1
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
8
2
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
9
3
|
}) : x)(function(x) {
|
|
@@ -11,152 +5,11 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
11
5
|
return require.apply(this, arguments);
|
|
12
6
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
13
7
|
});
|
|
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
|
-
}
|
|
145
8
|
|
|
146
9
|
// packages/common/keys/src/public-key.ts
|
|
147
10
|
import { inspect } from "@dxos/node-std/util";
|
|
148
11
|
import { truncateKey, devtoolsFormatter, equalsSymbol } from "@dxos/debug";
|
|
149
12
|
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
|
|
160
13
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
|
|
161
14
|
var PUBLIC_KEY_LENGTH = 32;
|
|
162
15
|
var SECRET_KEY_LENGTH = 64;
|
|
@@ -169,7 +22,7 @@ var PublicKey = class _PublicKey {
|
|
|
169
22
|
static from(source) {
|
|
170
23
|
invariant(source, void 0, {
|
|
171
24
|
F: __dxlog_file,
|
|
172
|
-
L:
|
|
25
|
+
L: 30,
|
|
173
26
|
S: this,
|
|
174
27
|
A: [
|
|
175
28
|
"source",
|
|
@@ -224,9 +77,6 @@ var PublicKey = class _PublicKey {
|
|
|
224
77
|
static random() {
|
|
225
78
|
return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
226
79
|
}
|
|
227
|
-
static randomOfLength(length) {
|
|
228
|
-
return _PublicKey.from(randomBytes(length));
|
|
229
|
-
}
|
|
230
80
|
static *randomSequence() {
|
|
231
81
|
for (let i = 0; i < 1e4; i++) {
|
|
232
82
|
yield _PublicKey.random();
|
|
@@ -261,7 +111,7 @@ var PublicKey = class _PublicKey {
|
|
|
261
111
|
static bufferize(str) {
|
|
262
112
|
invariant(typeof str === "string", "Invalid type", {
|
|
263
113
|
F: __dxlog_file,
|
|
264
|
-
L:
|
|
114
|
+
L: 129,
|
|
265
115
|
S: this,
|
|
266
116
|
A: [
|
|
267
117
|
"typeof str === 'string'",
|
|
@@ -284,7 +134,7 @@ var PublicKey = class _PublicKey {
|
|
|
284
134
|
}
|
|
285
135
|
invariant(key instanceof Buffer, "Invalid type", {
|
|
286
136
|
F: __dxlog_file,
|
|
287
|
-
L:
|
|
137
|
+
L: 148,
|
|
288
138
|
S: this,
|
|
289
139
|
A: [
|
|
290
140
|
"key instanceof Buffer",
|
|
@@ -300,18 +150,6 @@ var PublicKey = class _PublicKey {
|
|
|
300
150
|
static hash(key) {
|
|
301
151
|
return key.toHex();
|
|
302
152
|
}
|
|
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
|
-
}
|
|
315
153
|
constructor(_value) {
|
|
316
154
|
this._value = _value;
|
|
317
155
|
if (!(_value instanceof Uint8Array)) {
|
|
@@ -333,9 +171,6 @@ var PublicKey = class _PublicKey {
|
|
|
333
171
|
toHex() {
|
|
334
172
|
return this.asBuffer().toString("hex");
|
|
335
173
|
}
|
|
336
|
-
toMultibase32() {
|
|
337
|
-
return "B" + base32Encode(this._value, "RFC4648");
|
|
338
|
-
}
|
|
339
174
|
truncate(length = void 0) {
|
|
340
175
|
return truncateKey(this, length);
|
|
341
176
|
}
|
|
@@ -440,59 +275,15 @@ var PublicKey = class _PublicKey {
|
|
|
440
275
|
return this.equals(other);
|
|
441
276
|
}
|
|
442
277
|
};
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
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;
|
|
278
|
+
var randomBytes = (length) => {
|
|
279
|
+
const webCrypto = globalThis.crypto ?? __require("@dxos/node-std/crypto").webcrypto;
|
|
280
|
+
const bytes = new Uint8Array(length);
|
|
281
|
+
webCrypto.getRandomValues(bytes);
|
|
282
|
+
return bytes;
|
|
283
|
+
};
|
|
492
284
|
export {
|
|
493
285
|
PUBLIC_KEY_LENGTH,
|
|
494
286
|
PublicKey,
|
|
495
|
-
SECRET_KEY_LENGTH
|
|
496
|
-
SpaceId
|
|
287
|
+
SECRET_KEY_LENGTH
|
|
497
288
|
};
|
|
498
289
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
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": "
|
|
6
|
-
"names": ["
|
|
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": "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",
|
|
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", "length", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "header", "style", "other", "otherConverted", "equal", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "getRandomValues"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"
|
|
1
|
+
{"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":29335,"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}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":673,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":579,"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"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13773},"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}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"packages/common/keys/src/public-key.ts":{"bytesInOutput":7265},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7778}}}
|
package/dist/lib/node/index.cjs
CHANGED
|
@@ -20,20 +20,12 @@ 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
|
|
24
|
-
SpaceId: () => SpaceId
|
|
23
|
+
SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH
|
|
25
24
|
});
|
|
26
25
|
module.exports = __toCommonJS(node_exports);
|
|
27
26
|
var import_node_util = require("node:util");
|
|
28
27
|
var import_debug = require("@dxos/debug");
|
|
29
28
|
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;
|
|
37
29
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
38
30
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
39
31
|
}) : x)(function(x) {
|
|
@@ -41,135 +33,6 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
41
33
|
return require.apply(this, arguments);
|
|
42
34
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
43
35
|
});
|
|
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
|
-
};
|
|
173
36
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
|
|
174
37
|
var PUBLIC_KEY_LENGTH = 32;
|
|
175
38
|
var SECRET_KEY_LENGTH = 64;
|
|
@@ -182,7 +45,7 @@ var PublicKey = class _PublicKey {
|
|
|
182
45
|
static from(source) {
|
|
183
46
|
(0, import_invariant.invariant)(source, void 0, {
|
|
184
47
|
F: __dxlog_file,
|
|
185
|
-
L:
|
|
48
|
+
L: 30,
|
|
186
49
|
S: this,
|
|
187
50
|
A: [
|
|
188
51
|
"source",
|
|
@@ -237,9 +100,6 @@ var PublicKey = class _PublicKey {
|
|
|
237
100
|
static random() {
|
|
238
101
|
return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
239
102
|
}
|
|
240
|
-
static randomOfLength(length) {
|
|
241
|
-
return _PublicKey.from(randomBytes(length));
|
|
242
|
-
}
|
|
243
103
|
static *randomSequence() {
|
|
244
104
|
for (let i = 0; i < 1e4; i++) {
|
|
245
105
|
yield _PublicKey.random();
|
|
@@ -274,7 +134,7 @@ var PublicKey = class _PublicKey {
|
|
|
274
134
|
static bufferize(str) {
|
|
275
135
|
(0, import_invariant.invariant)(typeof str === "string", "Invalid type", {
|
|
276
136
|
F: __dxlog_file,
|
|
277
|
-
L:
|
|
137
|
+
L: 129,
|
|
278
138
|
S: this,
|
|
279
139
|
A: [
|
|
280
140
|
"typeof str === 'string'",
|
|
@@ -297,7 +157,7 @@ var PublicKey = class _PublicKey {
|
|
|
297
157
|
}
|
|
298
158
|
(0, import_invariant.invariant)(key instanceof Buffer, "Invalid type", {
|
|
299
159
|
F: __dxlog_file,
|
|
300
|
-
L:
|
|
160
|
+
L: 148,
|
|
301
161
|
S: this,
|
|
302
162
|
A: [
|
|
303
163
|
"key instanceof Buffer",
|
|
@@ -313,18 +173,6 @@ var PublicKey = class _PublicKey {
|
|
|
313
173
|
static hash(key) {
|
|
314
174
|
return key.toHex();
|
|
315
175
|
}
|
|
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
|
-
}
|
|
328
176
|
constructor(_value) {
|
|
329
177
|
this._value = _value;
|
|
330
178
|
if (!(_value instanceof Uint8Array)) {
|
|
@@ -346,9 +194,6 @@ var PublicKey = class _PublicKey {
|
|
|
346
194
|
toHex() {
|
|
347
195
|
return this.asBuffer().toString("hex");
|
|
348
196
|
}
|
|
349
|
-
toMultibase32() {
|
|
350
|
-
return "B" + base32Encode(this._value, "RFC4648");
|
|
351
|
-
}
|
|
352
197
|
truncate(length = void 0) {
|
|
353
198
|
return (0, import_debug.truncateKey)(this, length);
|
|
354
199
|
}
|
|
@@ -453,57 +298,16 @@ var PublicKey = class _PublicKey {
|
|
|
453
298
|
return this.equals(other);
|
|
454
299
|
}
|
|
455
300
|
};
|
|
456
|
-
var
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
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;
|
|
301
|
+
var randomBytes = (length) => {
|
|
302
|
+
const webCrypto = globalThis.crypto ?? __require("node:crypto").webcrypto;
|
|
303
|
+
const bytes = new Uint8Array(length);
|
|
304
|
+
webCrypto.getRandomValues(bytes);
|
|
305
|
+
return bytes;
|
|
306
|
+
};
|
|
502
307
|
// Annotate the CommonJS export names for ESM import in node:
|
|
503
308
|
0 && (module.exports = {
|
|
504
309
|
PUBLIC_KEY_LENGTH,
|
|
505
310
|
PublicKey,
|
|
506
|
-
SECRET_KEY_LENGTH
|
|
507
|
-
SpaceId
|
|
311
|
+
SECRET_KEY_LENGTH
|
|
508
312
|
});
|
|
509
313
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
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": "
|
|
6
|
-
"names": ["
|
|
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": "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",
|
|
6
|
+
"names": ["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", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "constructor", "_value", "toJSON", "toJSONL", "truncate", "length", "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", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "getRandomValues"]
|
|
7
7
|
}
|
package/dist/lib/node/meta.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"
|
|
1
|
+
{"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":29335,"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}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":673,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":579,"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"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13772},"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}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"packages/common/keys/src/public-key.ts":{"bytesInOutput":7245},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7758}}}
|
|
@@ -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"}
|
|
@@ -35,7 +35,6 @@ 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;
|
|
39
38
|
static randomSequence(): Generator<PublicKey>;
|
|
40
39
|
/**
|
|
41
40
|
* Tests if provided values is an instance of PublicKey.
|
|
@@ -66,14 +65,12 @@ export declare class PublicKey implements Equatable {
|
|
|
66
65
|
* Returns a scalar representation for this key.
|
|
67
66
|
*/
|
|
68
67
|
static hash(key: PublicKey): string;
|
|
69
|
-
static fromMultibase32(encoded: string): PublicKey;
|
|
70
68
|
constructor(_value: Uint8Array);
|
|
71
69
|
toString(): string;
|
|
72
70
|
toJSON(): string;
|
|
73
71
|
toJSONL(): string;
|
|
74
72
|
get length(): number;
|
|
75
73
|
toHex(): string;
|
|
76
|
-
toMultibase32(): string;
|
|
77
74
|
truncate(length?: undefined): string;
|
|
78
75
|
asBuffer(): Buffer;
|
|
79
76
|
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":";;AAIA,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;AAGnH,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAEpC;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,UAAU,GAAG,WAAW,GAAG,MAAM,CAAC;AAEnF;;;;GAIG;AACH,qBAAa,SAAU,YAAW,SAAS;IAyI7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAxInC;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS;IAoB7C;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,SAAS;IAiB9D;;OAEG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM;IAU1B;;OAEG;IACH,MAAM,CAAC,MAAM,IAAI,SAAS;IAK1B,MAAM,CAAE,cAAc,IAAI,SAAS,CAAC,SAAS,CAAC;IAQ9C;;OAEG;IACH,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,SAAS;IAIlD;;OAEG;IACH,MAAM,CAAC,oBAAoB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO,CAAC,KAAK,IAAI,SAAS;IAMnE;;OAEG;IACH,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,aAAa;IAIvD;;;;OAIG;IACH,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAQrC;;;;OAIG;IACH,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,WAAW,GAAG,MAAM;IAWhE;;;OAGG;IACH,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,GAAG,MAAM;gBAIN,MAAM,EAAE,UAAU;IAM/C,QAAQ,IAAI,MAAM;IAIlB,MAAM;IAIN,OAAO,IAAI,MAAM;IAIjB,IAAI,MAAM,WAET;IAED,KAAK,IAAI,MAAM;IAIf,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"}
|
|
@@ -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":";AAKA,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.8-
|
|
3
|
+
"version": "0.5.8-next.4b7fabd",
|
|
4
4
|
"description": "Key utils and definitions.",
|
|
5
5
|
"homepage": "https://dxos.org",
|
|
6
6
|
"bugs": "https://github.com/dxos/dxos/issues",
|
|
@@ -21,13 +21,9 @@
|
|
|
21
21
|
"src"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@dxos/
|
|
25
|
-
"@dxos/
|
|
26
|
-
"@dxos/node-std": "0.5.8-
|
|
27
|
-
},
|
|
28
|
-
"devDependencies": {
|
|
29
|
-
"base32-decode": "^1.0.0",
|
|
30
|
-
"base32-encode": "^2.0.0"
|
|
24
|
+
"@dxos/debug": "0.5.8-next.4b7fabd",
|
|
25
|
+
"@dxos/invariant": "0.5.8-next.4b7fabd",
|
|
26
|
+
"@dxos/node-std": "0.5.8-next.4b7fabd"
|
|
31
27
|
},
|
|
32
28
|
"publishConfig": {
|
|
33
29
|
"access": "public"
|
package/src/index.ts
CHANGED
package/src/public-key.test.ts
CHANGED
|
@@ -60,11 +60,4 @@ 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
|
-
});
|
|
70
63
|
});
|
package/src/public-key.ts
CHANGED
|
@@ -2,15 +2,11 @@
|
|
|
2
2
|
// Copyright 2020 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import base32Decode from 'base32-decode';
|
|
6
|
-
import base32Encode from 'base32-encode';
|
|
7
5
|
import { inspect, type InspectOptionsStylized } from 'node:util';
|
|
8
6
|
|
|
9
7
|
import { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';
|
|
10
8
|
import { invariant } from '@dxos/invariant';
|
|
11
9
|
|
|
12
|
-
import { randomBytes } from './random-bytes';
|
|
13
|
-
|
|
14
10
|
export const PUBLIC_KEY_LENGTH = 32;
|
|
15
11
|
export const SECRET_KEY_LENGTH = 64;
|
|
16
12
|
|
|
@@ -93,10 +89,6 @@ export class PublicKey implements Equatable {
|
|
|
93
89
|
return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
|
|
94
90
|
}
|
|
95
91
|
|
|
96
|
-
static randomOfLength(length: number): PublicKey {
|
|
97
|
-
return PublicKey.from(randomBytes(length));
|
|
98
|
-
}
|
|
99
|
-
|
|
100
92
|
static *randomSequence(): Generator<PublicKey> {
|
|
101
93
|
for (let i = 0; i < 1_0000; i++) {
|
|
102
94
|
// Counter just to protect against infinite loops.
|
|
@@ -165,12 +157,6 @@ export class PublicKey implements Equatable {
|
|
|
165
157
|
return key.toHex();
|
|
166
158
|
}
|
|
167
159
|
|
|
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
|
-
|
|
174
160
|
constructor(private readonly _value: Uint8Array) {
|
|
175
161
|
if (!(_value instanceof Uint8Array)) {
|
|
176
162
|
throw new TypeError(`Expected Uint8Array, got: ${_value}`);
|
|
@@ -197,10 +183,6 @@ export class PublicKey implements Equatable {
|
|
|
197
183
|
return this.asBuffer().toString('hex');
|
|
198
184
|
}
|
|
199
185
|
|
|
200
|
-
toMultibase32(): string {
|
|
201
|
-
return 'B' + base32Encode(this._value, 'RFC4648');
|
|
202
|
-
}
|
|
203
|
-
|
|
204
186
|
truncate(length = undefined) {
|
|
205
187
|
return truncateKey(this, length);
|
|
206
188
|
}
|
|
@@ -309,3 +291,13 @@ export class PublicKey implements Equatable {
|
|
|
309
291
|
return this.equals(other);
|
|
310
292
|
}
|
|
311
293
|
}
|
|
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
|
+
};
|
package/src/types.ts
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"random-bytes.d.ts","sourceRoot":"","sources":["../../../src/random-bytes.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,WAAW,WAAY,MAAM,eAQzC,CAAC"}
|
|
@@ -1,16 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"space-id.test.d.ts","sourceRoot":"","sources":["../../../src/space-id.test.ts"],"names":[],"mappings":""}
|
package/src/random-bytes.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
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
|
-
};
|
package/src/space-id.test.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
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;
|