@oxyhq/core 3.10.1 → 3.12.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.
- package/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/AuthManager.js +9 -2
- package/dist/cjs/HttpService.js +27 -9
- package/dist/cjs/OxyServices.base.js +3 -2
- package/dist/cjs/crypto/canonicalJson.js +107 -0
- package/dist/cjs/crypto/keyManager.js +67 -8
- package/dist/cjs/crypto/signatureService.js +189 -0
- package/dist/cjs/index.js +30 -4
- package/dist/cjs/mixins/OxyServices.assets.js +16 -1
- package/dist/cjs/mixins/OxyServices.auth.js +190 -1
- package/dist/cjs/mixins/OxyServices.civic.js +611 -0
- package/dist/cjs/mixins/OxyServices.identity.js +291 -0
- package/dist/cjs/mixins/OxyServices.sso.js +28 -1
- package/dist/cjs/mixins/OxyServices.user.js +1 -0
- package/dist/cjs/mixins/index.js +6 -0
- package/dist/cjs/server/cors.js +20 -21
- package/dist/cjs/server/rateLimit.js +32 -8
- package/dist/cjs/utils/profileLinks.js +52 -0
- package/dist/cjs/utils/ssoReturn.js +1 -1
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/AuthManager.js +9 -2
- package/dist/esm/HttpService.js +27 -9
- package/dist/esm/OxyServices.base.js +3 -2
- package/dist/esm/crypto/canonicalJson.js +104 -0
- package/dist/esm/crypto/keyManager.js +67 -8
- package/dist/esm/crypto/signatureService.js +187 -0
- package/dist/esm/index.js +19 -1
- package/dist/esm/mixins/OxyServices.assets.js +16 -1
- package/dist/esm/mixins/OxyServices.auth.js +190 -1
- package/dist/esm/mixins/OxyServices.civic.js +605 -0
- package/dist/esm/mixins/OxyServices.identity.js +287 -0
- package/dist/esm/mixins/OxyServices.sso.js +28 -1
- package/dist/esm/mixins/OxyServices.user.js +1 -0
- package/dist/esm/mixins/index.js +6 -0
- package/dist/esm/server/cors.js +20 -21
- package/dist/esm/server/rateLimit.js +32 -8
- package/dist/esm/utils/profileLinks.js +49 -0
- package/dist/esm/utils/ssoReturn.js +1 -1
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/HttpService.d.ts +3 -0
- package/dist/types/OxyServices.d.ts +2 -2
- package/dist/types/crypto/canonicalJson.d.ts +44 -0
- package/dist/types/crypto/keyManager.d.ts +7 -0
- package/dist/types/crypto/signatureService.d.ts +112 -0
- package/dist/types/index.d.ts +10 -2
- package/dist/types/mixins/OxyServices.auth.d.ts +136 -0
- package/dist/types/mixins/OxyServices.civic.d.ts +512 -0
- package/dist/types/mixins/OxyServices.identity.d.ts +249 -0
- package/dist/types/mixins/OxyServices.sso.d.ts +4 -1
- package/dist/types/mixins/index.d.ts +3 -1
- package/dist/types/models/interfaces.d.ts +3 -0
- package/dist/types/server/cors.d.ts +5 -5
- package/dist/types/utils/profileLinks.d.ts +36 -0
- package/dist/types/utils/ssoReturn.d.ts +1 -1
- package/package.json +2 -2
- package/src/AuthManager.ts +8 -2
- package/src/HttpService.ts +36 -8
- package/src/OxyServices.base.ts +3 -2
- package/src/OxyServices.ts +1 -1
- package/src/__tests__/authManager.security.test.ts +31 -0
- package/src/__tests__/httpServiceCsrf.test.ts +75 -0
- package/src/crypto/__tests__/canonicalJson.test.ts +116 -0
- package/src/crypto/__tests__/keyManager.atomicity.test.ts +41 -2
- package/src/crypto/__tests__/signChallengeShared.test.ts +64 -0
- package/src/crypto/__tests__/signedRecord.test.ts +345 -0
- package/src/crypto/canonicalJson.ts +120 -0
- package/src/crypto/keyManager.ts +62 -12
- package/src/crypto/signatureService.ts +225 -0
- package/src/index.ts +55 -2
- package/src/mixins/OxyServices.assets.ts +16 -1
- package/src/mixins/OxyServices.auth.ts +309 -1
- package/src/mixins/OxyServices.civic.ts +956 -0
- package/src/mixins/OxyServices.identity.ts +445 -0
- package/src/mixins/OxyServices.sso.ts +30 -1
- package/src/mixins/OxyServices.user.ts +1 -0
- package/src/mixins/__tests__/OxyServices.civic.test.ts +1097 -0
- package/src/mixins/__tests__/OxyServices.identity.test.ts +364 -0
- package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
- package/src/mixins/__tests__/commonsSignIn.test.ts +277 -0
- package/src/mixins/__tests__/serviceAuth.test.ts +19 -0
- package/src/mixins/__tests__/sso.test.ts +31 -0
- package/src/mixins/index.ts +8 -0
- package/src/models/interfaces.ts +3 -0
- package/src/server/__tests__/cors.test.ts +5 -1
- package/src/server/__tests__/rateLimit.test.ts +116 -0
- package/src/server/cors.ts +25 -20
- package/src/server/rateLimit.ts +39 -8
- package/src/utils/__tests__/consumeSsoReturn.test.ts +1 -1
- package/src/utils/__tests__/profileLinks.test.ts +126 -0
- package/src/utils/__tests__/ssoReturn.test.ts +1 -1
- package/src/utils/profileLinks.ts +74 -0
- package/src/utils/ssoReturn.ts +2 -2
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseIdPayload = parseIdPayload;
|
|
4
|
+
exports.parseAttestPayload = parseAttestPayload;
|
|
5
|
+
exports.verifyPublicCardAttestation = verifyPublicCardAttestation;
|
|
6
|
+
exports.OxyServicesCivicMixin = OxyServicesCivicMixin;
|
|
7
|
+
const canonicalJson_1 = require("../crypto/canonicalJson");
|
|
8
|
+
const signatureService_1 = require("../crypto/signatureService");
|
|
9
|
+
const OxyServices_identity_1 = require("./OxyServices.identity");
|
|
10
|
+
const mixinHelpers_1 = require("./mixinHelpers");
|
|
11
|
+
/**
|
|
12
|
+
* Validity window of a real-life-attestation QR (`oxycommons://attest?…exp=…`),
|
|
13
|
+
* matching the server's `REAL_LIFE_NONCE_MAX_AGE_MS` ceiling: the QR must be
|
|
14
|
+
* scanned and submitted within this window. The server is authoritative on
|
|
15
|
+
* freshness; this is the client-issued `exp`.
|
|
16
|
+
*/
|
|
17
|
+
const ATTEST_QR_TTL_MS = 10 * 60 * 1000;
|
|
18
|
+
/** AtProto-style collection for a real-life counterparty attestation record. */
|
|
19
|
+
const ATTEST_COLLECTION = 'app.oxy.attestation';
|
|
20
|
+
/** AtProto-style collection for a validator's signed verdict record. */
|
|
21
|
+
const VALIDATION_COLLECTION = 'app.oxy.validation';
|
|
22
|
+
/** AtProto-style collection for a personhood vouch record. */
|
|
23
|
+
const VOUCH_COLLECTION = 'app.oxy.vouch';
|
|
24
|
+
/**
|
|
25
|
+
* AtProto-style collection (NSID) for a verifiable credential record — matches
|
|
26
|
+
* the server's `CREDENTIAL_COLLECTION`. Each credential is its own chain entry,
|
|
27
|
+
* so the per-credential `rkey` MUST be unique (a fresh nonce), unlike the
|
|
28
|
+
* one-per-subject vouch keyed on the subject DID.
|
|
29
|
+
*/
|
|
30
|
+
const CREDENTIAL_COLLECTION = 'app.oxy.credential';
|
|
31
|
+
/**
|
|
32
|
+
* The W3C base VC type (`CREDENTIAL_BASE_TYPE` on the server) that MUST be
|
|
33
|
+
* present in every credential's `types`. The client prepends it when the caller
|
|
34
|
+
* omits it; the server rejects a credential record lacking it (`missing_base_type`).
|
|
35
|
+
*/
|
|
36
|
+
const CREDENTIAL_BASE_TYPE = 'VerifiableCredential';
|
|
37
|
+
/**
|
|
38
|
+
* Cache-key prefix of every credential read — the holder list
|
|
39
|
+
* (`GET /civic/credentials/:holderUserId`) and the by-record verify
|
|
40
|
+
* (`GET /civic/credentials/by-record/:recordId/verify`) both start with it.
|
|
41
|
+
* Swept after an issue / revoke so a re-read reflects the new credential set /
|
|
42
|
+
* status instead of a stale cached one. The identity tag is a key SUFFIX, so
|
|
43
|
+
* this prefix invalidates the resource for every cached identity.
|
|
44
|
+
*/
|
|
45
|
+
const CREDENTIAL_CACHE_PREFIX = 'GET:/civic/credentials/';
|
|
46
|
+
/**
|
|
47
|
+
* Cache-key prefix of every personhood-status read (`GET /civic/personhood/:userId`).
|
|
48
|
+
* Swept after a vouch / withdraw so a re-read reflects the recomputed snapshot
|
|
49
|
+
* instead of a stale cached one. The identity tag is a key SUFFIX, so this
|
|
50
|
+
* prefix invalidates the resource for every cached identity.
|
|
51
|
+
*/
|
|
52
|
+
const PERSONHOOD_CACHE_PREFIX = 'GET:/civic/personhood/';
|
|
53
|
+
/**
|
|
54
|
+
* Cache-key prefix of the current user's `GET /users/me`. Swept after a vouch /
|
|
55
|
+
* withdraw because a subject crossing the personhood threshold flips their
|
|
56
|
+
* mirrored `User.verified` flag.
|
|
57
|
+
*/
|
|
58
|
+
const USERS_ME_CACHE_PREFIX = 'GET:/users/me';
|
|
59
|
+
/** URI scheme/host that introduces a Commons Oxy ID card payload. */
|
|
60
|
+
const CARD_MATCHER = /^oxycommons:\/\/card(?:[/?#]|$)/i;
|
|
61
|
+
/** URI scheme/host that introduces a real-life counterparty attestation payload. */
|
|
62
|
+
const ATTEST_MATCHER = /^oxycommons:\/\/attest(?:[/?#]|$)/i;
|
|
63
|
+
/**
|
|
64
|
+
* Minimal, allocation-light query-string parser (no `URL` / `URLSearchParams`)
|
|
65
|
+
* so it runs identically under Hermes and jsdom — mirrors the robustness of the
|
|
66
|
+
* "Sign in with Oxy" approval-link parser. Shared by every `oxycommons://…`
|
|
67
|
+
* payload parser in this module.
|
|
68
|
+
*/
|
|
69
|
+
function parseCommonsQuery(raw) {
|
|
70
|
+
const params = new Map();
|
|
71
|
+
const qIndex = raw.indexOf('?');
|
|
72
|
+
if (qIndex < 0)
|
|
73
|
+
return params;
|
|
74
|
+
let query = raw.slice(qIndex + 1);
|
|
75
|
+
const hashIndex = query.indexOf('#');
|
|
76
|
+
if (hashIndex >= 0)
|
|
77
|
+
query = query.slice(0, hashIndex);
|
|
78
|
+
for (const pair of query.split('&')) {
|
|
79
|
+
if (pair.length === 0)
|
|
80
|
+
continue;
|
|
81
|
+
const eq = pair.indexOf('=');
|
|
82
|
+
const rawKey = eq < 0 ? pair : pair.slice(0, eq);
|
|
83
|
+
const rawValue = eq < 0 ? '' : pair.slice(eq + 1);
|
|
84
|
+
try {
|
|
85
|
+
params.set(decodeURIComponent(rawKey), decodeURIComponent(rawValue.replace(/\+/g, ' ')));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Malformed percent-encoding — keep the raw token rather than throwing, so
|
|
89
|
+
// a single bad field doesn't sink an otherwise valid payload.
|
|
90
|
+
params.set(rawKey, rawValue);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return params;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Parse a scanned / deep-linked Oxy ID payload (`oxycommons://card?did=…`) into
|
|
97
|
+
* the referenced DID. Pure + dependency-free (Hermes-safe, no `URL` global) so
|
|
98
|
+
* Commons (and any scanner) can reuse it without an OxyServices instance.
|
|
99
|
+
*
|
|
100
|
+
* @param raw - The raw scanned string or deep-link URL.
|
|
101
|
+
* @returns `{ did }` when a usable DID is present; `null` for anything else (a
|
|
102
|
+
* non-card scheme, a missing/empty `did`, or non-string input).
|
|
103
|
+
*/
|
|
104
|
+
function parseIdPayload(raw) {
|
|
105
|
+
if (typeof raw !== 'string' || raw.trim().length === 0) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
const value = raw.trim();
|
|
109
|
+
if (!CARD_MATCHER.test(value)) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const did = parseCommonsQuery(value).get('did');
|
|
113
|
+
if (!did || did.length === 0) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return { did };
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Parse a scanned / deep-linked real-life-attestation payload
|
|
120
|
+
* (`oxycommons://attest?subject=…&ctx=…&nonce=…&exp=…`). Pure + dependency-free
|
|
121
|
+
* (Hermes-safe, no `URL` global), mirroring {@link parseIdPayload}, so Commons
|
|
122
|
+
* (and any scanner) can reuse it without an OxyServices instance.
|
|
123
|
+
*
|
|
124
|
+
* @param raw - The raw scanned string or deep-link URL.
|
|
125
|
+
* @returns `{ subjectDid, context, nonce, exp }` when the required fields are
|
|
126
|
+
* present and `exp` is a positive finite number; `null` otherwise (a non-attest
|
|
127
|
+
* scheme, a missing `subject`/`nonce`/`exp`, an unparseable `exp`, or non-string
|
|
128
|
+
* input). `context` defaults to `''` when the QR omits `ctx`.
|
|
129
|
+
*/
|
|
130
|
+
function parseAttestPayload(raw) {
|
|
131
|
+
if (typeof raw !== 'string' || raw.trim().length === 0) {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
const value = raw.trim();
|
|
135
|
+
if (!ATTEST_MATCHER.test(value)) {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const params = parseCommonsQuery(value);
|
|
139
|
+
const subjectDid = params.get('subject');
|
|
140
|
+
const nonce = params.get('nonce');
|
|
141
|
+
const expRaw = params.get('exp');
|
|
142
|
+
if (!subjectDid || !nonce || expRaw === undefined || expRaw.length === 0) {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
const exp = Number(expRaw);
|
|
146
|
+
if (!Number.isFinite(exp) || exp <= 0) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
return { subjectDid, context: params.get('ctx') ?? '', nonce, exp };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Verify the Oxy custodial attestation on a public card.
|
|
153
|
+
*
|
|
154
|
+
* Re-canonicalizes the received `card` (so the order of the JSON keys on the
|
|
155
|
+
* wire is irrelevant; `canonicalize` also omits any `undefined`-valued optional
|
|
156
|
+
* key, matching the server which omits absent keys entirely) and checks the
|
|
157
|
+
* `ES256K-DER-SHA256` signature against `attestation.publicKey`.
|
|
158
|
+
*
|
|
159
|
+
* NEVER throws: `SignatureService.verify` already swallows malformed-input
|
|
160
|
+
* errors and returns `false`, and an absent attestation short-circuits to
|
|
161
|
+
* `false`. A pure, reusable helper (Commons can call it on a cached card).
|
|
162
|
+
*
|
|
163
|
+
* @param card - The card to verify (exactly as received).
|
|
164
|
+
* @param attestation - The card's attestation, or `null` (unsigned ⇒ `false`).
|
|
165
|
+
*/
|
|
166
|
+
async function verifyPublicCardAttestation(card, attestation) {
|
|
167
|
+
if (!attestation) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
const { signature, publicKey } = attestation;
|
|
171
|
+
if (!signature || !publicKey) {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
return signatureService_1.SignatureService.verify((0, canonicalJson_1.canonicalize)(card), signature, publicKey);
|
|
175
|
+
}
|
|
176
|
+
function OxyServicesCivicMixin(Base) {
|
|
177
|
+
return class extends Base {
|
|
178
|
+
constructor(...args) {
|
|
179
|
+
super(...args);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Fetch a user's signed public Oxy ID card and verify the Oxy attestation
|
|
183
|
+
* client-side. Public (no auth required); short-TTL cached.
|
|
184
|
+
*
|
|
185
|
+
* Resolves to `{ card, attestation, verified }`. A bad/absent signature does
|
|
186
|
+
* NOT reject — it yields `verified: false` so the UI can warn. Only a
|
|
187
|
+
* transport failure (the fetch itself) rejects.
|
|
188
|
+
*
|
|
189
|
+
* @param userId - The subject account's Mongo `_id`. URL-encoded into the path.
|
|
190
|
+
*/
|
|
191
|
+
async getPublicCard(userId) {
|
|
192
|
+
try {
|
|
193
|
+
const signed = await this.makeRequest('GET', `/civic/${encodeURIComponent(userId)}/card`, undefined, { cache: true, cacheTTL: mixinHelpers_1.CACHE_TIMES.SHORT });
|
|
194
|
+
const verified = await verifyPublicCardAttestation(signed.card, signed.attestation);
|
|
195
|
+
return { card: signed.card, attestation: signed.attestation, verified };
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
throw this.handleError(error);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Build the Oxy ID QR payload for the current user:
|
|
203
|
+
* `oxycommons://card?did=<did>&v=1`, where `<did>` is the user's Oxy DID
|
|
204
|
+
* (`did:web:oxy.so:u:<userId>`). The QR encodes ONLY the DID (anti-spoof — no
|
|
205
|
+
* trust data); a scanner resolves the signed card via {@link getPublicCard}.
|
|
206
|
+
* Round-trips through {@link parseIdPayload}.
|
|
207
|
+
*
|
|
208
|
+
* Throws if no user is authenticated (no DID to derive).
|
|
209
|
+
*/
|
|
210
|
+
getMyIdPayload() {
|
|
211
|
+
const userId = this.getCurrentUserId();
|
|
212
|
+
if (!userId) {
|
|
213
|
+
throw new Error('No authenticated user — cannot build an Oxy ID payload.');
|
|
214
|
+
}
|
|
215
|
+
return `oxycommons://card?did=${(0, OxyServices_identity_1.buildUserDid)(userId)}&v=1`;
|
|
216
|
+
}
|
|
217
|
+
// =========================================================================
|
|
218
|
+
// FASE 2 — real-life counterparty attestation (HIGH weight)
|
|
219
|
+
// =========================================================================
|
|
220
|
+
/**
|
|
221
|
+
* Build the real-life-attestation QR the current user (A) shows to be
|
|
222
|
+
* attested by a counterparty (B):
|
|
223
|
+
* `oxycommons://attest?subject=<A.did>&ctx=<context>&nonce=<fresh>&exp=<now+10m>`.
|
|
224
|
+
*
|
|
225
|
+
* A fresh crypto-random nonce is minted per call (single-use replay guard);
|
|
226
|
+
* `exp` is `now + 10min` (matching the server ceiling — scan promptly). The
|
|
227
|
+
* QR carries NO trust data; B re-signs and the server is authoritative. The
|
|
228
|
+
* returned `nonce`/`exp` let the displaying screen track which scan completed.
|
|
229
|
+
*
|
|
230
|
+
* Async because a crypto-secure nonce requires the platform RNG (async on
|
|
231
|
+
* native via expo-crypto). Throws if no user is authenticated.
|
|
232
|
+
*
|
|
233
|
+
* @param input.context - An opaque interaction id describing the encounter.
|
|
234
|
+
*/
|
|
235
|
+
async buildAttestQrPayload(input) {
|
|
236
|
+
const userId = this.getCurrentUserId();
|
|
237
|
+
if (!userId) {
|
|
238
|
+
throw new Error('No authenticated user — cannot build an attestation QR.');
|
|
239
|
+
}
|
|
240
|
+
const subject = (0, OxyServices_identity_1.buildUserDid)(userId);
|
|
241
|
+
const nonce = await signatureService_1.SignatureService.generateChallenge();
|
|
242
|
+
const exp = Date.now() + ATTEST_QR_TTL_MS;
|
|
243
|
+
const payload = `oxycommons://attest?subject=${subject}` +
|
|
244
|
+
`&ctx=${encodeURIComponent(input.context)}` +
|
|
245
|
+
`&nonce=${nonce}&exp=${exp}`;
|
|
246
|
+
return { payload, nonce, exp };
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Submit a real-life counterparty attestation as the SCANNER (B): sign a
|
|
250
|
+
* self-issued `real_life_attestation` v2 record on B's own chain
|
|
251
|
+
* (`subject === issuer === B.did`), referencing A via `record.about`, then
|
|
252
|
+
* `POST /civic/attestations`. The server enforces nonce single-use,
|
|
253
|
+
* freshness, graph-exclusion (B is not A's puppet), and the per-pair
|
|
254
|
+
* cooldown, then awards A the HIGH-weight points.
|
|
255
|
+
*
|
|
256
|
+
* NATIVE-ONLY (signs with the on-device key; throws on web / when no
|
|
257
|
+
* identity or no authenticated user). The record is keyed
|
|
258
|
+
* `collection: 'app.oxy.attestation'`, `rkey: <nonce>`.
|
|
259
|
+
*
|
|
260
|
+
* @param input - The parsed QR fields ({@link ParsedAttestPayload}) plus B's
|
|
261
|
+
* optional `geohash` / `biometricOk` support signals.
|
|
262
|
+
*/
|
|
263
|
+
async submitRealLifeAttestation(input) {
|
|
264
|
+
try {
|
|
265
|
+
const envelope = await this._signMyCivicRecordV2('real_life_attestation', {
|
|
266
|
+
about: input.subjectDid,
|
|
267
|
+
context: input.context,
|
|
268
|
+
nonce: input.nonce,
|
|
269
|
+
exp: input.exp,
|
|
270
|
+
...(input.geohash !== undefined ? { geohash: input.geohash } : {}),
|
|
271
|
+
...(input.biometricOk !== undefined ? { biometricOk: input.biometricOk } : {}),
|
|
272
|
+
}, ATTEST_COLLECTION, input.nonce);
|
|
273
|
+
return await this.makeRequest('POST', '/civic/attestations', envelope, { cache: false });
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
throw this.handleError(error);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// =========================================================================
|
|
280
|
+
// FASE 2 — validator / jury (MEDIUM weight)
|
|
281
|
+
// =========================================================================
|
|
282
|
+
/**
|
|
283
|
+
* List the current user's pending jury duties (`GET /civic/validations/inbox`).
|
|
284
|
+
* Auth required; never cached (the inbox is a live queue). Returns `[]` when
|
|
285
|
+
* the caller is on no juries.
|
|
286
|
+
*/
|
|
287
|
+
async getValidatorInbox() {
|
|
288
|
+
try {
|
|
289
|
+
const res = await this.makeRequest('GET', '/civic/validations/inbox', undefined, { cache: false });
|
|
290
|
+
return res.requests ?? [];
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
throw this.handleError(error);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Cast a SIGNED verdict on a validation request as a selected juror: sign a
|
|
298
|
+
* self-issued `validation_verdict` v2 record on the juror's own chain bound
|
|
299
|
+
* to `requestId` + `payloadHash` (so a verdict cannot be replayed onto a
|
|
300
|
+
* different request or an altered payload), then
|
|
301
|
+
* `POST /civic/validations/:id/vote`.
|
|
302
|
+
*
|
|
303
|
+
* NATIVE-ONLY (signs with the on-device key; throws on web / when no
|
|
304
|
+
* identity or no authenticated user). The record is keyed
|
|
305
|
+
* `collection: 'app.oxy.validation'`, `rkey: <requestId>`.
|
|
306
|
+
*
|
|
307
|
+
* @param requestId - The validation request being voted on.
|
|
308
|
+
* @param payloadHash - The request's canonical payload hash (from the inbox);
|
|
309
|
+
* the server rejects a vote whose hash does not match the stored request.
|
|
310
|
+
* @param verdict - `'valid'` | `'invalid'` | `'abstain'`.
|
|
311
|
+
*/
|
|
312
|
+
async submitValidationVote(requestId, payloadHash, verdict) {
|
|
313
|
+
try {
|
|
314
|
+
const envelope = await this._signMyCivicRecordV2('validation_verdict', { requestId, payloadHash, verdict }, VALIDATION_COLLECTION, requestId);
|
|
315
|
+
return await this.makeRequest('POST', `/civic/validations/${encodeURIComponent(requestId)}/vote`, envelope, { cache: false });
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
throw this.handleError(error);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Recuse from a validation request (`POST /civic/validations/:id/deny`): the
|
|
323
|
+
* juror is removed from the jury and the request is re-tallied. Auth
|
|
324
|
+
* required; no signed record (recusal is not an attestation).
|
|
325
|
+
*
|
|
326
|
+
* @param requestId - The validation request to recuse from.
|
|
327
|
+
*/
|
|
328
|
+
async denyValidation(requestId) {
|
|
329
|
+
try {
|
|
330
|
+
return await this.makeRequest('POST', `/civic/validations/${encodeURIComponent(requestId)}/deny`, undefined, { cache: false });
|
|
331
|
+
}
|
|
332
|
+
catch (error) {
|
|
333
|
+
throw this.handleError(error);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// =========================================================================
|
|
337
|
+
// FASE 3 — proof-of-personhood web-of-trust (staked vouch)
|
|
338
|
+
// =========================================================================
|
|
339
|
+
/**
|
|
340
|
+
* Vouch that another user is a real person as the VOUCHER (B): sign a
|
|
341
|
+
* self-issued `personhood_vouch` v2 record on B's own chain
|
|
342
|
+
* (`subject === issuer === B.did`), referencing the subject (A) via
|
|
343
|
+
* `record.about`, then `POST /civic/personhood/vouch`. The server verifies
|
|
344
|
+
* it, enforces the voucher-eligibility (personhood ≥ τ) + graph-exclusion
|
|
345
|
+
* gates, stakes B, awards A `personhood_vouched`, and recomputes A's
|
|
346
|
+
* personhood. The voucher id is resolved server-side from the session — never
|
|
347
|
+
* from the body.
|
|
348
|
+
*
|
|
349
|
+
* The signed record matches the API schema: `{ about, stake?, … }` — note the
|
|
350
|
+
* wire field is `stake` (the caller's `stakeAmount` request), distinct from
|
|
351
|
+
* the server-clamped `VouchResult.stakeAmount` it returns. The optional
|
|
352
|
+
* `biometricOk` is carried as a signed support signal.
|
|
353
|
+
*
|
|
354
|
+
* NATIVE-ONLY (signs with the on-device key; throws on web / when no identity
|
|
355
|
+
* or no authenticated user). The record is keyed
|
|
356
|
+
* `collection: 'app.oxy.vouch'`, `rkey: <subjectDid>` (one vouch per subject
|
|
357
|
+
* on the voucher's chain — last-writer-wins). After a successful vouch the
|
|
358
|
+
* personhood + `/users/me` GET caches are swept.
|
|
359
|
+
*
|
|
360
|
+
* @param input - The subject DID plus B's optional stake / biometric signal.
|
|
361
|
+
*/
|
|
362
|
+
async vouchForPerson(input) {
|
|
363
|
+
try {
|
|
364
|
+
const envelope = await this._signMyCivicRecordV2('personhood_vouch', {
|
|
365
|
+
about: input.subjectDid,
|
|
366
|
+
...(input.stakeAmount !== undefined ? { stake: input.stakeAmount } : {}),
|
|
367
|
+
...(input.biometricOk !== undefined ? { biometricOk: input.biometricOk } : {}),
|
|
368
|
+
}, VOUCH_COLLECTION, input.subjectDid);
|
|
369
|
+
const result = await this.makeRequest('POST', '/civic/personhood/vouch', envelope, { cache: false });
|
|
370
|
+
this._sweepPersonhoodCaches();
|
|
371
|
+
return result;
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
throw this.handleError(error);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Withdraw the current user's active vouch for a subject
|
|
379
|
+
* (`DELETE /civic/personhood/vouch/:subjectUserId`). The vouch flips to
|
|
380
|
+
* `withdrawn` server-side and the subject is recomputed (which may demote
|
|
381
|
+
* them below θ). Auth required; no signed record (withdrawal is not an
|
|
382
|
+
* attestation). After a successful withdraw the personhood + `/users/me` GET
|
|
383
|
+
* caches are swept.
|
|
384
|
+
*
|
|
385
|
+
* @param subjectUserId - The subject account's Mongo `_id` (NOT a DID) — the
|
|
386
|
+
* id the server keys the vouch on. URL-encoded into the path.
|
|
387
|
+
*/
|
|
388
|
+
async withdrawVouch(subjectUserId) {
|
|
389
|
+
try {
|
|
390
|
+
const result = await this.makeRequest('DELETE', `/civic/personhood/vouch/${encodeURIComponent(subjectUserId)}`, undefined, { cache: false });
|
|
391
|
+
this._sweepPersonhoodCaches();
|
|
392
|
+
return result;
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
throw this.handleError(error);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Fetch a user's public personhood status snapshot
|
|
400
|
+
* (`GET /civic/personhood/:userId`). Read-only: the server returns the cached
|
|
401
|
+
* snapshot, or a zeroed `unverified` shape (`breakdown`/`updatedAt` null) when
|
|
402
|
+
* none exists yet. Public (no auth required); short-TTL cached.
|
|
403
|
+
*
|
|
404
|
+
* @param userId - The subject account's Mongo `_id`. URL-encoded into the path.
|
|
405
|
+
*/
|
|
406
|
+
async getPersonhood(userId) {
|
|
407
|
+
try {
|
|
408
|
+
return await this.makeRequest('GET', `/civic/personhood/${encodeURIComponent(userId)}`, undefined, { cache: true, cacheTTL: mixinHelpers_1.CACHE_TIMES.SHORT });
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
throw this.handleError(error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Fetch the CURRENT user's personhood status ({@link getPersonhood} for the
|
|
416
|
+
* authenticated user's id). Throws if no user is authenticated.
|
|
417
|
+
*/
|
|
418
|
+
async getMyPersonhood() {
|
|
419
|
+
const userId = this.getCurrentUserId();
|
|
420
|
+
if (!userId) {
|
|
421
|
+
throw new Error('No authenticated user — cannot resolve personhood status.');
|
|
422
|
+
}
|
|
423
|
+
return this.getPersonhood(userId);
|
|
424
|
+
}
|
|
425
|
+
// =========================================================================
|
|
426
|
+
// FASE 4 — verifiable credentials
|
|
427
|
+
// =========================================================================
|
|
428
|
+
/**
|
|
429
|
+
* Issue a verifiable credential as the ISSUER: sign a self-issued
|
|
430
|
+
* `credential` v2 record on the caller's own chain
|
|
431
|
+
* (`subject === issuer === issuer.did`) whose `record.about` is the HOLDER's
|
|
432
|
+
* DID (the W3C `credentialSubject`), then `POST /civic/credentials`. The
|
|
433
|
+
* server verifies the signature + the issuer's CURRENT verification method +
|
|
434
|
+
* chain continuity, stores the signed record, and projects a queryable
|
|
435
|
+
* credential row. All claim data comes from the SIGNED envelope — the issuer
|
|
436
|
+
* id is resolved server-side from the session, never from the body.
|
|
437
|
+
*
|
|
438
|
+
* `'VerifiableCredential'` is ensured present as the base type (prepended
|
|
439
|
+
* when the caller omits it; the server rejects a record missing it). An
|
|
440
|
+
* `expiresAt` ISO string is converted to the epoch-ms the signed record
|
|
441
|
+
* carries (the server rejects a past expiry).
|
|
442
|
+
*
|
|
443
|
+
* NATIVE-ONLY (signs with the on-device key; throws on web / when no identity
|
|
444
|
+
* or no authenticated user). The record is keyed
|
|
445
|
+
* `collection: 'app.oxy.credential'`, `rkey: <fresh unique nonce>` (each
|
|
446
|
+
* credential is a distinct chain entry, so the rkey must be unique per
|
|
447
|
+
* credential). After a successful issue the credential GET caches are swept.
|
|
448
|
+
*
|
|
449
|
+
* @param input - The holder DID, VC types, claims, and optional ISO expiry.
|
|
450
|
+
*/
|
|
451
|
+
async issueCredential(input) {
|
|
452
|
+
try {
|
|
453
|
+
const types = input.types.includes(CREDENTIAL_BASE_TYPE)
|
|
454
|
+
? input.types
|
|
455
|
+
: [CREDENTIAL_BASE_TYPE, ...input.types];
|
|
456
|
+
let expiresAtMs;
|
|
457
|
+
if (input.expiresAt !== undefined) {
|
|
458
|
+
const parsed = Date.parse(input.expiresAt);
|
|
459
|
+
if (Number.isNaN(parsed)) {
|
|
460
|
+
throw new Error('Invalid expiresAt — must be an ISO 8601 date string.');
|
|
461
|
+
}
|
|
462
|
+
expiresAtMs = parsed;
|
|
463
|
+
}
|
|
464
|
+
const record = {
|
|
465
|
+
about: input.holderDid,
|
|
466
|
+
types,
|
|
467
|
+
claims: input.claims,
|
|
468
|
+
...(expiresAtMs !== undefined ? { expiresAt: expiresAtMs } : {}),
|
|
469
|
+
};
|
|
470
|
+
// A fresh crypto-random rkey: every credential is its own chain entry, so
|
|
471
|
+
// (unlike the one-per-subject vouch keyed on the subject DID) the rkey
|
|
472
|
+
// must be unique per credential or a second credential would collide.
|
|
473
|
+
const rkey = await signatureService_1.SignatureService.generateChallenge();
|
|
474
|
+
const envelope = await this._signMyCivicRecordV2('credential', record, CREDENTIAL_COLLECTION, rkey);
|
|
475
|
+
const result = await this.makeRequest('POST', '/civic/credentials', envelope, { cache: false });
|
|
476
|
+
this._sweepCredentialCaches();
|
|
477
|
+
return result;
|
|
478
|
+
}
|
|
479
|
+
catch (error) {
|
|
480
|
+
throw this.handleError(error);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* List a holder's verifiable credentials
|
|
485
|
+
* (`GET /civic/credentials/:holderUserId`), newest first, optionally filtered
|
|
486
|
+
* by stored `status`. Public (credentials are issuer-signed attestations a
|
|
487
|
+
* holder collects to SHOW); short-TTL cached and swept after the caller's own
|
|
488
|
+
* issue / revoke. An unknown holder yields an empty list.
|
|
489
|
+
*
|
|
490
|
+
* @param holderUserId - The holder account's Mongo `_id` (NOT a DID). URL-encoded.
|
|
491
|
+
* @param opts.status - Optional `'active' | 'revoked' | 'expired'` filter.
|
|
492
|
+
*/
|
|
493
|
+
async listCredentials(holderUserId, opts = {}) {
|
|
494
|
+
try {
|
|
495
|
+
const base = `/civic/credentials/${encodeURIComponent(holderUserId)}`;
|
|
496
|
+
const url = opts.status ? `${base}?status=${encodeURIComponent(opts.status)}` : base;
|
|
497
|
+
return await this.makeRequest('GET', url, undefined, { cache: true, cacheTTL: mixinHelpers_1.CACHE_TIMES.SHORT });
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
throw this.handleError(error);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* List the CURRENT user's verifiable credentials ({@link listCredentials} for
|
|
505
|
+
* the authenticated user's id). Throws if no user is authenticated.
|
|
506
|
+
*
|
|
507
|
+
* @param opts.status - Optional status filter.
|
|
508
|
+
*/
|
|
509
|
+
async listMyCredentials(opts = {}) {
|
|
510
|
+
const userId = this.getCurrentUserId();
|
|
511
|
+
if (!userId) {
|
|
512
|
+
throw new Error('No authenticated user — cannot list credentials.');
|
|
513
|
+
}
|
|
514
|
+
return this.listCredentials(userId, opts);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Verify a credential by its signed-record id
|
|
518
|
+
* (`GET /civic/credentials/by-record/:recordId/verify`). The server recomputes
|
|
519
|
+
* the canonical signing input from the STORED envelope and verifies the
|
|
520
|
+
* signature against a CURRENT verification method of the ISSUER DID (so a
|
|
521
|
+
* key the issuer has since rotated away no longer verifies), then checks the
|
|
522
|
+
* credential is neither revoked nor expired. Public; short-TTL cached
|
|
523
|
+
* (matching the server's `max-age=60`) and swept after the caller's own issue
|
|
524
|
+
* / revoke.
|
|
525
|
+
*
|
|
526
|
+
* A revoked / expired / unverifiable credential yields `valid: false` (NOT a
|
|
527
|
+
* throw) so the UI can render it as untrusted; `credential` is `null` only
|
|
528
|
+
* when no credential exists for the record id. Only a transport failure (the
|
|
529
|
+
* fetch itself) rejects.
|
|
530
|
+
*
|
|
531
|
+
* @param recordId - The credential's signed-record id. URL-encoded into the path.
|
|
532
|
+
*/
|
|
533
|
+
async verifyCredential(recordId) {
|
|
534
|
+
try {
|
|
535
|
+
return await this.makeRequest('GET', `/civic/credentials/by-record/${encodeURIComponent(recordId)}/verify`, undefined, { cache: true, cacheTTL: mixinHelpers_1.CACHE_TIMES.SHORT });
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
throw this.handleError(error);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Revoke a credential the current user originally issued
|
|
543
|
+
* (`POST /civic/credentials/:id/revoke`). Only the original USER issuer may
|
|
544
|
+
* revoke; the server flips the credential to `revoked`. After a successful
|
|
545
|
+
* revoke the credential GET caches are swept.
|
|
546
|
+
*
|
|
547
|
+
* @param id - The credential's id (the projection row `_id`, NOT the signed
|
|
548
|
+
* record id). URL-encoded into the path.
|
|
549
|
+
*/
|
|
550
|
+
async revokeCredential(id) {
|
|
551
|
+
try {
|
|
552
|
+
const result = await this.makeRequest('POST', `/civic/credentials/${encodeURIComponent(id)}/revoke`, undefined, { cache: false });
|
|
553
|
+
this._sweepCredentialCaches();
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
catch (error) {
|
|
557
|
+
throw this.handleError(error);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Sweep the credential GET caches an issue / revoke invalidates: every
|
|
562
|
+
* credential read (the holder list + the by-record verify, which share the
|
|
563
|
+
* `GET:/civic/credentials/` prefix) so a re-read reflects the new credential
|
|
564
|
+
* set / status. Public rather than `private` for the same TS4094 reason as
|
|
565
|
+
* {@link _signMyCivicRecordV2}.
|
|
566
|
+
*/
|
|
567
|
+
_sweepCredentialCaches() {
|
|
568
|
+
this.clearCacheByPrefix(CREDENTIAL_CACHE_PREFIX);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Sweep the GET caches a vouch / withdraw can invalidate: every personhood
|
|
572
|
+
* status read (the subject's snapshot changed) and `/users/me` (a subject
|
|
573
|
+
* crossing the threshold flips their mirrored `User.verified`). Public rather
|
|
574
|
+
* than `private` for the same TS4094 reason as {@link _signMyCivicRecordV2}.
|
|
575
|
+
*/
|
|
576
|
+
_sweepPersonhoodCaches() {
|
|
577
|
+
this.clearCacheByPrefix(PERSONHOOD_CACHE_PREFIX);
|
|
578
|
+
this.clearCacheByPrefix(USERS_ME_CACHE_PREFIX);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Sign a self-issued v2 signed-record envelope on the CURRENT user's own
|
|
582
|
+
* per-subject hash chain. Fetches the caller's chain head fresh (uncached, so
|
|
583
|
+
* `seq`/`prev` are never stale → no `bad_seq`/`chain_fork`) and signs with
|
|
584
|
+
* {@link SignatureService.signRecordV2}.
|
|
585
|
+
*
|
|
586
|
+
* NATIVE-ONLY (the private key lives in native secure storage). Internal
|
|
587
|
+
* helper (leading underscore); public rather than `private` because mixins
|
|
588
|
+
* compose into an exported anonymous class where TypeScript cannot represent a
|
|
589
|
+
* private member in the emitted declaration file (TS4094).
|
|
590
|
+
*
|
|
591
|
+
* @param type - The signed-record category.
|
|
592
|
+
* @param record - The record payload (canonicalized into the signed bytes).
|
|
593
|
+
* @param collection - The AtProto-style collection namespace.
|
|
594
|
+
* @param rkey - The AtProto-style record key within the collection.
|
|
595
|
+
*/
|
|
596
|
+
async _signMyCivicRecordV2(type, record, collection, rkey) {
|
|
597
|
+
const userId = this.getCurrentUserId();
|
|
598
|
+
if (!userId) {
|
|
599
|
+
throw new Error('No authenticated user — cannot sign a civic record.');
|
|
600
|
+
}
|
|
601
|
+
const subject = (0, OxyServices_identity_1.buildUserDid)(userId);
|
|
602
|
+
const head = await this.makeRequest('GET', `/identity/records/${encodeURIComponent(userId)}/chain/head`, undefined, { cache: false });
|
|
603
|
+
return signatureService_1.SignatureService.signRecordV2(type, subject, record, {
|
|
604
|
+
seq: head.seq + 1,
|
|
605
|
+
prev: head.headRecordId,
|
|
606
|
+
collection,
|
|
607
|
+
rkey,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|