@oxy.so/protocol 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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';