@oxyhq/core 4.0.1 → 5.0.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.
Files changed (109) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +6 -18
  3. package/dist/cjs/OxyServices.base.js +0 -21
  4. package/dist/cjs/crypto/keyManager.js +7 -7
  5. package/dist/cjs/crypto/polyfill.js +6 -5
  6. package/dist/cjs/crypto/signatureService.js +44 -220
  7. package/dist/cjs/index.js +4 -8
  8. package/dist/cjs/mixins/OxyServices.accounts.js +54 -0
  9. package/dist/cjs/mixins/OxyServices.assets.js +2 -2
  10. package/dist/cjs/mixins/OxyServices.auth.js +3 -3
  11. package/dist/cjs/mixins/OxyServices.civic.js +3 -3
  12. package/dist/cjs/mixins/OxyServices.language.js +2 -2
  13. package/dist/cjs/mixins/OxyServices.utility.js +7 -95
  14. package/dist/cjs/utils/cacheKey.js +17 -19
  15. package/dist/cjs/utils/deviceManager.js +2 -2
  16. package/dist/cjs/utils/platform.js +0 -14
  17. package/dist/esm/.tsbuildinfo +1 -1
  18. package/dist/esm/HttpService.js +6 -18
  19. package/dist/esm/OxyServices.base.js +0 -21
  20. package/dist/esm/crypto/keyManager.js +4 -4
  21. package/dist/esm/crypto/polyfill.js +5 -4
  22. package/dist/esm/crypto/signatureService.js +39 -214
  23. package/dist/esm/index.js +1 -2
  24. package/dist/esm/mixins/OxyServices.accounts.js +54 -0
  25. package/dist/esm/mixins/OxyServices.assets.js +1 -1
  26. package/dist/esm/mixins/OxyServices.auth.js +1 -1
  27. package/dist/esm/mixins/OxyServices.civic.js +3 -3
  28. package/dist/esm/mixins/OxyServices.language.js +1 -1
  29. package/dist/esm/mixins/OxyServices.utility.js +6 -94
  30. package/dist/esm/utils/cacheKey.js +17 -19
  31. package/dist/esm/utils/deviceManager.js +1 -1
  32. package/dist/esm/utils/platform.js +0 -12
  33. package/dist/types/.tsbuildinfo +1 -1
  34. package/dist/types/HttpService.d.ts +3 -6
  35. package/dist/types/OxyServices.base.d.ts +0 -17
  36. package/dist/types/crypto/polyfill.d.ts +2 -2
  37. package/dist/types/crypto/signatureService.d.ts +18 -84
  38. package/dist/types/index.d.ts +3 -4
  39. package/dist/types/mixins/OxyServices.accounts.d.ts +57 -5
  40. package/dist/types/mixins/OxyServices.analytics.d.ts +0 -2
  41. package/dist/types/mixins/OxyServices.appData.d.ts +0 -2
  42. package/dist/types/mixins/OxyServices.assets.d.ts +0 -2
  43. package/dist/types/mixins/OxyServices.auth.d.ts +0 -2
  44. package/dist/types/mixins/OxyServices.civic.d.ts +3 -5
  45. package/dist/types/mixins/OxyServices.connectedApps.d.ts +0 -2
  46. package/dist/types/mixins/OxyServices.contacts.d.ts +0 -2
  47. package/dist/types/mixins/OxyServices.devices.d.ts +0 -2
  48. package/dist/types/mixins/OxyServices.features.d.ts +0 -2
  49. package/dist/types/mixins/OxyServices.fedcm.d.ts +0 -2
  50. package/dist/types/mixins/OxyServices.identity.d.ts +8 -5
  51. package/dist/types/mixins/OxyServices.language.d.ts +0 -2
  52. package/dist/types/mixins/OxyServices.links.d.ts +0 -2
  53. package/dist/types/mixins/OxyServices.location.d.ts +0 -2
  54. package/dist/types/mixins/OxyServices.nodes.d.ts +0 -44
  55. package/dist/types/mixins/OxyServices.payment.d.ts +0 -2
  56. package/dist/types/mixins/OxyServices.privacy.d.ts +0 -2
  57. package/dist/types/mixins/OxyServices.redirect.d.ts +0 -2
  58. package/dist/types/mixins/OxyServices.reputation.d.ts +0 -2
  59. package/dist/types/mixins/OxyServices.security.d.ts +0 -2
  60. package/dist/types/mixins/OxyServices.silent.d.ts +0 -2
  61. package/dist/types/mixins/OxyServices.sso.d.ts +0 -2
  62. package/dist/types/mixins/OxyServices.topics.d.ts +0 -2
  63. package/dist/types/mixins/OxyServices.user.d.ts +0 -2
  64. package/dist/types/mixins/OxyServices.utility.d.ts +0 -32
  65. package/dist/types/server/auth.d.ts +0 -6
  66. package/dist/types/server/index.d.ts +1 -1
  67. package/dist/types/utils/cacheKey.d.ts +6 -7
  68. package/dist/types/utils/platform.d.ts +0 -8
  69. package/package.json +4 -7
  70. package/src/HttpService.ts +6 -22
  71. package/src/OxyServices.base.ts +0 -23
  72. package/src/__tests__/httpServiceCache.test.ts +0 -19
  73. package/src/crypto/__tests__/keyManager.atomicity.test.ts +2 -1
  74. package/src/crypto/__tests__/keyManager.test.ts +9 -7
  75. package/src/crypto/__tests__/signChallengeShared.test.ts +2 -1
  76. package/src/crypto/__tests__/signedRecord.test.ts +37 -150
  77. package/src/crypto/keyManager.ts +28 -17
  78. package/src/crypto/polyfill.ts +5 -4
  79. package/src/crypto/signatureService.ts +67 -255
  80. package/src/index.ts +3 -3
  81. package/src/mixins/OxyServices.accounts.ts +91 -3
  82. package/src/mixins/OxyServices.assets.ts +1 -1
  83. package/src/mixins/OxyServices.auth.ts +1 -1
  84. package/src/mixins/OxyServices.civic.ts +6 -17
  85. package/src/mixins/OxyServices.identity.ts +8 -2
  86. package/src/mixins/OxyServices.language.ts +1 -1
  87. package/src/mixins/OxyServices.nodes.ts +1 -12
  88. package/src/mixins/OxyServices.utility.ts +6 -119
  89. package/src/mixins/__tests__/OxyServices.civic.test.ts +2 -2
  90. package/src/mixins/__tests__/accounts.test.ts +70 -0
  91. package/src/server/auth.ts +0 -7
  92. package/src/server/index.ts +0 -1
  93. package/src/utils/__tests__/cacheKey.test.ts +0 -0
  94. package/src/utils/cacheKey.ts +16 -21
  95. package/src/utils/deviceManager.ts +1 -1
  96. package/src/utils/platform.ts +0 -14
  97. package/dist/cjs/crypto/canonicalJson.js +0 -107
  98. package/dist/cjs/utils/platformCrypto.js +0 -165
  99. package/dist/cjs/utils/platformCrypto.native.js +0 -123
  100. package/dist/esm/crypto/canonicalJson.js +0 -104
  101. package/dist/esm/utils/platformCrypto.js +0 -125
  102. package/dist/esm/utils/platformCrypto.native.js +0 -80
  103. package/dist/types/crypto/canonicalJson.d.ts +0 -44
  104. package/dist/types/utils/platformCrypto.d.ts +0 -87
  105. package/dist/types/utils/platformCrypto.native.d.ts +0 -54
  106. package/src/crypto/__tests__/canonicalJson.test.ts +0 -116
  107. package/src/crypto/canonicalJson.ts +0 -120
  108. package/src/utils/platformCrypto.native.ts +0 -101
  109. package/src/utils/platformCrypto.ts +0 -145
