@oxy.so/protocol 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +675 -201
  2. package/NOTICE +7 -2
  3. package/dist/cjs/.tsbuildinfo +1 -1
  4. package/dist/cjs/auth/registrationPow.js +149 -0
  5. package/dist/cjs/index.js +9 -1
  6. package/dist/cjs/platform/crypto.js +6 -10
  7. package/dist/cjs/platform/crypto.native.js +14 -46
  8. package/dist/cjs/platform/optionalPeer.js +22 -0
  9. package/dist/cjs/platform/random.js +18 -0
  10. package/dist/cjs/platform/random.native.js +52 -0
  11. package/dist/cjs/random.js +25 -0
  12. package/dist/esm/.tsbuildinfo +1 -1
  13. package/dist/esm/auth/registrationPow.js +143 -0
  14. package/dist/esm/index.js +4 -0
  15. package/dist/esm/platform/crypto.js +4 -9
  16. package/dist/esm/platform/crypto.native.js +10 -43
  17. package/dist/esm/platform/optionalPeer.js +19 -0
  18. package/dist/esm/platform/random.js +15 -0
  19. package/dist/esm/platform/random.native.js +48 -0
  20. package/dist/esm/random.js +19 -0
  21. package/dist/types/.tsbuildinfo +1 -1
  22. package/dist/types/auth/registrationPow.d.ts +102 -0
  23. package/dist/types/index.d.ts +1 -0
  24. package/dist/types/platform/crypto.d.ts +1 -7
  25. package/dist/types/platform/crypto.native.d.ts +2 -10
  26. package/dist/types/platform/optionalPeer.d.ts +9 -0
  27. package/dist/types/platform/random.d.ts +13 -0
  28. package/dist/types/platform/random.native.d.ts +33 -0
  29. package/dist/types/random.d.ts +19 -0
  30. package/package.json +21 -4
  31. package/src/__tests__/randomEntry.test.ts +107 -0
  32. package/src/__tests__/registrationPow.test.ts +73 -0
  33. package/src/auth/registrationPow.ts +146 -0
  34. package/src/index.ts +10 -0
  35. package/src/platform/crypto.native.ts +10 -48
  36. package/src/platform/crypto.ts +4 -9
  37. package/src/platform/optionalPeer.ts +23 -0
  38. package/src/platform/random.native.ts +56 -0
  39. package/src/platform/random.ts +18 -0
  40. package/src/random.ts +20 -0
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Registration proof-of-work — the message format and difficulty check a
3
+ * signup grinds a nonce against, shared verbatim between the client (which
4
+ * SOLVES it) and the server (which CHECKS it).
5
+ *
6
+ * ## Why this exists
7
+ *
8
+ * `POST /auth/register` mints an account from nothing more than a freshly
9
+ * generated secp256k1 keypair and a signature over
10
+ * `oxy:register:{publicKey}:{timestamp}` — computationally free. A PoW nonce
11
+ * makes each account cost a small, real amount of CPU time to mint, without
12
+ * asking a real signer for anything beyond what they already do locally: no
13
+ * server round trip, no third-party CAPTCHA, no extra user-visible step.
14
+ *
15
+ * ## Single source, on purpose
16
+ *
17
+ * The client must SOLVE the exact message the server CHECKS, so the message
18
+ * format and the difficulty threshold live here once, in a package both
19
+ * `@oxy.so/core` (the client SDK) and the API already depend on for
20
+ * secp256k1 — see `packages/contracts/src/username.ts`'s docblock for why
21
+ * this codebase treats "the same rule declared twice" as a bug class, not a
22
+ * style preference. This file is deliberately CRYPTO-FREE: it is pure
23
+ * string/bit arithmetic over a caller-supplied hex digest, so it needs no
24
+ * platform hashing primitive and is trivially unit-testable with fixed
25
+ * digests. Each side hashes with whatever SHA-256 it already has — Node's
26
+ * `crypto` server-side (`packages/api/src/controllers/session.controller.ts`),
27
+ * `@noble/hashes/sha256` client-side (`packages/core/src/crypto/registrationPow.ts`,
28
+ * already a `@oxy.so/core` dependency — see `crypto/kdf.ts`,
29
+ * `crypto/identityProof.ts`) — and both produce byte-identical digests over
30
+ * the same message, because SHA-256 has exactly one correct output for a
31
+ * given input regardless of implementation.
32
+ *
33
+ * ## What this is NOT
34
+ *
35
+ * Not a defense against a targeted, patient attacker: nothing stops one from
36
+ * choosing their OWN `timestamp` a few minutes in the future and grinding the
37
+ * nonce ahead of time, banking a queue of pre-solved (timestamp, nonce) pairs
38
+ * to spend inside the 5-minute signature freshness window
39
+ * (`SignatureService.isTimestampFresh` / `MAX_SIGNATURE_AGE_MS`). Closing that
40
+ * needs a server-issued, single-use challenge — a real round trip and server
41
+ * state this deliberately does not add, because the goal here is raising the
42
+ * COST of unattended bulk signup, not proving liveness. Combined with a
43
+ * per-IP rate limit on `/auth/register`, it still meaningfully raises the
44
+ * price of automated mass account creation over today's zero-cost baseline.
45
+ *
46
+ * ## Rollout: advisory only, for now
47
+ *
48
+ * `POST /auth/register`'s `powNonce` field is OPTIONAL on the wire and the
49
+ * server does not yet reject a missing or failing one — see the comment at
50
+ * the check site in `packages/api/src/controllers/session.controller.ts` for
51
+ * why (every Oxy app consumes the SDK as a published package, not this
52
+ * monorepo live, so hard-enforcing before every app has picked up a client
53
+ * new enough to send it would break their signup outright) and exactly what
54
+ * to change to flip it to a hard 400.
55
+ */
56
+ /**
57
+ * Leading zero BITS contributed by one lowercase hex nibble.
58
+ *
59
+ * A hex digit is 4 bits: `'0'` contributes all 4, `'8'`–`'f'` (binary `1xxx`)
60
+ * contribute none because their own leading bit is already `1`. Spelled out
61
+ * as a table rather than derived with `Math.clz32` so the mapping is checkable
62
+ * by eye against the difficulty this gates.
63
+ */
64
+ const NIBBLE_LEADING_ZERO_BITS = {
65
+ '0': 4,
66
+ '1': 3,
67
+ '2': 2,
68
+ '3': 2,
69
+ '4': 1,
70
+ '5': 1,
71
+ '6': 1,
72
+ '7': 1,
73
+ '8': 0,
74
+ '9': 0,
75
+ a: 0,
76
+ b: 0,
77
+ c: 0,
78
+ d: 0,
79
+ e: 0,
80
+ f: 0,
81
+ };
82
+ /**
83
+ * The message a registration PoW nonce is grinded against, given the same
84
+ * `publicKey`/`timestamp` the registration signature (`oxy:register:…`)
85
+ * already commits to. A distinct prefix (`register-pow`, not `register`) so a
86
+ * solved PoW nonce can never be replayed as a registration signature input or
87
+ * vice versa — the two are unrelated preimages even for the same
88
+ * `publicKey`/`timestamp` pair.
89
+ */
90
+ export function registrationPowMessage(publicKey, timestamp, nonce) {
91
+ return `oxy:register-pow:${publicKey}:${timestamp}:${nonce}`;
92
+ }
93
+ /**
94
+ * The number of leading zero bits {@link meetsRegistrationPowDifficulty}
95
+ * requires of a solved nonce's digest.
96
+ *
97
+ * 16 bits ⇒ 65,536 SHA-256 attempts on average to solve. The client grinds
98
+ * with `@noble/hashes/sha256` — a pure-JS, SYNCHRONOUS implementation with
99
+ * "identical behaviour on web, Node, and React Native with zero WebCrypto /
100
+ * native-module dependency" (its own doc comment in `crypto/kdf.ts`) — so,
101
+ * unlike a solve loop built on a platform hashing primitive that crosses a
102
+ * JS↔native bridge per call (`expo-crypto`'s `digestStringAsync`, which this
103
+ * deliberately avoids for exactly that reason), there is no per-attempt
104
+ * bridge cost to budget for. The remaining uncertainty is Hermes' lack of a
105
+ * JIT, which can make a tight pure-JS loop meaningfully slower than V8 — 16
106
+ * bits is chosen to stay a sub-second grind even under that penalty, without
107
+ * reaching for a bound high enough to make Hermes specifically the deciding
108
+ * factor. Retune this constant (it is the only place the number is declared)
109
+ * once there is real on-device telemetry across the low end of the supported
110
+ * device range.
111
+ */
112
+ export const REGISTRATION_POW_DIFFICULTY_BITS = 16;
113
+ /**
114
+ * Count the leading zero BITS of a lowercase hex digest.
115
+ *
116
+ * Stops at the first non-zero nibble — a solved nonce only ever needs to beat
117
+ * a bound in the tens of bits, so scanning the full 256-bit digest is wasted
118
+ * work. A character outside `[0-9a-f]` (not a real digest — a caller passed
119
+ * something malformed) stops the count where it is rather than throwing: the
120
+ * caller compares the result against a difficulty, and an under-count from bad
121
+ * input correctly fails that comparison instead of crashing a request path.
122
+ */
123
+ export function countLeadingZeroBits(hexDigest) {
124
+ let bits = 0;
125
+ for (const char of hexDigest.toLowerCase()) {
126
+ const nibbleZeroBits = NIBBLE_LEADING_ZERO_BITS[char];
127
+ if (nibbleZeroBits === undefined)
128
+ break;
129
+ bits += nibbleZeroBits;
130
+ if (nibbleZeroBits < 4)
131
+ break;
132
+ }
133
+ return bits;
134
+ }
135
+ /**
136
+ * Whether a SHA-256 hex digest — of {@link registrationPowMessage} — clears
137
+ * `difficultyBits` leading zero bits. The one predicate both the client's
138
+ * solve loop and the server's check call, so neither can drift from what
139
+ * "solved" means.
140
+ */
141
+ export function meetsRegistrationPowDifficulty(hexDigest, difficultyBits) {
142
+ return countLeadingZeroBits(hexDigest) >= difficultyBits;
143
+ }
package/dist/esm/index.js CHANGED
@@ -26,6 +26,10 @@ export { verifyAndAppend } from './chain/engine.js';
26
26
  export { EMPTY_TRANSPARENCY_ROOT, transparencyLeafHash, buildTransparencyTree, buildTransparencyTreeFromHeads, inclusionProof, verifyInclusionProof, } from './transparency/tree.js';
