@dxos/keys 0.4.4-next.e0df51e → 0.4.5-main.2d76d4e

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.
@@ -1,15 +1,13 @@
1
- import "@dxos/node-std/globals";
2
-
3
- // inject-globals:@inject-globals
4
- import {
5
- global,
6
- Buffer,
7
- process
8
- } from "@dxos/node-std/inject-globals";
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
9
8
 
10
9
  // packages/common/keys/src/public-key.ts
11
10
  import { inspect } from "@dxos/node-std/util";
12
- import randomBytes from "randombytes";
13
11
  import { truncateKey, devtoolsFormatter, equalsSymbol } from "@dxos/debug";
14
12
  import { invariant } from "@dxos/invariant";
15
13
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
@@ -24,7 +22,7 @@ var PublicKey = class _PublicKey {
24
22
  static from(source) {
25
23
  invariant(source, void 0, {
26
24
  F: __dxlog_file,
27
- L: 31,
25
+ L: 30,
28
26
  S: this,
29
27
  A: [
30
28
  "source",
@@ -113,7 +111,7 @@ var PublicKey = class _PublicKey {
113
111
  static bufferize(str) {
114
112
  invariant(typeof str === "string", "Invalid type", {
115
113
  F: __dxlog_file,
116
- L: 130,
114
+ L: 129,
117
115
  S: this,
118
116
  A: [
119
117
  "typeof str === 'string'",
@@ -136,7 +134,7 @@ var PublicKey = class _PublicKey {
136
134
  }
137
135
  invariant(key instanceof Buffer, "Invalid type", {
138
136
  F: __dxlog_file,
139
- L: 149,
137
+ L: 148,
140
138
  S: this,
141
139
  A: [
142
140
  "key instanceof Buffer",
@@ -274,6 +272,12 @@ var PublicKey = class _PublicKey {
274
272
  return this.equals(other);
275
273
  }
276
274
  };
275
+ var randomBytes = (length) => {
276
+ const webCrypto = globalThis.crypto ?? __require("@dxos/node-std/crypto").webcrypto;
277
+ const bytes = new Uint8Array(length);
278
+ webCrypto.getRandomValues(bytes);
279
+ return bytes;
280
+ };
277
281
  export {
278
282
  PUBLIC_KEY_LENGTH,
279
283
  PublicKey,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/public-key.ts"],
4
- "sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect, type InspectOptionsStylized } from 'node:util';\nimport randomBytes from 'randombytes';\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 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"],
5
- "mappings": ";;;;;;;;;;AAIA,SAASA,eAA4C;AACrD,OAAOC,iBAAiB;AAExB,SAASC,aAAaC,mBAA2CC,oBAAoC;AACrG,SAASC,iBAAiB;;AAEnB,IAAMC,oBAAoB;AAC1B,IAAMC,oBAAoB;AAY1B,IAAMC,YAAN,MAAMA,WAAAA;;;;;;EAMX,OAAOC,KAAKC,QAAkC;AAC5CL,cAAUK,QAAAA,QAAAA;;;;;;;;;AACV,QAAIA,kBAAkBF,YAAW;AAC/B,aAAOE;IACT,WAAWA,kBAAkBC,QAAQ;AACnC,aAAO,IAAIH,WAAU,IAAII,WAAWF,OAAOG,QAAQH,OAAOI,YAAYJ,OAAOK,UAAU,CAAA;IACzF,WAAWL,kBAAkBE,YAAY;AACvC,aAAO,IAAIJ,WAAUE,MAAAA;IACvB,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KAAK1B,OAAOhB,CAAAA,MAAOyC,eAAezB,OAAOhB,CAAAA;IACrD;AAEA,WAAO0C;EACT;EAEA,CAACpE,YAAAA,EAAckE,OAAY;AACzB,QAAI,CAAC9D,WAAUwB,YAAYsC,KAAAA,GAAQ;AACjC,aAAO;IACT;AAEA,WAAO,KAAKnC,OAAOmC,KAAAA;EACrB;AACF;",
6
- "names": ["inspect", "randomBytes", "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", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "constructor", "_value", "toJSON", "length", "truncate", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "header", "style", "other", "otherConverted", "equal"]
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 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": ";;;;;;;;;AAIA,SAASA,eAA4C;AAErD,SAASC,aAAaC,mBAA2CC,oBAAoC;AACrG,SAASC,iBAAiB;;AAEnB,IAAMC,oBAAoB;AAC1B,IAAMC,oBAAoB;AAY1B,IAAMC,YAAN,MAAMA,WAAAA;;;;;;EAMX,OAAOC,KAAKC,QAAkC;AAC5CL,cAAUK,QAAAA,QAAAA;;;;;;;;;AACV,QAAIA,kBAAkBF,YAAW;AAC/B,aAAOE;IACT,WAAWA,kBAAkBC,QAAQ;AACnC,aAAO,IAAIH,WAAU,IAAII,WAAWF,OAAOG,QAAQH,OAAOI,YAAYJ,OAAOK,UAAU,CAAA;IACzF,WAAWL,kBAAkBE,YAAY;AACvC,aAAO,IAAIJ,WAAUE,MAAAA;IACvB,WAAWA,kBAAkBM,aAAa;AACxC,aAAO,IAAIR,WAAU,IAAII,WAAWF,MAAAA,CAAAA;IACtC,WAAW,OAAOA,WAAW,UAAU;AAErC,aAAOF,WAAUS,QAAQP,MAAAA;IAC3B,WAAiBA,OAAQQ,cAAc;AACrC,aAAO,IAAIV,WAAgBE,OAAQQ,aAAY,CAAA;IACjD,OAAO;AACL,YAAM,IAAIC,UAAU,mCAAmCT,MAAAA,EAAQ;IACjE;EACF;;;;;;EAOA,OAAOU,SAASV,QAA+C;AAC7D,QAAI,CAACA,QAAQ;AACX,aAAOW;IACT;AAEA,QAAI;AACF,YAAMC,MAAMd,WAAUC,KAAKC,MAAAA;AAK3B,aAAOY;IACT,SAASC,KAAU;AACjB,aAAOF;IACT;EACF;;;;EAKA,OAAOJ,QAAQO,KAAa;AAC1B,QAAIA,IAAIC,WAAW,IAAA,GAAO;AACxBD,YAAMA,IAAIE,MAAM,CAAA;IAClB;AAEA,UAAMC,MAAMhB,OAAOF,KAAKe,KAAK,KAAA;AAE7B,WAAO,IAAI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;AAEN,cAAMR,SAAS;UACb;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;AAEF,cAAMM,QAAQN,OAAO,KAAKV,gBAAgBU,OAAOZ,MAAM,CAAA;AAEvD,eAAO;UACL;UACA,CAAC;UACD;YAAC;YAAQ,CAAC;YAAG;;UACb;YAAC;YAAQ;cAAEqB,OAAO,UAAUH,KAAAA;YAAS;YAAG,KAAKjB,SAAQ;;UACrD;YAAC;YAAQ,CAAC;YAAG;;;MAEjB;IACF;EACF;;;;EAKAd,OAAOmC,OAAsB;AAC3B,UAAMC,iBAAiBhE,WAAUC,KAAK8D,KAAAA;AACtC,QAAI,KAAKxB,OAAOE,WAAWuB,eAAezB,OAAOE,QAAQ;AACvD,aAAO;IACT;AAEA,QAAIwB,QAAQ;AACZ,aAAS1C,IAAI,GAAGA,IAAI,KAAKgB,OAAOE,QAAQlB,KAAK;AAC3C0C,gBAAU,KAAK1B,OAAOhB,CAAAA,MAAOyC,eAAezB,OAAOhB,CAAAA;IACrD;AAEA,WAAO0C;EACT;EAEA,CAACrE,YAAAA,EAAcmE,OAAY;AACzB,QAAI,CAAC/D,WAAUyB,YAAYsC,KAAAA,GAAQ;AACjC,aAAO;IACT;AAEA,WAAO,KAAKnC,OAAOmC,KAAAA;EACrB;AACF;AAEA,IAAM1C,cAAc,CAACoB,WAAAA;AAGnB,QAAMyB,YAAYC,WAAWC,UAAUC,UAAQ,uBAAA,EAAeC;AAE9D,QAAMC,QAAQ,IAAInE,WAAWqC,MAAAA;AAC7ByB,YAAUM,gBAAgBD,KAAAA;AAC1B,SAAOA;AACT;",
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", "length", "truncate", "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":{"inject-globals:@inject-globals":{"bytes":384,"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":27550,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"randombytes","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":641,"imports":[{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":547,"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":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13059},"packages/common/keys/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"randombytes","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"inject-globals:@inject-globals":{"bytesInOutput":79},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7044},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7335}}}
1
+ {"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":28725,"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":641,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":547,"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":13662},"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":7219},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7732}}}
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
  var node_exports = {};
30
20
  __export(node_exports, {
@@ -34,9 +24,15 @@ __export(node_exports, {
34
24
  });
35
25
  module.exports = __toCommonJS(node_exports);
36
26
  var import_node_util = require("node:util");
37
- var import_randombytes = __toESM(require("randombytes"));
38
27
  var import_debug = require("@dxos/debug");
39
28
  var import_invariant = require("@dxos/invariant");
29
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
30
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
31
+ }) : x)(function(x) {
32
+ if (typeof require !== "undefined")
33
+ return require.apply(this, arguments);
34
+ throw Error('Dynamic require of "' + x + '" is not supported');
35
+ });
40
36
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
41
37
  var PUBLIC_KEY_LENGTH = 32;
42
38
  var SECRET_KEY_LENGTH = 64;
@@ -49,7 +45,7 @@ var PublicKey = class _PublicKey {
49
45
  static from(source) {
50
46
  (0, import_invariant.invariant)(source, void 0, {
51
47
  F: __dxlog_file,
52
- L: 31,
48
+ L: 30,
53
49
  S: this,
54
50
  A: [
55
51
  "source",
@@ -102,7 +98,7 @@ var PublicKey = class _PublicKey {
102
98
  * Creates a new key.
103
99
  */
104
100
  static random() {
105
- return _PublicKey.from((0, import_randombytes.default)(PUBLIC_KEY_LENGTH));
101
+ return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
106
102
  }
107
103
  static *randomSequence() {
108
104
  for (let i = 0; i < 1e4; i++) {
@@ -138,7 +134,7 @@ var PublicKey = class _PublicKey {
138
134
  static bufferize(str) {
139
135
  (0, import_invariant.invariant)(typeof str === "string", "Invalid type", {
140
136
  F: __dxlog_file,
141
- L: 130,
137
+ L: 129,
142
138
  S: this,
143
139
  A: [
144
140
  "typeof str === 'string'",
@@ -161,7 +157,7 @@ var PublicKey = class _PublicKey {
161
157
  }
162
158
  (0, import_invariant.invariant)(key instanceof Buffer, "Invalid type", {
163
159
  F: __dxlog_file,
164
- L: 149,
160
+ L: 148,
165
161
  S: this,
166
162
  A: [
167
163
  "key instanceof Buffer",
@@ -299,6 +295,12 @@ var PublicKey = class _PublicKey {
299
295
  return this.equals(other);
300
296
  }
301
297
  };
298
+ var randomBytes = (length) => {
299
+ const webCrypto = globalThis.crypto ?? __require("node:crypto").webcrypto;
300
+ const bytes = new Uint8Array(length);
301
+ webCrypto.getRandomValues(bytes);
302
+ return bytes;
303
+ };
302
304
  // Annotate the CommonJS export names for ESM import in node:
303
305
  0 && (module.exports = {
304
306
  PUBLIC_KEY_LENGTH,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/public-key.ts"],
4
- "sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect, type InspectOptionsStylized } from 'node:util';\nimport randomBytes from 'randombytes';\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 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"],
5
- "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EF,cAAMM,QAAQN,OAAO,KAAKX,gBAAgBW,OAAOd,MAAM,CAAA;AAEvD,eAAO;UACL;UACA,CAAC;UACD;YAAC;YAAQ,CAAC;YAAG;;UACb;YAAC;YAAQ;cAAEwB,OAAO,UAAUJ,KAAAA;YAAS;YAAG,KAAKnB,SAAQ;;UACrD;YAAC;YAAQ,CAAC;YAAG;;;MAEjB;IACF;EACF;;;;EAKAd,OAAOsC,OAAsB;AAC3B,UAAMC,iBAAiBpE,WAAUC,KAAKkE,KAAAA;AACtC,QAAI,KAAK3B,OAAOE,WAAW0B,eAAe5B,OAAOE,QAAQ;AACvD,aAAO;IACT;AAEA,QAAI2B,QAAQ;AACZ,aAAS7C,IAAI,GAAGA,IAAI,KAAKgB,OAAOE,QAAQlB,KAAK;AAC3C6C,gBAAU,KAAK7B,OAAOhB,CAAAA,MAAO4C,eAAe5B,OAAOhB,CAAAA;IACrD;AAEA,WAAO6C;EACT;EAEA,CAACC,yBAAAA,EAAcH,OAAY;AACzB,QAAI,CAACnE,WAAU0B,YAAYyC,KAAAA,GAAQ;AACjC,aAAO;IACT;AAEA,WAAO,KAAKtC,OAAOsC,KAAAA;EACrB;AACF;",
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", "length", "truncate", "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"]
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 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": ";;;;;;;;;;;;;;;;;;;;;;;;;AAIA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;;;;;;;;;AAEnB,IAAMA,oBAAoB;AAC1B,IAAMC,oBAAoB;AAY1B,IAAMC,YAAN,MAAMA,WAAAA;;;;;;EAMX,OAAOC,KAAKC,QAAkC;AAC5CC,oCAAUD,QAAAA,QAAAA;;;;;;;;;AACV,QAAIA,kBAAkBF,YAAW;AAC/B,aAAOE;IACT,WAAWA,kBAAkBE,QAAQ;AACnC,aAAO,IAAIJ,WAAU,IAAIK,WAAWH,OAAOI,QAAQJ,OAAOK,YAAYL,OAAOM,UAAU,CAAA;IACzF,WAAWN,kBAAkBG,YAAY;AACvC,aAAO,IAAIL,WAAUE,MAAAA;IACvB,WAAWA,kBAAkBO,aAAa;AACxC,aAAO,IAAIT,WAAU,IAAIK,WAAWH,MAAAA,CAAAA;IACtC,WAAW,OAAOA,WAAW,UAAU;AAErC,aAAOF,WAAUU,QAAQR,MAAAA;IAC3B,WAA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AAA,GAAQ;AACjC,aAAO;IACT;AAEA,WAAO,KAAKtC,OAAOsC,KAAAA;EACrB;AACF;AAEA,IAAM7C,cAAc,CAACoB,WAAAA;AAGnB,QAAM6B,YAAYC,WAAWC,UAAUC,UAAQ,aAAA,EAAeC;AAE9D,QAAMC,QAAQ,IAAIvE,WAAWqC,MAAAA;AAC7B6B,YAAUM,gBAAgBD,KAAAA;AAC1B,SAAOA;AACT;",
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", "length", "truncate", "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
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":27550,"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"randombytes","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":641,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":547,"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":13050},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"randombytes","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","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":7034},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7177}}}
1
+ {"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":28725,"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":641,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":547,"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":13661},"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":7199},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7712}}}
@@ -1 +1 @@
1
- {"version":3,"file":"public-key.d.ts","sourceRoot":"","sources":["../../../src/public-key.ts"],"names":[],"mappings":";;AAIA,OAAO,EAAE,OAAO,EA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ys",
3
- "version": "0.4.4-next.e0df51e",
3
+ "version": "0.4.5-main.2d76d4e",
4
4
  "description": "Key utils and definitions.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
7
  "license": "MIT",
8
8
  "author": "DXOS.org",
9
- "main": "dist/lib/node/index.cjs",
10
- "browser": {
11
- "./dist/lib/node/index.cjs": "./dist/lib/browser/index.mjs"
9
+ "exports": {
10
+ ".": {
11
+ "browser": "./dist/lib/browser/index.mjs",
12
+ "node": "./dist/lib/node/index.cjs",
13
+ "import": "./dist/lib/browser/index.mjs",
14
+ "require": "./dist/lib/node/index.cjs",
15
+ "types": "./dist/types/src/index.d.ts"
16
+ }
12
17
  },
13
18
  "types": "dist/types/src/index.d.ts",
14
19
  "files": [
@@ -16,13 +21,9 @@
16
21
  "src"
17
22
  ],
18
23
  "dependencies": {
19
- "randombytes": "^2.1.0",
20
- "@dxos/invariant": "0.4.4-next.e0df51e",
21
- "@dxos/debug": "0.4.4-next.e0df51e",
22
- "@dxos/node-std": "0.4.4-next.e0df51e"
23
- },
24
- "devDependencies": {
25
- "@types/randombytes": "^2.0.0"
24
+ "@dxos/invariant": "0.4.5-main.2d76d4e",
25
+ "@dxos/debug": "0.4.5-main.2d76d4e",
26
+ "@dxos/node-std": "0.4.5-main.2d76d4e"
26
27
  },
27
28
  "publishConfig": {
28
29
  "access": "public"
@@ -3,8 +3,7 @@
3
3
  //
4
4
 
5
5
  import { expect } from 'chai';
6
-
7
- import { describe, test } from '@dxos/test';
6
+ import { describe, test } from 'vitest';
8
7
 
9
8
  import { PublicKey } from './public-key';
10
9
 
package/src/public-key.ts CHANGED
@@ -3,7 +3,6 @@
3
3
  //
4
4
 
5
5
  import { inspect, type InspectOptionsStylized } from 'node:util';
6
- import randomBytes from 'randombytes';
7
6
 
8
7
  import { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';
9
8
  import { invariant } from '@dxos/invariant';
@@ -288,3 +287,13 @@ export class PublicKey implements Equatable {
288
287
  return this.equals(other);
289
288
  }
290
289
  }
290
+
291
+ const randomBytes = (length: number) => {
292
+ // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.
293
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
294
+ const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;
295
+
296
+ const bytes = new Uint8Array(length);
297
+ webCrypto.getRandomValues(bytes);
298
+ return bytes;
299
+ };