@@ -1,165 +0,0 @@
1
- "use strict";
2
- /**
3
- * Platform Crypto / Storage — Default Variant (Node.js, Browser, generic bundlers)
4
- *
5
- * Provides lazy access to platform-specific crypto and storage modules.
6
- *
7
- * # Variants
8
- *
9
- * This module ships in two physical variants on disk, selected per consumer
10
- * by the bundler / runtime:
11
- *
12
- * - `platformCrypto.js` — this file. Used by Node.js, Vite, webpack,
13
- * Rollup, esbuild, and anything that does
14
- * not match Metro's `*.native.js`
15
- * source-extension preference.
16
- * - `platformCrypto.native.js` — sibling file. Picked up automatically by
17
- * Metro's resolver (which prefers
18
- * `*.<platform>.js` and `*.native.js` over
19
- * plain `*.js` when `preferNativePlatform`
20
- * is true — Expo sets this for all non-web
21
- * builds).
22
- *
23
- * The `package.json#exports` map also declares a `"react-native"` condition
24
- * pointing at the same `dist/esm/index.js` entry — that entry transitively
25
- * imports `./platformCrypto`, and Metro's per-file source-extension lookup
26
- * substitutes the `.native.js` sibling automatically inside `dist/`. This
27
- * means consumers never have to add resolver shims; Metro Just Works.
28
- *
29
- * Both variants expose the EXACT same public API; importers don't need to know
30
- * which one they got. The variant difference is purely about which underlying
31
- * native modules each one references:
32
- *
33
- * ┌──────────────────┬───────────────────────┬───────────────────────────────┐
34
- * │ Function │ Default variant │ React Native variant │
35
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
36
- * │ loadNodeCrypto │ `await import('crypto')` (Node built-in) │
37
- * │ │ │ throws — Node crypto is not │
38
- * │ │ │ available on Hermes/RN │
39
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
40
- * │ loadExpoCrypto │ throws — expo-crypto │ static `import 'expo-crypto'` │
41
- * │ │ is not part of a │ │
42
- * │ │ Node/Vite bundle │ │
43
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
44
- * │ loadSecureStore │ throws (web/Node have │ static `import 'expo-secure-` │
45
- * │ │ their own storage) │ store' │
46
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
47
- * │ loadAsyncStorage │ throws (web/Node have │ static `import '@react- │
48
- * │ │ their own storage) │ native-async-storage/...' │
49
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
50
- * │ getRandomBytesRN │ throws (RN-only) │ direct call into expo-crypto │
51
- * └──────────────────┴───────────────────────┴───────────────────────────────┘
52
- *
53
- * Crucially, the default variant references ONLY Node's `'crypto'`. It never
54
- * mentions `expo-*` or `@react-native-async-storage/*` — so Vite, webpack,
55
- * esbuild, Rollup, and Node itself can bundle / require it without ever
56
- * attempting to resolve those RN-only packages.
57
- *
58
- * The React Native variant references ONLY the RN packages. It never
59
- * mentions `'crypto'` — so Metro and Hermes have nothing to choke on.
60
- *
61
- * # Why not a single file with dynamic import?
62
- *
63
- * A previous iteration used a "bundler-opaque" `new Function('s', 'return
64
- * import(s)')` trick so a single file could service every platform. It
65
- * bundled cleanly on Metro but Hermes refused to PARSE the resulting
66
- * `import()` expression inside a Function-constructor body
67
- * (`SyntaxError: Invalid expression encountered` at the `(` of `import(`).
68
- * The platform-extension split is the only approach that lets each runtime
69
- * see a file containing only specifiers it can understand — no tricks, no
70
- * runtime parsing risks.
71
- */
72
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
73
- if (k2 === undefined) k2 = k;
74
- var desc = Object.getOwnPropertyDescriptor(m, k);
75
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
76
- desc = { enumerable: true, get: function() { return m[k]; } };
77
- }
78
- Object.defineProperty(o, k2, desc);
79
- }) : (function(o, m, k, k2) {
80
- if (k2 === undefined) k2 = k;
81
- o[k2] = m[k];
82
- }));
83
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
84
- Object.defineProperty(o, "default", { enumerable: true, value: v });
85
- }) : function(o, v) {
86
- o["default"] = v;
87
- });
88
- var __importStar = (this && this.__importStar) || (function () {
89
- var ownKeys = function(o) {
90
- ownKeys = Object.getOwnPropertyNames || function (o) {
91
- var ar = [];
92
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
93
- return ar;
94
- };
95
- return ownKeys(o);
96
- };
97
- return function (mod) {
98
- if (mod && mod.__esModule) return mod;
99
- var result = {};
100
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
101
- __setModuleDefault(result, mod);
102
- return result;
103
- };
104
- })();
105
- Object.defineProperty(exports, "__esModule", { value: true });
106
- exports.loadNodeCrypto = loadNodeCrypto;
107
- exports.loadExpoCrypto = loadExpoCrypto;
108
- exports.loadSecureStore = loadSecureStore;
109
- exports.loadAsyncStorage = loadAsyncStorage;
110
- exports.getRandomBytesRN = getRandomBytesRN;
111
- const platform_1 = require("./platform");
112
- // ---------------------------------------------------------------------------
113
- // Node `crypto` — Node built-in
114
- //
115
- // `await import('crypto')` here is a real, static-from-tsc's-perspective
116
- // dynamic import. Node ESM, Vite, webpack, and esbuild all resolve it fine.
117
- // Metro never sees this file because the `.react-native.js` sibling shadows
118
- // it, so Metro never tries to resolve `'crypto'`.
119
- // ---------------------------------------------------------------------------
120
- let cachedNodeCrypto = null;
121
- async function loadNodeCrypto() {
122
- if (cachedNodeCrypto) {
123
- return cachedNodeCrypto;
124
- }
125
- cachedNodeCrypto = await Promise.resolve().then(() => __importStar(require('node:crypto')));
126
- return cachedNodeCrypto;
127
- }
128
- // ---------------------------------------------------------------------------
129
- // RN-only modules — never called from this variant.
130
- //
131
- // These throw a clear error if anything ever reaches them outside RN. In
132
- // practice every caller gates with `isReactNative()` before calling, so
133
- // these are belt-and-braces.
134
- // ---------------------------------------------------------------------------
135
- function notReactNativeError(module) {
136
- return new Error(`[oxy.platformCrypto] Tried to load '${module}' 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.`);
137
- }
138
- async function loadExpoCrypto() {
139
- if ((0, platform_1.isReactNative)()) {
140
- // Should be unreachable: when running on RN, Metro / the `react-native`
141
- // exports condition serves the sibling variant. If we got here, the
142
- // package-exports map is misconfigured for this host. Throw with a
143
- // helpful diagnostic rather than fall back to a broken dynamic import.
144
- throw new Error('[oxy.platformCrypto] React Native runtime resolved the default ' +
145
- '(non-RN) variant of @oxyhq/core/utils/platformCrypto. Check the ' +
146
- "consumer's bundler resolution — Metro should pick the sibling " +
147
- '.react-native.js file via package exports.');
148
- }
149
- throw notReactNativeError('expo-crypto');
150
- }
151
- async function loadSecureStore() {
152
- throw notReactNativeError('expo-secure-store');
153
- }
154
- async function loadAsyncStorage() {
155
- throw notReactNativeError('@react-native-async-storage/async-storage');
156
- }
157
- /**
158
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`. Only available
159
- * in the React Native variant. The default variant throws because Node and
160
- * browsers have their own native CSPRNGs (`crypto.randomBytes` and
161
- * `crypto.getRandomValues` respectively) — callers should use those.
162
- */
163
- function getRandomBytesRN(_byteCount) {
164
- throw notReactNativeError('expo-crypto.getRandomBytes (sync)');
165
- }
@@ -1,123 +0,0 @@
1
- "use strict";
2
- /**
3
- * Platform Crypto / Storage — React Native Variant
4
- *
5
- * Companion to `./platformCrypto.ts`. See the doc-comment at the top of that
6
- * file for the full design.
7
- *
8
- * Metro auto-selects this file in any non-web build (`preferNativePlatform`
9
- * is `true` for iOS / Android, so `*.native.js` shadows `*.js` during
10
- * source-extension resolution inside `node_modules/@oxyhq/core/dist/`). On
11
- * iOS / Android `<base>.ios.js` / `<base>.android.js` would shadow this file
12
- * if they existed, but they don't — `.native.js` is the shared RN variant.
13
- *
14
- * - The default variant references Node's `'crypto'` and would crash Metro
15
- * if bundled into an RN app.
16
- * - This variant references the RN-only modules (`expo-crypto`,
17
- * `expo-secure-store`, `@react-native-async-storage/async-storage`)
18
- * as static imports, so Metro and Hermes both resolve and parse them
19
- * cleanly.
20
- *
21
- * Both variants expose the same surface; importers don't care which one
22
- * they got.
23
- *
24
- * # Why static imports?
25
- *
26
- * Every RN consumer of `@oxyhq/core` already lists or transitively pulls
27
- * in `expo-crypto`, `expo-secure-store`, and
28
- * `@react-native-async-storage/async-storage` (they're stable Expo modules
29
- * present in `services`, `accounts`, `inbox`, and `test-app`). A static
30
- * import is what Metro wants to see anyway, and Hermes parses it like any
31
- * other ES module — no `Function`-constructor parser exotic-mode involved.
32
- *
33
- * This is also clearer to debug: Metro fails up-front with a normal
34
- * unresolved-module error if a consumer is missing a peer dep, instead of
35
- * a confusing runtime throw the first time a code path that needs the
36
- * module is exercised.
37
- */
38
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
39
- if (k2 === undefined) k2 = k;
40
- var desc = Object.getOwnPropertyDescriptor(m, k);
41
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
42
- desc = { enumerable: true, get: function() { return m[k]; } };
43
- }
44
- Object.defineProperty(o, k2, desc);
45
- }) : (function(o, m, k, k2) {
46
- if (k2 === undefined) k2 = k;
47
- o[k2] = m[k];
48
- }));
49
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
50
- Object.defineProperty(o, "default", { enumerable: true, value: v });
51
- }) : function(o, v) {
52
- o["default"] = v;
53
- });
54
- var __importStar = (this && this.__importStar) || (function () {
55
- var ownKeys = function(o) {
56
- ownKeys = Object.getOwnPropertyNames || function (o) {
57
- var ar = [];
58
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
59
- return ar;
60
- };
61
- return ownKeys(o);
62
- };
63
- return function (mod) {
64
- if (mod && mod.__esModule) return mod;
65
- var result = {};
66
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
67
- __setModuleDefault(result, mod);
68
- return result;
69
- };
70
- })();
71
- var __importDefault = (this && this.__importDefault) || function (mod) {
72
- return (mod && mod.__esModule) ? mod : { "default": mod };
73
- };
74
- Object.defineProperty(exports, "__esModule", { value: true });
75
- exports.loadNodeCrypto = loadNodeCrypto;
76
- exports.loadExpoCrypto = loadExpoCrypto;
77
- exports.loadSecureStore = loadSecureStore;
78
- exports.loadAsyncStorage = loadAsyncStorage;
79
- exports.getRandomBytesRN = getRandomBytesRN;
80
- const ExpoCrypto = __importStar(require("expo-crypto"));
81
- const SecureStore = __importStar(require("expo-secure-store"));
82
- const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
83
- // ---------------------------------------------------------------------------
84
- // Node `crypto` — never available in RN.
85
- // ---------------------------------------------------------------------------
86
- async function loadNodeCrypto() {
87
- // Unreachable in practice: every caller gates with `isNodeJS()` before
88
- // invoking this. If it somehow does fire, throw immediately with a clear
89
- // diagnostic rather than letting Metro / Hermes attempt to find a
90
- // non-existent module at runtime.
91
- throw new Error("[oxy.platformCrypto] Node's built-in 'crypto' module is not available " +
92
- 'in a React Native runtime. Use the RN-specific helpers ' +
93
- '(loadExpoCrypto, getRandomBytesRN) or the Web Crypto API (`globalThis.crypto`).');
94
- }
95
- // ---------------------------------------------------------------------------
96
- // expo-crypto — RN cryptographic primitives.
97
- // ---------------------------------------------------------------------------
98
- async function loadExpoCrypto() {
99
- return ExpoCrypto;
100
- }
101
- // ---------------------------------------------------------------------------
102
- // expo-secure-store — RN keychain / keystore.
103
- // ---------------------------------------------------------------------------
104
- async function loadSecureStore() {
105
- return SecureStore;
106
- }
107
- async function loadAsyncStorage() {
108
- // Mirror the shape callers historically used (`module.default.<method>`)
109
- // so the call sites don't have to know whether the underlying module
110
- // ships ESM or CJS-with-default.
111
- const storage = async_storage_1.default;
112
- return {
113
- default: storage,
114
- };
115
- }
116
- /**
117
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`. Available
118
- * synchronously because `expo-crypto` is statically imported by this file
119
- * — no async initialization race.
120
- */
121
- function getRandomBytesRN(byteCount) {
122
- return ExpoCrypto.getRandomBytes(byteCount);
123
- }
@@ -1,104 +0,0 @@
1
- /**
2
- * Canonical JSON (RFC 8785 / JCS-style) serialization.
3
- *
4
- * `canonicalize(value)` produces a deterministic string for any JSON-compatible
5
- * value so that a client which SIGNS a record and a server which VERIFIES it
6
- * agree byte-for-byte on the signing input — regardless of the order in which
7
- * object keys happen to be written, how the value was deserialized, or which
8
- * runtime built it.
9
- *
10
- * This is the load-bearing primitive for the self-sovereign identity layer's
11
- * signed records (`SignatureService.signRecord` + the API's record-verify path):
12
- * both sides import THIS function from `@oxyhq/core`, so cross-implementation
13
- * number/string formatting differences cannot cause a verify mismatch.
14
- *
15
- * Rules (the JSON Canonicalization Scheme subset we need):
16
- * - Objects: keys are sorted (ascending, by UTF-16 code unit — the default
17
- * `Array.prototype.sort` order) and serialized recursively. Properties whose
18
- * value is `undefined`, a function, or a symbol are OMITTED (matching
19
- * `JSON.stringify` object semantics).
20
- * - Arrays: element order is PRESERVED; `undefined`/function/symbol elements
21
- * serialize to `null` (matching `JSON.stringify` array semantics).
22
- * - `null`, booleans, strings, and finite numbers serialize via the standard
23
- * JSON representation.
24
- * - Values exposing a `toJSON()` method (e.g. `Date`) are replaced by its
25
- * result first, then serialized — so a `Date` and its ISO-string equivalent
26
- * canonicalize identically (the wire always carries the string form).
27
- * - Non-finite numbers (`NaN`, `Infinity`) and `bigint` are not part of the
28
- * JSON data model and throw, rather than silently producing `null`.
29
- *
30
- * Platform-agnostic — zero dependencies, no `require()`, no react/react-native/
31
- * expo. Safe in the dual CJS + ESM build.
32
- */
33
- function hasToJSON(value) {
34
- return typeof value.toJSON === 'function';
35
- }
36
- /**
37
- * Serialize a single value into its canonical JSON fragment. Recursive; called
38
- * on each nested member. Object keys are sorted at every level.
39
- */
40
- function serialize(value) {
41
- if (value === null) {
42
- return 'null';
43
- }
44
- const valueType = typeof value;
45
- if (valueType === 'number') {
46
- if (!Number.isFinite(value)) {
47
- throw new Error('canonicalize: non-finite numbers cannot be serialized');
48
- }
49
- return JSON.stringify(value);
50
- }
51
- if (valueType === 'string' || valueType === 'boolean') {
52
- return JSON.stringify(value);
53
- }
54
- if (valueType === 'bigint') {
55
- throw new Error('canonicalize: bigint values cannot be serialized');
56
- }
57
- if (Array.isArray(value)) {
58
- const items = value.map((item) => {
59
- const itemType = typeof item;
60
- // JSON array semantics: undefined / function / symbol become null so the
61
- // element positions (and therefore the array length) are preserved.
62
- if (item === undefined || itemType === 'function' || itemType === 'symbol') {
63
- return 'null';
64
- }
65
- return serialize(item);
66
- });
67
- return `[${items.join(',')}]`;
68
- }
69
- if (valueType === 'object') {
70
- const obj = value;
71
- if (hasToJSON(obj)) {
72
- return serialize(obj.toJSON());
73
- }
74
- const record = obj;
75
- const parts = [];
76
- for (const key of Object.keys(record).sort()) {
77
- const member = record[key];
78
- const memberType = typeof member;
79
- // JSON object semantics: properties with undefined / function / symbol
80
- // values are omitted entirely.
81
- if (member === undefined || memberType === 'function' || memberType === 'symbol') {
82
- continue;
83
- }
84
- parts.push(`${JSON.stringify(key)}:${serialize(member)}`);
85
- }
86
- return `{${parts.join(',')}}`;
87
- }
88
- // undefined / function / symbol at the top level have no JSON representation.
89
- throw new Error(`canonicalize: cannot serialize a value of type ${valueType}`);
90
- }
91
- /**
92
- * Produce the canonical JSON string for `value`.
93
- *
94
- * Deterministic: two structurally-equal values yield identical strings even if
95
- * their object keys were written in different orders. Use this — never an
96
- * ad-hoc `JSON.stringify` of a hand-sorted object — as the signing input for
97
- * signed records, so client signing and server verification cannot drift.
98
- *
99
- * @throws if `value` (or any nested member used as the top-level/primitive)
100
- * contains a non-finite number or a `bigint`, which have no JSON form.
101
- */
102
- export function canonicalize(value) {
103
- return serialize(value);
104
- }
@@ -1,125 +0,0 @@
1
- /**
2
- * Platform Crypto / Storage — Default Variant (Node.js, Browser, generic bundlers)
3
- *
4
- * Provides lazy access to platform-specific crypto and storage modules.
5
- *
6
- * # Variants
7
- *
8
- * This module ships in two physical variants on disk, selected per consumer
9
- * by the bundler / runtime:
10
- *
11
- * - `platformCrypto.js` — this file. Used by Node.js, Vite, webpack,
12
- * Rollup, esbuild, and anything that does
13
- * not match Metro's `*.native.js`
14
- * source-extension preference.
15
- * - `platformCrypto.native.js` — sibling file. Picked up automatically by
16
- * Metro's resolver (which prefers
17
- * `*.<platform>.js` and `*.native.js` over
18
- * plain `*.js` when `preferNativePlatform`
19
- * is true — Expo sets this for all non-web
20
- * builds).
21
- *
22
- * The `package.json#exports` map also declares a `"react-native"` condition
23
- * pointing at the same `dist/esm/index.js` entry — that entry transitively
24
- * imports `./platformCrypto`, and Metro's per-file source-extension lookup
25
- * substitutes the `.native.js` sibling automatically inside `dist/`. This
26
- * means consumers never have to add resolver shims; Metro Just Works.
27
- *
28
- * Both variants expose the EXACT same public API; importers don't need to know
29
- * which one they got. The variant difference is purely about which underlying
30
- * native modules each one references:
31
- *
32
- * ┌──────────────────┬───────────────────────┬───────────────────────────────┐
33
- * │ Function │ Default variant │ React Native variant │
34
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
35
- * │ loadNodeCrypto │ `await import('crypto')` (Node built-in) │
36
- * │ │ │ throws — Node crypto is not │
37
- * │ │ │ available on Hermes/RN │
38
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
39
- * │ loadExpoCrypto │ throws — expo-crypto │ static `import 'expo-crypto'` │
40
- * │ │ is not part of a │ │
41
- * │ │ Node/Vite bundle │ │
42
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
43
- * │ loadSecureStore │ throws (web/Node have │ static `import 'expo-secure-` │
44
- * │ │ their own storage) │ store' │
45
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
46
- * │ loadAsyncStorage │ throws (web/Node have │ static `import '@react- │
47
- * │ │ their own storage) │ native-async-storage/...' │
48
- * ├──────────────────┼───────────────────────┼───────────────────────────────┤
49
- * │ getRandomBytesRN │ throws (RN-only) │ direct call into expo-crypto │
50
- * └──────────────────┴───────────────────────┴───────────────────────────────┘
51
- *
52
- * Crucially, the default variant references ONLY Node's `'crypto'`. It never
53
- * mentions `expo-*` or `@react-native-async-storage/*` — so Vite, webpack,
54
- * esbuild, Rollup, and Node itself can bundle / require it without ever
55
- * attempting to resolve those RN-only packages.
56
- *
57
- * The React Native variant references ONLY the RN packages. It never
58
- * mentions `'crypto'` — so Metro and Hermes have nothing to choke on.
59
- *
60
- * # Why not a single file with dynamic import?
61
- *
62
- * A previous iteration used a "bundler-opaque" `new Function('s', 'return
63
- * import(s)')` trick so a single file could service every platform. It
64
- * bundled cleanly on Metro but Hermes refused to PARSE the resulting
65
- * `import()` expression inside a Function-constructor body
66
- * (`SyntaxError: Invalid expression encountered` at the `(` of `import(`).
67
- * The platform-extension split is the only approach that lets each runtime
68
- * see a file containing only specifiers it can understand — no tricks, no
69
- * runtime parsing risks.
70
- */
71
- import { isReactNative } from './platform.js';
72
- // ---------------------------------------------------------------------------
73
- // Node `crypto` — Node built-in
74
- //
75
- // `await import('crypto')` here is a real, static-from-tsc's-perspective
76
- // dynamic import. Node ESM, Vite, webpack, and esbuild all resolve it fine.
77
- // Metro never sees this file because the `.react-native.js` sibling shadows
78
- // it, so Metro never tries to resolve `'crypto'`.
79
- // ---------------------------------------------------------------------------
80
- let cachedNodeCrypto = null;
81
- export async function loadNodeCrypto() {
82
- if (cachedNodeCrypto) {
83
- return cachedNodeCrypto;
84
- }
85
- cachedNodeCrypto = await import('node:crypto');
86
- return cachedNodeCrypto;
87
- }
88
- // ---------------------------------------------------------------------------
89
- // RN-only modules — never called from this variant.
90
- //
91
- // These throw a clear error if anything ever reaches them outside RN. In
92
- // practice every caller gates with `isReactNative()` before calling, so
93
- // these are belt-and-braces.
94
- // ---------------------------------------------------------------------------
95
- function notReactNativeError(module) {
96
- return new Error(`[oxy.platformCrypto] Tried to load '${module}' 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.`);
97
- }
98
- export async function loadExpoCrypto() {
99
- if (isReactNative()) {
100
- // Should be unreachable: when running on RN, Metro / the `react-native`
101
- // exports condition serves the sibling variant. If we got here, the
102
- // package-exports map is misconfigured for this host. Throw with a
103
- // helpful diagnostic rather than fall back to a broken dynamic import.
104
- throw new Error('[oxy.platformCrypto] React Native runtime resolved the default ' +
105
- '(non-RN) variant of @oxyhq/core/utils/platformCrypto. Check the ' +
106
- "consumer's bundler resolution — Metro should pick the sibling " +
107
- '.react-native.js file via package exports.');
108
- }
109
- throw notReactNativeError('expo-crypto');
110
- }
111
- export async function loadSecureStore() {
112
- throw notReactNativeError('expo-secure-store');
113
- }
114
- export async function loadAsyncStorage() {
115
- throw notReactNativeError('@react-native-async-storage/async-storage');
116
- }
117
- /**
118
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`. Only available
119
- * in the React Native variant. The default variant throws because Node and
120
- * browsers have their own native CSPRNGs (`crypto.randomBytes` and
121
- * `crypto.getRandomValues` respectively) — callers should use those.
122
- */
123
- export function getRandomBytesRN(_byteCount) {
124
- throw notReactNativeError('expo-crypto.getRandomBytes (sync)');
125
- }
@@ -1,80 +0,0 @@
1
- /**
2
- * Platform Crypto / Storage — React Native Variant
3
- *
4
- * Companion to `./platformCrypto.ts`. See the doc-comment at the top of that
5
- * file for the full design.
6
- *
7
- * Metro auto-selects this file in any non-web build (`preferNativePlatform`
8
- * is `true` for iOS / Android, so `*.native.js` shadows `*.js` during
9
- * source-extension resolution inside `node_modules/@oxyhq/core/dist/`). On
10
- * iOS / Android `<base>.ios.js` / `<base>.android.js` would shadow this file
11
- * if they existed, but they don't — `.native.js` is the shared RN variant.
12
- *
13
- * - The default variant references Node's `'crypto'` and would crash Metro
14
- * if bundled into an RN app.
15
- * - This variant references the RN-only modules (`expo-crypto`,
16
- * `expo-secure-store`, `@react-native-async-storage/async-storage`)
17
- * as static imports, so Metro and Hermes both resolve and parse them
18
- * cleanly.
19
- *
20
- * Both variants expose the same surface; importers don't care which one
21
- * they got.
22
- *
23
- * # Why static imports?
24
- *
25
- * Every RN consumer of `@oxyhq/core` already lists or transitively pulls
26
- * in `expo-crypto`, `expo-secure-store`, and
27
- * `@react-native-async-storage/async-storage` (they're stable Expo modules
28
- * present in `services`, `accounts`, `inbox`, and `test-app`). A static
29
- * import is what Metro wants to see anyway, and Hermes parses it like any
30
- * other ES module — no `Function`-constructor parser exotic-mode involved.
31
- *
32
- * This is also clearer to debug: Metro fails up-front with a normal
33
- * unresolved-module error if a consumer is missing a peer dep, instead of
34
- * a confusing runtime throw the first time a code path that needs the
35
- * module is exercised.
36
- */
37
- import * as ExpoCrypto from 'expo-crypto';
38
- import * as SecureStore from 'expo-secure-store';
39
- import AsyncStorage from '@react-native-async-storage/async-storage';
40
- // ---------------------------------------------------------------------------
41
- // Node `crypto` — never available in RN.
42
- // ---------------------------------------------------------------------------
43
- export async function loadNodeCrypto() {
44
- // Unreachable in practice: every caller gates with `isNodeJS()` before
45
- // invoking this. If it somehow does fire, throw immediately with a clear
46
- // diagnostic rather than letting Metro / Hermes attempt to find a
47
- // non-existent module at runtime.
48
- throw new Error("[oxy.platformCrypto] Node's built-in 'crypto' module is not available " +
49
- 'in a React Native runtime. Use the RN-specific helpers ' +
50
- '(loadExpoCrypto, getRandomBytesRN) or the Web Crypto API (`globalThis.crypto`).');
51
- }
52
- // ---------------------------------------------------------------------------
53
- // expo-crypto — RN cryptographic primitives.
54
- // ---------------------------------------------------------------------------
55
- export async function loadExpoCrypto() {
56
- return ExpoCrypto;
57
- }
58
- // ---------------------------------------------------------------------------
59
- // expo-secure-store — RN keychain / keystore.
60
- // ---------------------------------------------------------------------------
61
- export async function loadSecureStore() {
62
- return SecureStore;
63
- }
64
- export async function loadAsyncStorage() {
65
- // Mirror the shape callers historically used (`module.default.<method>`)
66
- // so the call sites don't have to know whether the underlying module
67
- // ships ESM or CJS-with-default.
68
- const storage = AsyncStorage;
69
- return {
70
- default: storage,
71
- };
72
- }
73
- /**
74
- * Synchronous random-bytes via `expo-crypto.getRandomBytes`. Available
75
- * synchronously because `expo-crypto` is statically imported by this file
76
- * — no async initialization race.
77
- */
78
- export function getRandomBytesRN(byteCount) {
79
- return ExpoCrypto.getRandomBytes(byteCount);
80
- }
@@ -1,44 +0,0 @@
1
- /**
2
- * Canonical JSON (RFC 8785 / JCS-style) serialization.
3
- *
4
- * `canonicalize(value)` produces a deterministic string for any JSON-compatible
5
- * value so that a client which SIGNS a record and a server which VERIFIES it
6
- * agree byte-for-byte on the signing input — regardless of the order in which
7
- * object keys happen to be written, how the value was deserialized, or which
8
- * runtime built it.
9
- *
10
- * This is the load-bearing primitive for the self-sovereign identity layer's
11
- * signed records (`SignatureService.signRecord` + the API's record-verify path):
12
- * both sides import THIS function from `@oxyhq/core`, so cross-implementation
13
- * number/string formatting differences cannot cause a verify mismatch.
14
- *
15
- * Rules (the JSON Canonicalization Scheme subset we need):
16
- * - Objects: keys are sorted (ascending, by UTF-16 code unit — the default
17
- * `Array.prototype.sort` order) and serialized recursively. Properties whose
18
- * value is `undefined`, a function, or a symbol are OMITTED (matching
19
- * `JSON.stringify` object semantics).
20
- * - Arrays: element order is PRESERVED; `undefined`/function/symbol elements
21
- * serialize to `null` (matching `JSON.stringify` array semantics).
22
- * - `null`, booleans, strings, and finite numbers serialize via the standard
23
- * JSON representation.
24
- * - Values exposing a `toJSON()` method (e.g. `Date`) are replaced by its
25
- * result first, then serialized — so a `Date` and its ISO-string equivalent
26
- * canonicalize identically (the wire always carries the string form).
27
- * - Non-finite numbers (`NaN`, `Infinity`) and `bigint` are not part of the
28
- * JSON data model and throw, rather than silently producing `null`.
29
- *
30
- * Platform-agnostic — zero dependencies, no `require()`, no react/react-native/
31
- * expo. Safe in the dual CJS + ESM build.
32
- */
33
- /**
34
- * Produce the canonical JSON string for `value`.
35
- *
36
- * Deterministic: two structurally-equal values yield identical strings even if
37
- * their object keys were written in different orders. Use this — never an
38
- * ad-hoc `JSON.stringify` of a hand-sorted object — as the signing input for
39
- * signed records, so client signing and server verification cannot drift.
40
- *
41
- * @throws if `value` (or any nested member used as the top-level/primitive)
42
- * contains a non-finite number or a `bigint`, which have no JSON form.
43
- */
44
- export declare function canonicalize(value: unknown): string;