27
27
  export { checkpointSigningInput, checkpointHash, signCheckpoint, verifyCheckpointSignature, } from './transparency/checkpoint.js';
28
28
  // ---------------------------------------------------------------------------
29
+ // Auth — registration proof-of-work (message format + difficulty check)
30
+ // ---------------------------------------------------------------------------
31
+ export { registrationPowMessage, countLeadingZeroBits, meetsRegistrationPowDifficulty, REGISTRATION_POW_DIFFICULTY_BITS, } from './auth/registrationPow.js';
32
+ // ---------------------------------------------------------------------------
29
33
  // Identity — injected verification-method resolution + authorization rule
30
34
  // ---------------------------------------------------------------------------
31
35
  export { isAuthorizedKey } from './identity/resolver.js';
@@ -123,15 +123,10 @@ export async function loadSecureStore() {
123
123
  export async function loadAsyncStorage() {
124
124
  throw notReactNativeError('@react-native-async-storage/async-storage');
125
125
  }
126
- /**
127
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`. Only available
128
- * in the React Native variant. The default variant throws because Node and
129
- * browsers have their own native CSPRNGs (`crypto.randomBytes` and
130
- * `crypto.getRandomValues` respectively) — callers should use those.
131
- */
132
- export function getRandomBytesRN(_byteCount) {
133
- throw notReactNativeError('expo-crypto.getRandomBytes (sync)');
134
- }
126
+ // Synchronous random bytes live in the dependency-free `./random` module so
127
+ // `@oxy.so/core`'s crypto polyfill can load them through the
128
+ // `@oxy.so/protocol/random` entry without evaluating any crypto library first.
129
+ export { getRandomBytesRN } from './random.js';
135
130
  // ---------------------------------------------------------------------------
136
131
  // Shared identity bridge — `@oxy.so/expo-oxy-identity` (native-only).
137
132
  //
@@ -24,7 +24,7 @@
24
24
  * Those three RN modules are declared OPTIONAL peer dependencies in
25
25
  * `package.json`. A static `import` contradicts that: an optional peer that is
26
26
  * omitted does not degrade, it fails to RESOLVE, and Metro aborts the whole
27
- * bundle. Because `@oxy.so/core`'s `crypto/polyfill` imports `@oxy.so/protocol`
27
+ * bundle. Because `@oxy.so/core` imports `@oxy.so/protocol`
28
28
  * from its root entry, this file is in the eager graph of EVERY React Native
29
29
  * app on `@oxy.so/core` — so a single undeclared optional peer broke the native
30
30
  * bundle of every app that did not happen to install it, with a resolution
@@ -52,14 +52,8 @@
52
52
  * so it stays a plain static import.
53
53
  */
54
54
  import { requireOptionalNativeModule } from 'expo-modules-core';
55
- let expoCryptoModule = null;
56
- let expoCryptoError;
57
- try {
58
- expoCryptoModule = require('expo-crypto');
59
- }
60
- catch (error) {
61
- expoCryptoError = error;
62
- }
55
+ import { missingOptionalPeerError } from './optionalPeer.js';
56
+ import { requireExpoCrypto } from './random.native.js';
63
57
  let secureStoreModule = null;
64
58
  let secureStoreError;
65
59
  try {
@@ -80,22 +74,6 @@ try {
80
74
  catch (error) {
81
75
  asyncStorageError = error;
82
76
  }
83
- /**
84
- * Actionable error for a missing optional peer. Carries the underlying Metro
85
- * resolution message so the failure is never silent — the `catch` above only
86
- * defers the report to the point where the capability is actually needed.
87
- */
88
- function missingOptionalPeerError(packageName, capability, cause) {
89
- const sentences = [
90
- `[oxy.protocol.crypto] '${packageName}' is not installed, so ${capability} is unavailable in this app.`,
91
- 'It is an optional peer dependency of @oxy.so/protocol that the React Native runtime needs —',
92
- `install it with \`npx expo install ${packageName}\`.`,
93
- ];
94
- if (cause instanceof Error) {
95
- sentences.push(`Underlying error: ${cause.message}`);
96
- }
97
- return new Error(sentences.join(' '));
98
- }
99
77
  // ---------------------------------------------------------------------------
100
78
  // Node `crypto` — never available in RN.
101
79
  // ---------------------------------------------------------------------------
@@ -116,10 +94,7 @@ export async function loadNodeCrypto() {
116
94
  // their compilation (see expoTypes.ts).
117
95
  // ---------------------------------------------------------------------------
118
96
  export async function loadExpoCrypto() {
119
- if (!expoCryptoModule) {
120
- throw missingOptionalPeerError('expo-crypto', 'React Native cryptography', expoCryptoError);
121
- }
122
- return expoCryptoModule;
97
+ return requireExpoCrypto('React Native cryptography');
123
98
  }
124
99
  // ---------------------------------------------------------------------------
125
100
  // expo-secure-store — RN keychain / keystore.
@@ -142,20 +117,12 @@ export async function loadAsyncStorage() {
142
117
  // ships ESM or CJS-with-default.
143
118
  return { default: asyncStorageModule };
144
119
  }
145
- /**
146
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`.
147
- *
148
- * Synchronous by contract: `@oxy.so/core`'s crypto polyfill uses this to back
149
- * `globalThis.crypto.getRandomValues`, which cannot await. That is why
150
- * `expo-crypto` is resolved with a synchronous `require` at module scope rather
151
- * than a dynamic `import()`.
152
- */
153
- export function getRandomBytesRN(byteCount) {
154
- if (!expoCryptoModule) {
155
- throw missingOptionalPeerError('expo-crypto', 'the React Native CSPRNG (crypto.getRandomValues)', expoCryptoError);
156
- }
157
- return expoCryptoModule.getRandomBytes(byteCount);
158
- }
120
+ // Synchronous random bytes (and the single `expo-crypto` resolution) live in
121
+ // the dependency-free `./random.native` module, so `@oxy.so/core`'s crypto
122
+ // polyfill can load them through `@oxy.so/protocol/random` without evaluating
123
+ // any crypto library first. The explicit `.native` specifier keeps tsc and
124
+ // Metro pointed at the same file.
125
+ export { getRandomBytesRN } from './random.native.js';
159
126
  // ---------------------------------------------------------------------------
160
127
  // Shared identity bridge — `@oxy.so/expo-oxy-identity` (native-only, OPTIONAL).
161
128
  //
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Actionable error for a missing optional React Native peer.
3
+ *
4
+ * Shared by the React Native platform variants (`crypto.native.ts`,
5
+ * `random.native.ts`). It carries the underlying Metro resolution message so
6
+ * the failure is never silent: the variants' `try { require(...) } catch` only
7
+ * defers the report to the point where the capability is actually used.
8
+ */
9
+ export function missingOptionalPeerError(packageName, capability, cause) {
10
+ const sentences = [
11
+ `[oxy.protocol.crypto] '${packageName}' is not installed, so ${capability} is unavailable in this app.`,
12
+ 'It is an optional peer dependency of @oxy.so/protocol that the React Native runtime needs —',
13
+ `install it with \`npx expo install ${packageName}\`.`,
14
+ ];
15
+ if (cause instanceof Error) {
16
+ sentences.push(`Underlying error: ${cause.message}`);
17
+ }
18
+ return new Error(sentences.join(' '));
19
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Synchronous CSPRNG source — default variant (Node.js, browsers, bundlers).
3
+ *
4
+ * Companion to `./random.native.ts`, which Metro substitutes on iOS / Android.
5
+ * Node and browsers own a native CSPRNG (`node:crypto`, `globalThis.crypto`),
6
+ * so `getRandomBytesRN` only exists here to keep both variants' surfaces
7
+ * identical, and throws if anything reaches it outside React Native.
8
+ *
9
+ * Like its sibling, this module imports nothing: it is part of the
10
+ * `@oxy.so/protocol/random` entry that `@oxy.so/core`'s crypto polyfill loads
11
+ * BEFORE any crypto library is evaluated.
12
+ */
13
+ export function getRandomBytesRN(_byteCount) {
14
+ throw new Error("[oxy.protocol.crypto] Tried to load 'expo-crypto.getRandomBytes (sync)' outside React Native. This module is only available in a React Native runtime; bundling routed this consumer to the default (Node/web) variant. This indicates a missing platform gate (`isReactNative()`) in the calling code.");
15
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Synchronous CSPRNG source — React Native variant.
3
+ *
4
+ * Companion to `./random.ts`; Metro substitutes this file on iOS / Android
5
+ * (see `./crypto.ts` for how the `.native` split works).
6
+ *
7
+ * This module is deliberately tiny and imports NOTHING but `expo-crypto`: it
8
+ * backs `@oxy.so/core`'s `globalThis.crypto.getRandomValues` polyfill, which
9
+ * must be fully installed before any module that captures `globalThis.crypto`
10
+ * at evaluation time (`@noble/hashes` 1.x's `crypto.js` does exactly that) is
11
+ * evaluated. Reaching a crypto library from here would let that library
12
+ * capture the missing global first and throw
13
+ * `crypto.getRandomValues must be defined` for the lifetime of the app.
14
+ *
15
+ * `expo-crypto` is an OPTIONAL peer, so it is resolved with a string-literal
16
+ * `require` inside a `try` (Metro's optional-dependency form; see
17
+ * `./crypto.native.ts`), and the load stays synchronous because
18
+ * `getRandomValues` cannot await.
19
+ */
20
+ import { missingOptionalPeerError } from './optionalPeer.js';
21
+ let expoCryptoModule = null;
22
+ let expoCryptoError;
23
+ try {
24
+ expoCryptoModule = require('expo-crypto');
25
+ }
26
+ catch (error) {
27
+ expoCryptoError = error;
28
+ }
29
+ /**
30
+ * The resolved `expo-crypto` module, or an actionable error naming the missing
31
+ * peer and the capability that needed it. Shared with `./crypto.native.ts` so
32
+ * the optional peer is resolved in exactly one place.
33
+ */
34
+ export function requireExpoCrypto(capability) {
35
+ if (!expoCryptoModule) {
36
+ throw missingOptionalPeerError('expo-crypto', capability, expoCryptoError);
37
+ }
38
+ return expoCryptoModule;
39
+ }
40
+ /**
41
+ * Synchronous random bytes via `expo-crypto.getRandomBytes`.
42
+ *
43
+ * Synchronous by contract: `@oxy.so/core`'s crypto polyfill uses this to back
44
+ * `globalThis.crypto.getRandomValues`, which cannot await.
45
+ */
46
+ export function getRandomBytesRN(byteCount) {
47
+ return requireExpoCrypto('the React Native CSPRNG (crypto.getRandomValues)').getRandomBytes(byteCount);
48
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@oxy.so/protocol/random` — the platform randomness source, and nothing else.
3
+ *
4
+ * `@oxy.so/core`'s crypto polyfill installs `globalThis.crypto.getRandomValues`
5
+ * on hosts that lack it (React Native / Hermes). `@noble/hashes` 1.x captures
6
+ * `globalThis.crypto` ONCE, when its `crypto.js` is evaluated, so the polyfill
7
+ * has to be installed before any `@noble/*` module is evaluated. ES imports are
8
+ * evaluated before the importing module's body, so whatever the polyfill
9
+ * imports is evaluated first: importing the ROOT entry (which reaches
10
+ * `@noble/curves` through the envelope signer) let noble capture `undefined`
11
+ * and broke identity creation on Android.
12
+ *
13
+ * This entry therefore reaches no crypto library, no `@oxy.so/*` package and no
14
+ * third-party module other than the optional `expo-crypto` peer (RN variant
15
+ * only). `src/__tests__/randomEntry.test.ts` walks its module graph to keep it
16
+ * that way.
17
+ */
18
+ export { isNodeJS, isReactNative } from './platform/platform.js';
19
+ export { getRandomBytesRN } from './platform/random.js';