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