@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,956 @@
1
+ /**
2
+ * Civic Methods Mixin (Commons "Oxy ID" — Fase 1; anti-gaming — Fase 2)
3
+ *
4
+ * Provides typed access to the public, verifiable citizen-identity ("Oxy ID")
5
+ * card a Commons user shows and others scan, plus the Fase 2 anti-gaming surfaces
6
+ * (real-life counterparty attestation + the validator/jury flow):
7
+ *
8
+ * - {@link OxyServicesCivicMixin.getPublicCard} fetches a user's signed card
9
+ * (`GET /civic/:userId/card`) and verifies the Oxy custodial attestation
10
+ * CLIENT-SIDE, so a scanner can trust the card OFFLINE (e.g. a cached card
11
+ * replayed without network) instead of re-trusting the transport.
12
+ * - {@link OxyServicesCivicMixin.getMyIdPayload} builds the QR payload the user
13
+ * displays. The QR encodes ONLY the DID (`oxycommons://card?did=…&v=1`) — never
14
+ * trust data — so the card cannot be spoofed by crafting a QR; the scanner
15
+ * resolves the signed card server-side and re-verifies it.
16
+ * - {@link OxyServicesCivicMixin.buildAttestQrPayload} builds the high-value
17
+ * real-life-attestation QR the person BEING attested (A) shows; the SCANNER
18
+ * (B) parses it with {@link parseAttestPayload} and signs a self-issued
19
+ * counterparty attestation via
20
+ * {@link OxyServicesCivicMixin.submitRealLifeAttestation}.
21
+ * - {@link OxyServicesCivicMixin.getValidatorInbox} /
22
+ * {@link OxyServicesCivicMixin.submitValidationVote} /
23
+ * {@link OxyServicesCivicMixin.denyValidation} drive a randomly-selected
24
+ * juror's medium-weight peer-validation duties.
25
+ *
26
+ * The wire shapes (`PublicCard`, `SignedPublicCard`, `ExportAttestation`,
27
+ * `RealLifeAttestationResult`, `ValidationRequestSummary`, `ValidationVoteResult`,
28
+ * `SignedRecordEnvelope`) come from `@oxyhq/contracts` — the single source of
29
+ * truth the API validates its output against — so producer and consumer cannot
30
+ * drift. The public Oxy ID card's attestation is an `ES256K-DER-SHA256` signature
31
+ * over `canonicalize(card)` (the exact bytes the server signed, with ONLY the
32
+ * present keys), so a consumer re-canonicalizes the `card` it received and checks
33
+ * the signature against `attestation.publicKey`.
34
+ *
35
+ * Card verification NEVER throws on a bad/absent signature — it returns
36
+ * `verified: false` so the UI can render a forged/unsigned card as visibly
37
+ * untrusted rather than silently trusting it. A transport/network failure (the
38
+ * fetch itself) still rejects, as everywhere else in the SDK.
39
+ *
40
+ * The Fase 2 writes (`submitRealLifeAttestation`, `submitValidationVote`) sign a
41
+ * v2 self-issued signed-record envelope with the on-device identity key (so they
42
+ * are NATIVE-ONLY — they throw on web, where `KeyManager` has no key) on the
43
+ * caller's own per-subject hash chain: each fetches the caller's chain head
44
+ * (`GET /identity/records/:userId/chain/head`) to set `seq`/`prev` before signing
45
+ * with {@link SignatureService.signRecordV2}.
46
+ *
47
+ * Reading a public card and building/parsing the QR payloads are
48
+ * platform-agnostic; deriving the current user's DID requires an authenticated
49
+ * session.
50
+ */
51
+ import type {
52
+ CredentialIssueResult,
53
+ CredentialListResult,
54
+ CredentialStatus,
55
+ CredentialVerifyResult,
56
+ ExportAttestation,
57
+ PersonhoodStatusResult,
58
+ PublicCard,
59
+ RealLifeAttestationResult,
60
+ SignedPublicCard,
61
+ SignedRecordEnvelope,
62
+ SignedRecordType,
63
+ ValidationRequestSummary,
64
+ ValidationVerdict,
65
+ ValidationVoteResult,
66
+ VerifiableCredentialResponse,
67
+ VouchResult,
68
+ } from '@oxyhq/contracts';
69
+ import type { OxyServicesBase } from '../OxyServices.base';
70
+ import { canonicalize } from '../crypto/canonicalJson';
71
+ import { SignatureService } from '../crypto/signatureService';
72
+ import { buildUserDid } from './OxyServices.identity';
73
+ import { CACHE_TIMES } from './mixinHelpers';
74
+
75
+ /**
76
+ * Validity window of a real-life-attestation QR (`oxycommons://attest?…exp=…`),
77
+ * matching the server's `REAL_LIFE_NONCE_MAX_AGE_MS` ceiling: the QR must be
78
+ * scanned and submitted within this window. The server is authoritative on
79
+ * freshness; this is the client-issued `exp`.
80
+ */
81
+ const ATTEST_QR_TTL_MS = 10 * 60 * 1000;
82
+
83
+ /** AtProto-style collection for a real-life counterparty attestation record. */
84
+ const ATTEST_COLLECTION = 'app.oxy.attestation';
85
+
86
+ /** AtProto-style collection for a validator's signed verdict record. */
87
+ const VALIDATION_COLLECTION = 'app.oxy.validation';
88
+
89
+ /** AtProto-style collection for a personhood vouch record. */
90
+ const VOUCH_COLLECTION = 'app.oxy.vouch';
91
+
92
+ /**
93
+ * AtProto-style collection (NSID) for a verifiable credential record — matches
94
+ * the server's `CREDENTIAL_COLLECTION`. Each credential is its own chain entry,
95
+ * so the per-credential `rkey` MUST be unique (a fresh nonce), unlike the
96
+ * one-per-subject vouch keyed on the subject DID.
97
+ */
98
+ const CREDENTIAL_COLLECTION = 'app.oxy.credential';
99
+
100
+ /**
101
+ * The W3C base VC type (`CREDENTIAL_BASE_TYPE` on the server) that MUST be
102
+ * present in every credential's `types`. The client prepends it when the caller
103
+ * omits it; the server rejects a credential record lacking it (`missing_base_type`).
104
+ */
105
+ const CREDENTIAL_BASE_TYPE = 'VerifiableCredential';
106
+
107
+ /**
108
+ * Cache-key prefix of every credential read — the holder list
109
+ * (`GET /civic/credentials/:holderUserId`) and the by-record verify
110
+ * (`GET /civic/credentials/by-record/:recordId/verify`) both start with it.
111
+ * Swept after an issue / revoke so a re-read reflects the new credential set /
112
+ * status instead of a stale cached one. The identity tag is a key SUFFIX, so
113
+ * this prefix invalidates the resource for every cached identity.
114
+ */
115
+ const CREDENTIAL_CACHE_PREFIX = 'GET:/civic/credentials/';
116
+
117
+ /**
118
+ * Cache-key prefix of every personhood-status read (`GET /civic/personhood/:userId`).
119
+ * Swept after a vouch / withdraw so a re-read reflects the recomputed snapshot
120
+ * instead of a stale cached one. The identity tag is a key SUFFIX, so this
121
+ * prefix invalidates the resource for every cached identity.
122
+ */
123
+ const PERSONHOOD_CACHE_PREFIX = 'GET:/civic/personhood/';
124
+
125
+ /**
126
+ * Cache-key prefix of the current user's `GET /users/me`. Swept after a vouch /
127
+ * withdraw because a subject crossing the personhood threshold flips their
128
+ * mirrored `User.verified` flag.
129
+ */
130
+ const USERS_ME_CACHE_PREFIX = 'GET:/users/me';
131
+
132
+ /**
133
+ * A {@link SignedPublicCard} augmented with the client's verification verdict.
134
+ *
135
+ * - `card` / `attestation` are echoed straight from the API response.
136
+ * - `verified` is `true` ONLY when `attestation` is present and its signature
137
+ * over `canonicalize(card)` checks out against `attestation.publicKey`. It is
138
+ * `false` for an unsigned card (dev, `attestation === null`), a tampered card,
139
+ * or a signature made with a different key.
140
+ *
141
+ * `verified` confirms the attestation's signature is internally consistent with
142
+ * its embedded `publicKey` (and that the card bytes were not mutated). It does
143
+ * NOT, on its own, establish that `publicKey` is Oxy's custodial key — that trust
144
+ * anchor is the Oxy API the card was fetched from (over TLS) and, for the
145
+ * pinning-conscious, `attestation.issuer` (the Oxy DID). The UI shows a trust
146
+ * indicator from `verified`; a `false` verdict MUST be surfaced as untrusted.
147
+ */
148
+ export interface CivicCardResult extends SignedPublicCard {
149
+ verified: boolean;
150
+ }
151
+
152
+ /** The DID extracted from a scanned `oxycommons://card?did=…` Oxy ID payload. */
153
+ export interface IdCardRef {
154
+ /** The subject's Oxy DID (`did:web:oxy.so:u:<userId>`). */
155
+ did: string;
156
+ }
157
+
158
+ /** URI scheme/host that introduces a Commons Oxy ID card payload. */
159
+ const CARD_MATCHER = /^oxycommons:\/\/card(?:[/?#]|$)/i;
160
+
161
+ /** URI scheme/host that introduces a real-life counterparty attestation payload. */
162
+ const ATTEST_MATCHER = /^oxycommons:\/\/attest(?:[/?#]|$)/i;
163
+
164
+ /**
165
+ * Minimal, allocation-light query-string parser (no `URL` / `URLSearchParams`)
166
+ * so it runs identically under Hermes and jsdom — mirrors the robustness of the
167
+ * "Sign in with Oxy" approval-link parser. Shared by every `oxycommons://…`
168
+ * payload parser in this module.
169
+ */
170
+ function parseCommonsQuery(raw: string): Map<string, string> {
171
+ const params = new Map<string, string>();
172
+ const qIndex = raw.indexOf('?');
173
+ if (qIndex < 0) return params;
174
+
175
+ let query = raw.slice(qIndex + 1);
176
+ const hashIndex = query.indexOf('#');
177
+ if (hashIndex >= 0) query = query.slice(0, hashIndex);
178
+
179
+ for (const pair of query.split('&')) {
180
+ if (pair.length === 0) continue;
181
+ const eq = pair.indexOf('=');
182
+ const rawKey = eq < 0 ? pair : pair.slice(0, eq);
183
+ const rawValue = eq < 0 ? '' : pair.slice(eq + 1);
184
+ try {
185
+ params.set(
186
+ decodeURIComponent(rawKey),
187
+ decodeURIComponent(rawValue.replace(/\+/g, ' ')),
188
+ );
189
+ } catch {
190
+ // Malformed percent-encoding — keep the raw token rather than throwing, so
191
+ // a single bad field doesn't sink an otherwise valid payload.
192
+ params.set(rawKey, rawValue);
193
+ }
194
+ }
195
+ return params;
196
+ }
197
+
198
+ /**
199
+ * Parse a scanned / deep-linked Oxy ID payload (`oxycommons://card?did=…`) into
200
+ * the referenced DID. Pure + dependency-free (Hermes-safe, no `URL` global) so
201
+ * Commons (and any scanner) can reuse it without an OxyServices instance.
202
+ *
203
+ * @param raw - The raw scanned string or deep-link URL.
204
+ * @returns `{ did }` when a usable DID is present; `null` for anything else (a
205
+ * non-card scheme, a missing/empty `did`, or non-string input).
206
+ */
207
+ export function parseIdPayload(raw: string): IdCardRef | null {
208
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
209
+ return null;
210
+ }
211
+ const value = raw.trim();
212
+ if (!CARD_MATCHER.test(value)) {
213
+ return null;
214
+ }
215
+ const did = parseCommonsQuery(value).get('did');
216
+ if (!did || did.length === 0) {
217
+ return null;
218
+ }
219
+ return { did };
220
+ }
221
+
222
+ /**
223
+ * The fields decoded from a scanned real-life-attestation QR
224
+ * (`oxycommons://attest?subject=…&ctx=…&nonce=…&exp=…`). The SCANNER feeds these
225
+ * to {@link OxyServicesCivicMixin.submitRealLifeAttestation}.
226
+ */
227
+ export interface ParsedAttestPayload {
228
+ /** The DID of the person being attested (A) — becomes the record's `about`. */
229
+ subjectDid: string;
230
+ /** Opaque interaction id (`ctx`); `''` when the QR omitted it. */
231
+ context: string;
232
+ /** Single-use replay-guard nonce. */
233
+ nonce: string;
234
+ /** Nonce expiry (epoch ms); the server re-checks freshness authoritatively. */
235
+ exp: number;
236
+ }
237
+
238
+ /**
239
+ * The QR a person shows to be attested in real life, plus the fresh nonce/exp it
240
+ * embeds so the displaying app can track which scan completed it.
241
+ */
242
+ export interface AttestQrPayload {
243
+ /** The `oxycommons://attest?subject=…&ctx=…&nonce=…&exp=…` string to encode as a QR. */
244
+ payload: string;
245
+ /** The single-use nonce embedded in the payload. */
246
+ nonce: string;
247
+ /** The nonce expiry embedded in the payload (epoch ms). */
248
+ exp: number;
249
+ }
250
+
251
+ /**
252
+ * Parse a scanned / deep-linked real-life-attestation payload
253
+ * (`oxycommons://attest?subject=…&ctx=…&nonce=…&exp=…`). Pure + dependency-free
254
+ * (Hermes-safe, no `URL` global), mirroring {@link parseIdPayload}, so Commons
255
+ * (and any scanner) can reuse it without an OxyServices instance.
256
+ *
257
+ * @param raw - The raw scanned string or deep-link URL.
258
+ * @returns `{ subjectDid, context, nonce, exp }` when the required fields are
259
+ * present and `exp` is a positive finite number; `null` otherwise (a non-attest
260
+ * scheme, a missing `subject`/`nonce`/`exp`, an unparseable `exp`, or non-string
261
+ * input). `context` defaults to `''` when the QR omits `ctx`.
262
+ */
263
+ export function parseAttestPayload(raw: string): ParsedAttestPayload | null {
264
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
265
+ return null;
266
+ }
267
+ const value = raw.trim();
268
+ if (!ATTEST_MATCHER.test(value)) {
269
+ return null;
270
+ }
271
+ const params = parseCommonsQuery(value);
272
+ const subjectDid = params.get('subject');
273
+ const nonce = params.get('nonce');
274
+ const expRaw = params.get('exp');
275
+ if (!subjectDid || !nonce || expRaw === undefined || expRaw.length === 0) {
276
+ return null;
277
+ }
278
+ const exp = Number(expRaw);
279
+ if (!Number.isFinite(exp) || exp <= 0) {
280
+ return null;
281
+ }
282
+ return { subjectDid, context: params.get('ctx') ?? '', nonce, exp };
283
+ }
284
+
285
+ /**
286
+ * Verify the Oxy custodial attestation on a public card.
287
+ *
288
+ * Re-canonicalizes the received `card` (so the order of the JSON keys on the
289
+ * wire is irrelevant; `canonicalize` also omits any `undefined`-valued optional
290
+ * key, matching the server which omits absent keys entirely) and checks the
291
+ * `ES256K-DER-SHA256` signature against `attestation.publicKey`.
292
+ *
293
+ * NEVER throws: `SignatureService.verify` already swallows malformed-input
294
+ * errors and returns `false`, and an absent attestation short-circuits to
295
+ * `false`. A pure, reusable helper (Commons can call it on a cached card).
296
+ *
297
+ * @param card - The card to verify (exactly as received).
298
+ * @param attestation - The card's attestation, or `null` (unsigned ⇒ `false`).
299
+ */
300
+ export async function verifyPublicCardAttestation(
301
+ card: PublicCard,
302
+ attestation: ExportAttestation | null,
303
+ ): Promise<boolean> {
304
+ if (!attestation) {
305
+ return false;
306
+ }
307
+ const { signature, publicKey } = attestation;
308
+ if (!signature || !publicKey) {
309
+ return false;
310
+ }
311
+ return SignatureService.verify(canonicalize(card), signature, publicKey);
312
+ }
313
+
314
+ /**
315
+ * Input for {@link OxyServicesCivicMixin.submitRealLifeAttestation} — the fields
316
+ * the SCANNER (B) carries over from a parsed {@link ParsedAttestPayload}, plus
317
+ * the optional co-location / biometric support signals B contributes.
318
+ */
319
+ export interface SubmitRealLifeAttestationInput {
320
+ /** The DID of the person being attested (A); becomes the record's `about`. */
321
+ subjectDid: string;
322
+ /** Opaque interaction id from the QR. */
323
+ context: string;
324
+ /** Single-use nonce from the QR (also the record's `rkey`). */
325
+ nonce: string;
326
+ /** Nonce expiry from the QR (epoch ms). */
327
+ exp: number;
328
+ /** Coarse co-location proof (optional). */
329
+ geohash?: string;
330
+ /** Whether B's device biometric gate fired before signing (optional). */
331
+ biometricOk?: boolean;
332
+ }
333
+
334
+ /** Result of {@link OxyServicesCivicMixin.denyValidation}. */
335
+ export interface DenyValidationResult {
336
+ denied: boolean;
337
+ }
338
+
339
+ /**
340
+ * Input for {@link OxyServicesCivicMixin.vouchForPerson} — the SUBJECT (A) the
341
+ * current user (B) is vouching for, plus B's optional stake and biometric
342
+ * support signal.
343
+ */
344
+ export interface VouchForPersonInput {
345
+ /** A's DID (`did:web:oxy.so:u:<userId>`); becomes the vouch record's `about`. */
346
+ subjectDid: string;
347
+ /**
348
+ * B's chosen stake (the `stake` wire field). Omitted ⇒ the server applies its
349
+ * default; the server clamps any value into its `[min, max]` and echoes the
350
+ * recorded amount back as `VouchResult.stakeAmount`.
351
+ */
352
+ stakeAmount?: number;
353
+ /** Whether B's device biometric gate fired before signing (optional signal). */
354
+ biometricOk?: boolean;
355
+ }
356
+
357
+ /** Result of {@link OxyServicesCivicMixin.withdrawVouch}. */
358
+ export interface WithdrawVouchResult {
359
+ withdrawn: boolean;
360
+ }
361
+
362
+ /**
363
+ * Input for {@link OxyServicesCivicMixin.issueCredential} — the HOLDER the
364
+ * caller (issuer) attests a claim about, the VC type tags, the issuer's claim
365
+ * set, and an optional ISO-8601 expiry.
366
+ */
367
+ export interface IssueCredentialInput {
368
+ /** The holder's Oxy DID (`did:web:oxy.so:u:<userId>`); becomes the record's `about`. */
369
+ holderDid: string;
370
+ /**
371
+ * The VC type tags. `'VerifiableCredential'` is the required base type and is
372
+ * prepended automatically when the caller omits it; provide at least one
373
+ * specific type alongside (e.g. `'EmploymentCredential'`).
374
+ */
375
+ types: string[];
376
+ /** The arbitrary, issuer-asserted claim set about the holder (signed verbatim). */
377
+ claims: Record<string, unknown>;
378
+ /**
379
+ * Optional expiry as an ISO-8601 date string; absent = non-expiring. Converted
380
+ * to epoch milliseconds in the signed record (the wire/storage unit), so a
381
+ * holder cannot extend validity after the fact. Must be a parseable date and,
382
+ * per the server, in the future.
383
+ */
384
+ expiresAt?: string;
385
+ }
386
+
387
+ /** Result of {@link OxyServicesCivicMixin.revokeCredential} (`POST …/:id/revoke`). */
388
+ export interface RevokeCredentialResult {
389
+ revoked: boolean;
390
+ credential: VerifiableCredentialResponse;
391
+ }
392
+
393
+ /**
394
+ * The current chain head as returned by `GET /identity/records/:userId/chain/head`.
395
+ * `headRecordId` is `null` and `seq` is `-1` when the subject has no chain yet,
396
+ * so the next record's coordinates are always `seq: head.seq + 1` (genesis = 0)
397
+ * and `prev: head.headRecordId` (genesis = null).
398
+ */
399
+ interface ChainHeadResponse {
400
+ headRecordId: string | null;
401
+ seq: number;
402
+ recordCount: number;
403
+ }
404
+
405
+ export function OxyServicesCivicMixin<T extends typeof OxyServicesBase>(Base: T) {
406
+ return class extends Base {
407
+ constructor(...args: any[]) {
408
+ super(...(args as [any]));
409
+ }
410
+
411
+ /**
412
+ * Fetch a user's signed public Oxy ID card and verify the Oxy attestation
413
+ * client-side. Public (no auth required); short-TTL cached.
414
+ *
415
+ * Resolves to `{ card, attestation, verified }`. A bad/absent signature does
416
+ * NOT reject — it yields `verified: false` so the UI can warn. Only a
417
+ * transport failure (the fetch itself) rejects.
418
+ *
419
+ * @param userId - The subject account's Mongo `_id`. URL-encoded into the path.
420
+ */
421
+ async getPublicCard(userId: string): Promise<CivicCardResult> {
422
+ try {
423
+ const signed = await this.makeRequest<SignedPublicCard>(
424
+ 'GET',
425
+ `/civic/${encodeURIComponent(userId)}/card`,
426
+ undefined,
427
+ { cache: true, cacheTTL: CACHE_TIMES.SHORT },
428
+ );
429
+ const verified = await verifyPublicCardAttestation(signed.card, signed.attestation);
430
+ return { card: signed.card, attestation: signed.attestation, verified };
431
+ } catch (error) {
432
+ throw this.handleError(error);
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Build the Oxy ID QR payload for the current user:
438
+ * `oxycommons://card?did=<did>&v=1`, where `<did>` is the user's Oxy DID
439
+ * (`did:web:oxy.so:u:<userId>`). The QR encodes ONLY the DID (anti-spoof — no
440
+ * trust data); a scanner resolves the signed card via {@link getPublicCard}.
441
+ * Round-trips through {@link parseIdPayload}.
442
+ *
443
+ * Throws if no user is authenticated (no DID to derive).
444
+ */
445
+ getMyIdPayload(): string {
446
+ const userId = this.getCurrentUserId();
447
+ if (!userId) {
448
+ throw new Error('No authenticated user — cannot build an Oxy ID payload.');
449
+ }
450
+ return `oxycommons://card?did=${buildUserDid(userId)}&v=1`;
451
+ }
452
+
453
+ // =========================================================================
454
+ // FASE 2 — real-life counterparty attestation (HIGH weight)
455
+ // =========================================================================
456
+
457
+ /**
458
+ * Build the real-life-attestation QR the current user (A) shows to be
459
+ * attested by a counterparty (B):
460
+ * `oxycommons://attest?subject=<A.did>&ctx=<context>&nonce=<fresh>&exp=<now+10m>`.
461
+ *
462
+ * A fresh crypto-random nonce is minted per call (single-use replay guard);
463
+ * `exp` is `now + 10min` (matching the server ceiling — scan promptly). The
464
+ * QR carries NO trust data; B re-signs and the server is authoritative. The
465
+ * returned `nonce`/`exp` let the displaying screen track which scan completed.
466
+ *
467
+ * Async because a crypto-secure nonce requires the platform RNG (async on
468
+ * native via expo-crypto). Throws if no user is authenticated.
469
+ *
470
+ * @param input.context - An opaque interaction id describing the encounter.
471
+ */
472
+ async buildAttestQrPayload(input: { context: string }): Promise<AttestQrPayload> {
473
+ const userId = this.getCurrentUserId();
474
+ if (!userId) {
475
+ throw new Error('No authenticated user — cannot build an attestation QR.');
476
+ }
477
+ const subject = buildUserDid(userId);
478
+ const nonce = await SignatureService.generateChallenge();
479
+ const exp = Date.now() + ATTEST_QR_TTL_MS;
480
+ const payload =
481
+ `oxycommons://attest?subject=${subject}` +
482
+ `&ctx=${encodeURIComponent(input.context)}` +
483
+ `&nonce=${nonce}&exp=${exp}`;
484
+ return { payload, nonce, exp };
485
+ }
486
+
487
+ /**
488
+ * Submit a real-life counterparty attestation as the SCANNER (B): sign a
489
+ * self-issued `real_life_attestation` v2 record on B's own chain
490
+ * (`subject === issuer === B.did`), referencing A via `record.about`, then
491
+ * `POST /civic/attestations`. The server enforces nonce single-use,
492
+ * freshness, graph-exclusion (B is not A's puppet), and the per-pair
493
+ * cooldown, then awards A the HIGH-weight points.
494
+ *
495
+ * NATIVE-ONLY (signs with the on-device key; throws on web / when no
496
+ * identity or no authenticated user). The record is keyed
497
+ * `collection: 'app.oxy.attestation'`, `rkey: <nonce>`.
498
+ *
499
+ * @param input - The parsed QR fields ({@link ParsedAttestPayload}) plus B's
500
+ * optional `geohash` / `biometricOk` support signals.
501
+ */
502
+ async submitRealLifeAttestation(
503
+ input: SubmitRealLifeAttestationInput,
504
+ ): Promise<RealLifeAttestationResult> {
505
+ try {
506
+ const envelope = await this._signMyCivicRecordV2(
507
+ 'real_life_attestation',
508
+ {
509
+ about: input.subjectDid,
510
+ context: input.context,
511
+ nonce: input.nonce,
512
+ exp: input.exp,
513
+ ...(input.geohash !== undefined ? { geohash: input.geohash } : {}),
514
+ ...(input.biometricOk !== undefined ? { biometricOk: input.biometricOk } : {}),
515
+ },
516
+ ATTEST_COLLECTION,
517
+ input.nonce,
518
+ );
519
+ return await this.makeRequest<RealLifeAttestationResult>(
520
+ 'POST',
521
+ '/civic/attestations',
522
+ envelope,
523
+ { cache: false },
524
+ );
525
+ } catch (error) {
526
+ throw this.handleError(error);
527
+ }
528
+ }
529
+
530
+ // =========================================================================
531
+ // FASE 2 — validator / jury (MEDIUM weight)
532
+ // =========================================================================
533
+
534
+ /**
535
+ * List the current user's pending jury duties (`GET /civic/validations/inbox`).
536
+ * Auth required; never cached (the inbox is a live queue). Returns `[]` when
537
+ * the caller is on no juries.
538
+ */
539
+ async getValidatorInbox(): Promise<ValidationRequestSummary[]> {
540
+ try {
541
+ const res = await this.makeRequest<{ requests?: ValidationRequestSummary[] }>(
542
+ 'GET',
543
+ '/civic/validations/inbox',
544
+ undefined,
545
+ { cache: false },
546
+ );
547
+ return res.requests ?? [];
548
+ } catch (error) {
549
+ throw this.handleError(error);
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Cast a SIGNED verdict on a validation request as a selected juror: sign a
555
+ * self-issued `validation_verdict` v2 record on the juror's own chain bound
556
+ * to `requestId` + `payloadHash` (so a verdict cannot be replayed onto a
557
+ * different request or an altered payload), then
558
+ * `POST /civic/validations/:id/vote`.
559
+ *
560
+ * NATIVE-ONLY (signs with the on-device key; throws on web / when no
561
+ * identity or no authenticated user). The record is keyed
562
+ * `collection: 'app.oxy.validation'`, `rkey: <requestId>`.
563
+ *
564
+ * @param requestId - The validation request being voted on.
565
+ * @param payloadHash - The request's canonical payload hash (from the inbox);
566
+ * the server rejects a vote whose hash does not match the stored request.
567
+ * @param verdict - `'valid'` | `'invalid'` | `'abstain'`.
568
+ */
569
+ async submitValidationVote(
570
+ requestId: string,
571
+ payloadHash: string,
572
+ verdict: ValidationVerdict,
573
+ ): Promise<ValidationVoteResult> {
574
+ try {
575
+ const envelope = await this._signMyCivicRecordV2(
576
+ 'validation_verdict',
577
+ { requestId, payloadHash, verdict },
578
+ VALIDATION_COLLECTION,
579
+ requestId,
580
+ );
581
+ return await this.makeRequest<ValidationVoteResult>(
582
+ 'POST',
583
+ `/civic/validations/${encodeURIComponent(requestId)}/vote`,
584
+ envelope,
585
+ { cache: false },
586
+ );
587
+ } catch (error) {
588
+ throw this.handleError(error);
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Recuse from a validation request (`POST /civic/validations/:id/deny`): the
594
+ * juror is removed from the jury and the request is re-tallied. Auth
595
+ * required; no signed record (recusal is not an attestation).
596
+ *
597
+ * @param requestId - The validation request to recuse from.
598
+ */
599
+ async denyValidation(requestId: string): Promise<DenyValidationResult> {
600
+ try {
601
+ return await this.makeRequest<DenyValidationResult>(
602
+ 'POST',
603
+ `/civic/validations/${encodeURIComponent(requestId)}/deny`,
604
+ undefined,
605
+ { cache: false },
606
+ );
607
+ } catch (error) {
608
+ throw this.handleError(error);
609
+ }
610
+ }
611
+
612
+ // =========================================================================
613
+ // FASE 3 — proof-of-personhood web-of-trust (staked vouch)
614
+ // =========================================================================
615
+
616
+ /**
617
+ * Vouch that another user is a real person as the VOUCHER (B): sign a
618
+ * self-issued `personhood_vouch` v2 record on B's own chain
619
+ * (`subject === issuer === B.did`), referencing the subject (A) via
620
+ * `record.about`, then `POST /civic/personhood/vouch`. The server verifies
621
+ * it, enforces the voucher-eligibility (personhood ≥ τ) + graph-exclusion
622
+ * gates, stakes B, awards A `personhood_vouched`, and recomputes A's
623
+ * personhood. The voucher id is resolved server-side from the session — never
624
+ * from the body.
625
+ *
626
+ * The signed record matches the API schema: `{ about, stake?, … }` — note the
627
+ * wire field is `stake` (the caller's `stakeAmount` request), distinct from
628
+ * the server-clamped `VouchResult.stakeAmount` it returns. The optional
629
+ * `biometricOk` is carried as a signed support signal.
630
+ *
631
+ * NATIVE-ONLY (signs with the on-device key; throws on web / when no identity
632
+ * or no authenticated user). The record is keyed
633
+ * `collection: 'app.oxy.vouch'`, `rkey: <subjectDid>` (one vouch per subject
634
+ * on the voucher's chain — last-writer-wins). After a successful vouch the
635
+ * personhood + `/users/me` GET caches are swept.
636
+ *
637
+ * @param input - The subject DID plus B's optional stake / biometric signal.
638
+ */
639
+ async vouchForPerson(input: VouchForPersonInput): Promise<VouchResult> {
640
+ try {
641
+ const envelope = await this._signMyCivicRecordV2(
642
+ 'personhood_vouch',
643
+ {
644
+ about: input.subjectDid,
645
+ ...(input.stakeAmount !== undefined ? { stake: input.stakeAmount } : {}),
646
+ ...(input.biometricOk !== undefined ? { biometricOk: input.biometricOk } : {}),
647
+ },
648
+ VOUCH_COLLECTION,
649
+ input.subjectDid,
650
+ );
651
+ const result = await this.makeRequest<VouchResult>(
652
+ 'POST',
653
+ '/civic/personhood/vouch',
654
+ envelope,
655
+ { cache: false },
656
+ );
657
+ this._sweepPersonhoodCaches();
658
+ return result;
659
+ } catch (error) {
660
+ throw this.handleError(error);
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Withdraw the current user's active vouch for a subject
666
+ * (`DELETE /civic/personhood/vouch/:subjectUserId`). The vouch flips to
667
+ * `withdrawn` server-side and the subject is recomputed (which may demote
668
+ * them below θ). Auth required; no signed record (withdrawal is not an
669
+ * attestation). After a successful withdraw the personhood + `/users/me` GET
670
+ * caches are swept.
671
+ *
672
+ * @param subjectUserId - The subject account's Mongo `_id` (NOT a DID) — the
673
+ * id the server keys the vouch on. URL-encoded into the path.
674
+ */
675
+ async withdrawVouch(subjectUserId: string): Promise<WithdrawVouchResult> {
676
+ try {
677
+ const result = await this.makeRequest<WithdrawVouchResult>(
678
+ 'DELETE',
679
+ `/civic/personhood/vouch/${encodeURIComponent(subjectUserId)}`,
680
+ undefined,
681
+ { cache: false },
682
+ );
683
+ this._sweepPersonhoodCaches();
684
+ return result;
685
+ } catch (error) {
686
+ throw this.handleError(error);
687
+ }
688
+ }
689
+
690
+ /**
691
+ * Fetch a user's public personhood status snapshot
692
+ * (`GET /civic/personhood/:userId`). Read-only: the server returns the cached
693
+ * snapshot, or a zeroed `unverified` shape (`breakdown`/`updatedAt` null) when
694
+ * none exists yet. Public (no auth required); short-TTL cached.
695
+ *
696
+ * @param userId - The subject account's Mongo `_id`. URL-encoded into the path.
697
+ */
698
+ async getPersonhood(userId: string): Promise<PersonhoodStatusResult> {
699
+ try {
700
+ return await this.makeRequest<PersonhoodStatusResult>(
701
+ 'GET',
702
+ `/civic/personhood/${encodeURIComponent(userId)}`,
703
+ undefined,
704
+ { cache: true, cacheTTL: CACHE_TIMES.SHORT },
705
+ );
706
+ } catch (error) {
707
+ throw this.handleError(error);
708
+ }
709
+ }
710
+
711
+ /**
712
+ * Fetch the CURRENT user's personhood status ({@link getPersonhood} for the
713
+ * authenticated user's id). Throws if no user is authenticated.
714
+ */
715
+ async getMyPersonhood(): Promise<PersonhoodStatusResult> {
716
+ const userId = this.getCurrentUserId();
717
+ if (!userId) {
718
+ throw new Error('No authenticated user — cannot resolve personhood status.');
719
+ }
720
+ return this.getPersonhood(userId);
721
+ }
722
+
723
+ // =========================================================================
724
+ // FASE 4 — verifiable credentials
725
+ // =========================================================================
726
+
727
+ /**
728
+ * Issue a verifiable credential as the ISSUER: sign a self-issued
729
+ * `credential` v2 record on the caller's own chain
730
+ * (`subject === issuer === issuer.did`) whose `record.about` is the HOLDER's
731
+ * DID (the W3C `credentialSubject`), then `POST /civic/credentials`. The
732
+ * server verifies the signature + the issuer's CURRENT verification method +
733
+ * chain continuity, stores the signed record, and projects a queryable
734
+ * credential row. All claim data comes from the SIGNED envelope — the issuer
735
+ * id is resolved server-side from the session, never from the body.
736
+ *
737
+ * `'VerifiableCredential'` is ensured present as the base type (prepended
738
+ * when the caller omits it; the server rejects a record missing it). An
739
+ * `expiresAt` ISO string is converted to the epoch-ms the signed record
740
+ * carries (the server rejects a past expiry).
741
+ *
742
+ * NATIVE-ONLY (signs with the on-device key; throws on web / when no identity
743
+ * or no authenticated user). The record is keyed
744
+ * `collection: 'app.oxy.credential'`, `rkey: <fresh unique nonce>` (each
745
+ * credential is a distinct chain entry, so the rkey must be unique per
746
+ * credential). After a successful issue the credential GET caches are swept.
747
+ *
748
+ * @param input - The holder DID, VC types, claims, and optional ISO expiry.
749
+ */
750
+ async issueCredential(input: IssueCredentialInput): Promise<CredentialIssueResult> {
751
+ try {
752
+ const types = input.types.includes(CREDENTIAL_BASE_TYPE)
753
+ ? input.types
754
+ : [CREDENTIAL_BASE_TYPE, ...input.types];
755
+
756
+ let expiresAtMs: number | undefined;
757
+ if (input.expiresAt !== undefined) {
758
+ const parsed = Date.parse(input.expiresAt);
759
+ if (Number.isNaN(parsed)) {
760
+ throw new Error('Invalid expiresAt — must be an ISO 8601 date string.');
761
+ }
762
+ expiresAtMs = parsed;
763
+ }
764
+
765
+ const record: Record<string, unknown> = {
766
+ about: input.holderDid,
767
+ types,
768
+ claims: input.claims,
769
+ ...(expiresAtMs !== undefined ? { expiresAt: expiresAtMs } : {}),
770
+ };
771
+
772
+ // A fresh crypto-random rkey: every credential is its own chain entry, so
773
+ // (unlike the one-per-subject vouch keyed on the subject DID) the rkey
774
+ // must be unique per credential or a second credential would collide.
775
+ const rkey = await SignatureService.generateChallenge();
776
+ const envelope = await this._signMyCivicRecordV2(
777
+ 'credential',
778
+ record,
779
+ CREDENTIAL_COLLECTION,
780
+ rkey,
781
+ );
782
+ const result = await this.makeRequest<CredentialIssueResult>(
783
+ 'POST',
784
+ '/civic/credentials',
785
+ envelope,
786
+ { cache: false },
787
+ );
788
+ this._sweepCredentialCaches();
789
+ return result;
790
+ } catch (error) {
791
+ throw this.handleError(error);
792
+ }
793
+ }
794
+
795
+ /**
796
+ * List a holder's verifiable credentials
797
+ * (`GET /civic/credentials/:holderUserId`), newest first, optionally filtered
798
+ * by stored `status`. Public (credentials are issuer-signed attestations a
799
+ * holder collects to SHOW); short-TTL cached and swept after the caller's own
800
+ * issue / revoke. An unknown holder yields an empty list.
801
+ *
802
+ * @param holderUserId - The holder account's Mongo `_id` (NOT a DID). URL-encoded.
803
+ * @param opts.status - Optional `'active' | 'revoked' | 'expired'` filter.
804
+ */
805
+ async listCredentials(
806
+ holderUserId: string,
807
+ opts: { status?: CredentialStatus } = {},
808
+ ): Promise<CredentialListResult> {
809
+ try {
810
+ const base = `/civic/credentials/${encodeURIComponent(holderUserId)}`;
811
+ const url = opts.status ? `${base}?status=${encodeURIComponent(opts.status)}` : base;
812
+ return await this.makeRequest<CredentialListResult>(
813
+ 'GET',
814
+ url,
815
+ undefined,
816
+ { cache: true, cacheTTL: CACHE_TIMES.SHORT },
817
+ );
818
+ } catch (error) {
819
+ throw this.handleError(error);
820
+ }
821
+ }
822
+
823
+ /**
824
+ * List the CURRENT user's verifiable credentials ({@link listCredentials} for
825
+ * the authenticated user's id). Throws if no user is authenticated.
826
+ *
827
+ * @param opts.status - Optional status filter.
828
+ */
829
+ async listMyCredentials(
830
+ opts: { status?: CredentialStatus } = {},
831
+ ): Promise<CredentialListResult> {
832
+ const userId = this.getCurrentUserId();
833
+ if (!userId) {
834
+ throw new Error('No authenticated user — cannot list credentials.');
835
+ }
836
+ return this.listCredentials(userId, opts);
837
+ }
838
+
839
+ /**
840
+ * Verify a credential by its signed-record id
841
+ * (`GET /civic/credentials/by-record/:recordId/verify`). The server recomputes
842
+ * the canonical signing input from the STORED envelope and verifies the
843
+ * signature against a CURRENT verification method of the ISSUER DID (so a
844
+ * key the issuer has since rotated away no longer verifies), then checks the
845
+ * credential is neither revoked nor expired. Public; short-TTL cached
846
+ * (matching the server's `max-age=60`) and swept after the caller's own issue
847
+ * / revoke.
848
+ *
849
+ * A revoked / expired / unverifiable credential yields `valid: false` (NOT a
850
+ * throw) so the UI can render it as untrusted; `credential` is `null` only
851
+ * when no credential exists for the record id. Only a transport failure (the
852
+ * fetch itself) rejects.
853
+ *
854
+ * @param recordId - The credential's signed-record id. URL-encoded into the path.
855
+ */
856
+ async verifyCredential(recordId: string): Promise<CredentialVerifyResult> {
857
+ try {
858
+ return await this.makeRequest<CredentialVerifyResult>(
859
+ 'GET',
860
+ `/civic/credentials/by-record/${encodeURIComponent(recordId)}/verify`,
861
+ undefined,
862
+ { cache: true, cacheTTL: CACHE_TIMES.SHORT },
863
+ );
864
+ } catch (error) {
865
+ throw this.handleError(error);
866
+ }
867
+ }
868
+
869
+ /**
870
+ * Revoke a credential the current user originally issued
871
+ * (`POST /civic/credentials/:id/revoke`). Only the original USER issuer may
872
+ * revoke; the server flips the credential to `revoked`. After a successful
873
+ * revoke the credential GET caches are swept.
874
+ *
875
+ * @param id - The credential's id (the projection row `_id`, NOT the signed
876
+ * record id). URL-encoded into the path.
877
+ */
878
+ async revokeCredential(id: string): Promise<RevokeCredentialResult> {
879
+ try {
880
+ const result = await this.makeRequest<RevokeCredentialResult>(
881
+ 'POST',
882
+ `/civic/credentials/${encodeURIComponent(id)}/revoke`,
883
+ undefined,
884
+ { cache: false },
885
+ );
886
+ this._sweepCredentialCaches();
887
+ return result;
888
+ } catch (error) {
889
+ throw this.handleError(error);
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Sweep the credential GET caches an issue / revoke invalidates: every
895
+ * credential read (the holder list + the by-record verify, which share the
896
+ * `GET:/civic/credentials/` prefix) so a re-read reflects the new credential
897
+ * set / status. Public rather than `private` for the same TS4094 reason as
898
+ * {@link _signMyCivicRecordV2}.
899
+ */
900
+ _sweepCredentialCaches(): void {
901
+ this.clearCacheByPrefix(CREDENTIAL_CACHE_PREFIX);
902
+ }
903
+
904
+ /**
905
+ * Sweep the GET caches a vouch / withdraw can invalidate: every personhood
906
+ * status read (the subject's snapshot changed) and `/users/me` (a subject
907
+ * crossing the threshold flips their mirrored `User.verified`). Public rather
908
+ * than `private` for the same TS4094 reason as {@link _signMyCivicRecordV2}.
909
+ */
910
+ _sweepPersonhoodCaches(): void {
911
+ this.clearCacheByPrefix(PERSONHOOD_CACHE_PREFIX);
912
+ this.clearCacheByPrefix(USERS_ME_CACHE_PREFIX);
913
+ }
914
+
915
+ /**
916
+ * Sign a self-issued v2 signed-record envelope on the CURRENT user's own
917
+ * per-subject hash chain. Fetches the caller's chain head fresh (uncached, so
918
+ * `seq`/`prev` are never stale → no `bad_seq`/`chain_fork`) and signs with
919
+ * {@link SignatureService.signRecordV2}.
920
+ *
921
+ * NATIVE-ONLY (the private key lives in native secure storage). Internal
922
+ * helper (leading underscore); public rather than `private` because mixins
923
+ * compose into an exported anonymous class where TypeScript cannot represent a
924
+ * private member in the emitted declaration file (TS4094).
925
+ *
926
+ * @param type - The signed-record category.
927
+ * @param record - The record payload (canonicalized into the signed bytes).
928
+ * @param collection - The AtProto-style collection namespace.
929
+ * @param rkey - The AtProto-style record key within the collection.
930
+ */
931
+ async _signMyCivicRecordV2(
932
+ type: SignedRecordType,
933
+ record: Record<string, unknown>,
934
+ collection: string,
935
+ rkey: string,
936
+ ): Promise<SignedRecordEnvelope> {
937
+ const userId = this.getCurrentUserId();
938
+ if (!userId) {
939
+ throw new Error('No authenticated user — cannot sign a civic record.');
940
+ }
941
+ const subject = buildUserDid(userId);
942
+ const head = await this.makeRequest<ChainHeadResponse>(
943
+ 'GET',
944
+ `/identity/records/${encodeURIComponent(userId)}/chain/head`,
945
+ undefined,
946
+ { cache: false },
947
+ );
948
+ return SignatureService.signRecordV2(type, subject, record, {
949
+ seq: head.seq + 1,
950
+ prev: head.headRecordId,
951
+ collection,
952
+ rkey,
953
+ });
954
+ }
955
+ };
956
+ }