| … | … | @@ -1,609 +1,7 @@ |
| 1 | | import { decodeOp, OpTypes, validateOp } from './identity-operations.js' |
| 2 | | import b4a from 'b4a' |
| 3 | | |
| 4 | | /** |
| 5 | | * Contract validation — checks that the writer who appended an operation |
| 6 | | * has permission to execute it. This prevents rogue Autobase writers from |
| 7 | | * injecting admin-level operations. |
| 8 | | * |
| 9 | | * Permission model: |
| 10 | | * - CREATE_USER: any writer (but first user gets admin via autoRegister) |
| 11 | | * - UPDATE_USER: writer must be the user themselves or an admin |
| 12 | | * - DELETE_USER: admin only |
| 13 | | * - ADD_IDENTITY / REMOVE_IDENTITY / LINK_IDENTITY: admin or self |
| 14 | | * - UPGRADE_PERMISSIONS: admin only |
| 15 | | * - MERGE_ACCOUNTS: admin only |
| 16 | | * - REVOKE_IDENTITY / RESTORE_IDENTITY: admin only |
| 17 | | * - SET_USERNAME: writer must be the user themselves or an admin |
| 18 | | * |
| 19 | | * Note: The first writer (bootstrapper) is always trusted for initial setup. |
| 20 | | * Contract validation is skipped if opts.contractValidation is false (default for |
| 21 | | * backwards compatibility during migration). |
| 22 | | */ |
| 23 | | |
| 24 | | // Operations that require admin permissions |
| 25 | | const ADMIN_OPS = new Set([ |
| 26 | | OpTypes.DELETE_USER, |
| 27 | | OpTypes.UPGRADE_PERMISSIONS, |
| 28 | | OpTypes.MERGE_ACCOUNTS, |
| 29 | | OpTypes.REVOKE_IDENTITY, |
| 30 | | OpTypes.RESTORE_IDENTITY, |
| 31 | | OpTypes.DEACTIVATE_USER, |
| 32 | | OpTypes.REACTIVATE_USER |
| 33 | | ]) |
| 34 | | |
| 35 | | // Operations that require admin OR self (userId in op matches writer's user) |
| 36 | | const SELF_OR_ADMIN_OPS = new Set([ |
| 37 | | OpTypes.UPDATE_USER, |
| 38 | | OpTypes.ADD_IDENTITY, |
| 39 | | OpTypes.REMOVE_IDENTITY, |
| 40 | | OpTypes.LINK_IDENTITY, |
| 41 | | OpTypes.SET_USERNAME |
| 42 | | ]) |
| 43 | | |
| 44 | | /** |
| 45 | | * Create the Autobase apply function for identity registry |
| 46 | | * |
| 47 | | * @param {Object} opts - Options |
| 48 | | * @param {string} opts.prefix - Key prefix for namespacing (default: '') |
| 49 | | * @param {boolean} opts.contractValidation - Enable contract validation (default: false for migration compat) |
| 50 | | * @returns {Function} Autobase apply function |
| 51 | | */ |
| 52 | | export function createApplyFunction (opts = {}) { |
| 53 | | const prefix = opts.prefix || '' |
| 54 | | const enableContract = opts.contractValidation === true |
| 55 | | |
| 56 | | return async function apply (batch, view, base) { |
| 57 | | const b = view.batch({ update: false }) |
| 58 | | |
| 59 | | try { |
| 60 | | for (const node of batch) { |
| 61 | | try { |
| 62 | | const op = decodeOp(node.value) |
| 63 | | const validation = validateOp(op) |
| 64 | | if (!validation.valid) { |
| 65 | | console.error(`[IdentityApply] Invalid op: ${validation.error}`) |
| 66 | | continue |
| 67 | | } |
| 68 | | |
| 69 | | // Contract validation: check writer permissions |
| 70 | | if (enableContract && node.from) { |
| 71 | | const writerKey = b4a.toString(node.from.key, 'hex') |
| 72 | | const violation = await checkContract(b, prefix, writerKey, op) |
| 73 | | if (violation) { |
| 74 | | console.error(`[IdentityApply] Contract violation: ${violation} (writer: ${writerKey.slice(0, 16)}..., op: ${op.type})`) |
| 75 | | continue // Drop the operation |
| 76 | | } |
| 77 | | } |
| 78 | | |
| 79 | | // The op's own clock, stamped by encodeOp on the authoring peer. Every timestamp and |
| 80 | | // every time COMPARISON below uses it, so this apply is a pure function of the log. |
| 81 | | // |
| 82 | | // ⚠ The `at` fallback is for ops written BEFORE this field existed, already |
| 83 | | // durable in deployed logs. Those replay non-deterministically exactly as they do today — |
| 84 | | // no worse, and unfixable without rewriting history. Every NEW op converges. |
| 85 | | const at = op.timestamp || Date.now() |
| 86 | | |
| 87 | | switch (op.type) { |
| 88 | | case OpTypes.CREATE_USER: { |
| 89 | | const key = `${prefix}user:${op.userId}` |
| 90 | | const existing = await b.get(key) |
| 91 | | if (existing) continue // Don't overwrite |
| 92 | | |
| 93 | | // Deterministic admin bootstrap: the FIRST user created gets |
| 94 | | // admin permissions. All subsequent users get read-only. |
| 95 | | // This decision happens in the apply function (deterministic, |
| 96 | | // linearized by Autobase) — NOT in the caller (which would be |
| 97 | | // racy in multi-writer scenarios). |
| 98 | | const isFirstUser = !(await hasAnyUser(b, prefix)) |
| 99 | | const permissions = isFirstUser |
| 100 | | ? ['read', 'write', 'admin'] |
| 101 | | : ['read'] |
| 102 | | const resources = isFirstUser |
| 103 | | ? [{ name: '*', permissions: ['read', 'write', 'admin'] }] |
| 104 | | : [{ name: '*', permissions: ['read'] }] |
| 105 | | |
| 106 | | const user = { |
| 107 | | userId: op.userId, |
| 108 | | username: op.username || null, |
| 109 | | name: op.name || 'Anonymous', |
| 110 | | email: op.email || null, |
| 111 | | profilePicture: op.profilePicture || null, |
| 112 | | globalPermissions: permissions, |
| 113 | | resources, |
| 114 | | identities: op.identities || [], |
| 115 | | createdAt: op.createdAt || at, |
| 116 | | updatedAt: op.updatedAt || at |
| 117 | | } |
| 118 | | await b.put(key, user) |
| 119 | | |
| 120 | | // Index identities |
| 121 | | for (const id of user.identities) { |
| 122 | | await b.put(`${prefix}user-identity:${id}`, { userId: op.userId }) |
| 123 | | } |
| 124 | | break |
| 125 | | } |
| 126 | | |
| 127 | | case OpTypes.UPDATE_USER: { |
| 128 | | const key = `${prefix}user:${op.userId}` |
| 129 | | const existing = await b.get(key) |
| 130 | | if (!existing) continue |
| 131 | | |
| 132 | | const user = existing.value |
| 133 | | if (op.username !== undefined) user.username = op.username |
| 134 | | if (op.name !== undefined) user.name = op.name |
| 135 | | if (op.email !== undefined) user.email = op.email |
| 136 | | if (op.profilePicture !== undefined) user.profilePicture = op.profilePicture |
| 137 | | if (op.theme !== undefined) user.theme = op.theme |
| 138 | | if (op.globalPermissions !== undefined) user.globalPermissions = op.globalPermissions |
| 139 | | user.updatedAt = at |
| 140 | | await b.put(key, user) |
| 141 | | break |
| 142 | | } |
| 143 | | |
| 144 | | case OpTypes.DELETE_USER: { |
| 145 | | const key = `${prefix}user:${op.userId}` |
| 146 | | const existing = await b.get(key) |
| 147 | | if (!existing) continue |
| 148 | | |
| 149 | | const user = existing.value |
| 150 | | // Remove identity index entries AND the identity records + their |
| 151 | | // reverse indexes FROM THE VIEW. Since the view-migration these |
| 152 | | // records live in the view; deleteUserCascade only cleaned the |
| 153 | | // legacy db, so the view's pubkey/sshkey/noisekey indexes |
| 154 | | // survived a delete. Mirror REGISTER_IDENTITY's index writes in |
| 155 | | // reverse so a cascade is complete and replicates to peers. |
| 156 | | for (const id of (user.identities || [])) { |
| 157 | | await b.del(`${prefix}user-identity:${id}`) |
| 158 | | const idEntry = await b.get(`${prefix}identity:${id}`) |
| 159 | | if (idEntry) { |
| 160 | | const idRec = idEntry.value |
| 161 | | if (idRec.publicKey) await b.del(`${prefix}pubkey:${idRec.publicKey}`) |
| 162 | | if (idRec.method === 'ssh-key' && idRec.credentials && idRec.credentials.fingerprint) { |
| 163 | | await b.del(`${prefix}sshkey:${idRec.credentials.fingerprint}`) |
| 164 | | } |
| 165 | | if (idRec.method === 'noise-key' && idRec.credentials && idRec.credentials.publicKey) { |
| 166 | | await b.del(`${prefix}noisekey:${idRec.credentials.publicKey}`) |
| 167 | | } |
| 168 | | if (idRec.method === 'atproto' && idRec.credentials) { |
| 169 | | if (idRec.credentials.did) await b.del(`${prefix}atproto-did:${idRec.credentials.did}`) |
| 170 | | if (idRec.credentials.handle) await b.del(`${prefix}atproto-handle:${idRec.credentials.handle}`) |
| 171 | | } |
| 172 | | await b.del(`${prefix}identity:${id}`) |
| 173 | | } |
| 174 | | } |
| 175 | | if (user.username) await b.del(`${prefix}username:${user.username}`) |
| 176 | | await b.del(key) |
| 177 | | break |
| 178 | | } |
| 179 | | |
| 180 | | case OpTypes.ADD_IDENTITY: { |
| 181 | | const key = `${prefix}user:${op.userId}` |
| 182 | | const existing = await b.get(key) |
| 183 | | if (!existing) continue |
| 184 | | |
| 185 | | const user = existing.value |
| 186 | | if (!user.identities.includes(op.identityId)) { |
| 187 | | user.identities.push(op.identityId) |
| 188 | | user.updatedAt = at |
| 189 | | await b.put(key, user) |
| 190 | | await b.put(`${prefix}user-identity:${op.identityId}`, { userId: op.userId }) |
| 191 | | } |
| 192 | | break |
| 193 | | } |
| 194 | | |
| 195 | | case OpTypes.REMOVE_IDENTITY: { |
| 196 | | const key = `${prefix}user:${op.userId}` |
| 197 | | const existing = await b.get(key) |
| 198 | | if (!existing) continue |
| 199 | | |
| 200 | | const user = existing.value |
| 201 | | user.identities = user.identities.filter(id => id !== op.identityId) |
| 202 | | user.updatedAt = at |
| 203 | | await b.put(key, user) |
| 204 | | await b.del(`${prefix}user-identity:${op.identityId}`) |
| 205 | | break |
| 206 | | } |
| 207 | | |
| 208 | | case OpTypes.LINK_IDENTITY: { |
| 209 | | await b.put(`${prefix}user-identity:${op.identityId}`, { userId: op.userId }) |
| 210 | | const key = `${prefix}user:${op.userId}` |
| 211 | | const existing = await b.get(key) |
| 212 | | if (existing) { |
| 213 | | const user = existing.value |
| 214 | | if (!user.identities.includes(op.identityId)) { |
| 215 | | user.identities.push(op.identityId) |
| 216 | | user.updatedAt = at |
| 217 | | await b.put(key, user) |
| 218 | | } |
| 219 | | } |
| 220 | | // Stamp the owning userId onto the identity record IN THE VIEW. |
| 221 | | // Since the view-migration, identity records live in the view and |
| 222 | | // getIdentity reads it first; the registry method only wrote |
| 223 | | // userId to the legacy db, leaving the view record without it |
| 224 | | // (cross-daemon link ownership invisible). Idempotent. |
| 225 | | const idKey = `${prefix}identity:${op.identityId}` |
| 226 | | const idEntry = await b.get(idKey) |
| 227 | | if (idEntry && idEntry.value.userId !== op.userId) { |
| 228 | | const idRec = idEntry.value |
| 229 | | idRec.userId = op.userId |
| 230 | | idRec.updatedAt = at |
| 231 | | await b.put(idKey, idRec) |
| 232 | | } |
| 233 | | break |
| 234 | | } |
| 235 | | |
| 236 | | case OpTypes.UPGRADE_PERMISSIONS: { |
| 237 | | const key = `${prefix}user:${op.userId}` |
| 238 | | const existing = await b.get(key) |
| 239 | | if (!existing) continue |
| 240 | | |
| 241 | | const user = existing.value |
| 242 | | const resourceName = op.resourceName |
| 243 | | |
| 244 | | if (resourceName === '*') { |
| 245 | | // Global permissions |
| 246 | | user.globalPermissions = op.permissions |
| 247 | | } else { |
| 248 | | // Resource-specific permissions |
| 249 | | if (!user.resources) user.resources = [] |
| 250 | | const idx = user.resources.findIndex(r => r.name === resourceName) |
| 251 | | if (idx >= 0) { |
| 252 | | user.resources[idx].permissions = op.permissions |
| 253 | | } else { |
| 254 | | user.resources.push({ name: resourceName, permissions: op.permissions }) |
| 255 | | } |
| 256 | | } |
| 257 | | user.updatedAt = at |
| 258 | | await b.put(key, user) |
| 259 | | break |
| 260 | | } |
| 261 | | |
| 262 | | case OpTypes.MERGE_ACCOUNTS: { |
| 263 | | const primaryKey = `${prefix}user:${op.primaryUserId}` |
| 264 | | const secondaryKey = `${prefix}user:${op.secondaryUserId}` |
| 265 | | |
| 266 | | const primary = await b.get(primaryKey) |
| 267 | | const secondary = await b.get(secondaryKey) |
| 268 | | |
| 269 | | if (!primary || !secondary) continue |
| 270 | | |
| 271 | | const pUser = primary.value |
| 272 | | const sUser = secondary.value |
| 273 | | |
| 274 | | // Merge identities |
| 275 | | for (const id of sUser.identities) { |
| 276 | | if (!pUser.identities.includes(id)) { |
| 277 | | pUser.identities.push(id) |
| 278 | | } |
| 279 | | await b.put(`${prefix}user-identity:${id}`, { userId: op.primaryUserId }) |
| 280 | | } |
| 281 | | |
| 282 | | // Merge resources |
| 283 | | for (const res of (sUser.resources || [])) { |
| 284 | | const idx = (pUser.resources || []).findIndex(r => r.name === res.name) |
| 285 | | if (idx < 0) { |
| 286 | | if (!pUser.resources) pUser.resources = [] |
| 287 | | pUser.resources.push(res) |
| 288 | | } |
| 289 | | } |
| 290 | | |
| 291 | | // Merge global permissions |
| 292 | | const allPerms = new Set([...pUser.globalPermissions, ...sUser.globalPermissions]) |
| 293 | | pUser.globalPermissions = [...allPerms] |
| 294 | | |
| 295 | | pUser.updatedAt = at |
| 296 | | await b.put(primaryKey, pUser) |
| 297 | | |
| 298 | | // Mark secondary as merged |
| 299 | | sUser.mergedInto = op.primaryUserId |
| 300 | | sUser.updatedAt = at |
| 301 | | await b.put(secondaryKey, sUser) |
| 302 | | break |
| 303 | | } |
| 304 | | |
| 305 | | case OpTypes.REVOKE_IDENTITY: { |
| 306 | | // Write revocation record to view (consensus-visible) |
| 307 | | // Direct-write db is updated separately in registry method |
| 308 | | await b.put(`${prefix}revoked:${op.identityId}`, { |
| 309 | | identityId: op.identityId, |
| 310 | | revokedAt: op.revokedAt || at, |
| 311 | | reason: op.reason || null |
| 312 | | }) |
| 313 | | break |
| 314 | | } |
| 315 | | |
| 316 | | case OpTypes.RESTORE_IDENTITY: { |
| 317 | | await b.del(`${prefix}revoked:${op.identityId}`) |
| 318 | | break |
| 319 | | } |
| 320 | | |
| 321 | | case OpTypes.DEACTIVATE_USER: { |
| 322 | | const key = `${prefix}user:${op.userId}` |
| 323 | | const existing = await b.get(key) |
| 324 | | if (!existing) continue |
| 325 | | |
| 326 | | const user = existing.value |
| 327 | | |
| 328 | | // Guard: can't deactivate the last admin |
| 329 | | if (user.globalPermissions?.includes('admin')) { |
| 330 | | let adminCount = 0 |
| 331 | | for await (const e of b.createReadStream({ gt: `${prefix}user:`, lt: `${prefix}user:\xff` })) { |
| 332 | | if (e.value.globalPermissions?.includes('admin') && !e.value.deactivatedAt && !e.value.mergedInto) adminCount++ |
| 333 | | } |
| 334 | | if (adminCount <= 1) continue // Silently skip — can't deactivate last admin |
| 335 | | } |
| 336 | | |
| 337 | | user.deactivatedAt = at |
| 338 | | user.deactivatedReason = op.reason || null |
| 339 | | user.updatedAt = at |
| 340 | | await b.put(key, user) |
| 341 | | break |
| 342 | | } |
| 343 | | |
| 344 | | case OpTypes.REACTIVATE_USER: { |
| 345 | | const key = `${prefix}user:${op.userId}` |
| 346 | | const existing = await b.get(key) |
| 347 | | if (!existing) continue |
| 348 | | |
| 349 | | const user = existing.value |
| 350 | | delete user.deactivatedAt |
| 351 | | delete user.deactivatedReason |
| 352 | | user.updatedAt = at |
| 353 | | await b.put(key, user) |
| 354 | | break |
| 355 | | } |
| 356 | | |
| 357 | | case OpTypes.CREATE_LINK_TOKEN: { |
| 358 | | // Store the token row keyed by its hash. Idempotent — a |
| 359 | | // duplicate op for the same hash is silently dropped. |
| 360 | | const key = `${prefix}link-token:${op.tokenHash}` |
| 361 | | const existing = await b.get(key) |
| 362 | | if (existing) break |
| 363 | | await b.put(key, { |
| 364 | | tokenHash: op.tokenHash, |
| 365 | | userId: op.userId, |
| 366 | | expiresAt: op.expiresAt, |
| 367 | | createdAt: op.createdAt || at, |
| 368 | | consumed: false |
| 369 | | }) |
| 370 | | break |
| 371 | | } |
| 372 | | |
| 373 | | case OpTypes.CONSUME_LINK_TOKEN: { |
| 374 | | const tokenKey = `${prefix}link-token:${op.tokenHash}` |
| 375 | | const tokenEntry = await b.get(tokenKey) |
| 376 | | if (!tokenEntry) break // unknown token |
| 377 | | const token = tokenEntry.value |
| 378 | | if (token.consumed) break // double-consume |
| 379 | | if (token.expiresAt && token.expiresAt < at) break // expired |
| 380 | | |
| 381 | | // 1. Mark token consumed (kept for audit, never deleted) |
| 382 | | await b.put(tokenKey, { |
| 383 | | ...token, |
| 384 | | consumed: true, |
| 385 | | consumedAt: at, |
| 386 | | consumedBy: op.newIdentityId |
| 387 | | }) |
| 388 | | |
| 389 | | // 2. Attach the new identity to the token's target user |
| 390 | | const targetKey = `${prefix}user:${token.userId}` |
| 391 | | const targetEntry = await b.get(targetKey) |
| 392 | | if (targetEntry) { |
| 393 | | const target = targetEntry.value |
| 394 | | if (!target.identities.includes(op.newIdentityId)) { |
| 395 | | target.identities.push(op.newIdentityId) |
| 396 | | target.updatedAt = at |
| 397 | | await b.put(targetKey, target) |
| 398 | | } |
| 399 | | // Always rewrite the user-identity index — if the identity |
| 400 | | // was previously linked to a throwaway, this rebinds it. |
| 401 | | await b.put(`${prefix}user-identity:${op.newIdentityId}`, { userId: token.userId }) |
| 402 | | } |
| 403 | | |
| 404 | | // 3. Optionally deactivate the throwaway user the new |
| 405 | | // identity used to belong to. Strip the identity from |
| 406 | | // that user first so it isn't double-counted. |
| 407 | | if (op.deactivateUserId && op.deactivateUserId !== token.userId) { |
| 408 | | const dKey = `${prefix}user:${op.deactivateUserId}` |
| 409 | | const dEntry = await b.get(dKey) |
| 410 | | if (dEntry) { |
| 411 | | const u = dEntry.value |
| 412 | | u.identities = (u.identities || []).filter(id => id !== op.newIdentityId) |
| 413 | | u.deactivatedAt = at |
| 414 | | u.deactivatedReason = 'merged-via-link-token' |
| 415 | | u.updatedAt = at |
| 416 | | await b.put(dKey, u) |
| 417 | | } |
| 418 | | } |
| 419 | | break |
| 420 | | } |
| 421 | | |
| 422 | | case OpTypes.SET_USERNAME: { |
| 423 | | const key = `${prefix}user:${op.userId}` |
| 424 | | const existing = await b.get(key) |
| 425 | | if (!existing) continue |
| 426 | | |
| 427 | | const user = existing.value |
| 428 | | |
| 429 | | // Remove old username index |
| 430 | | if (user.username) { |
| 431 | | await b.del(`${prefix}username:${user.username}`) |
| 432 | | } |
| 433 | | |
| 434 | | // Set new username |
| 435 | | user.username = op.username |
| 436 | | user.updatedAt = at |
| 437 | | await b.put(key, user) |
| 438 | | await b.put(`${prefix}username:${op.username}`, { userId: op.userId }) |
| 439 | | break |
| 440 | | } |
| 441 | | |
| 442 | | case OpTypes.ADD_WRITER: { |
| 443 | | // Audit trail in the view |
| 444 | | await b.put(`${prefix}writer:${op.writerKey}`, { |
| 445 | | addedAt: at, |
| 446 | | addedBy: op.addedBy || null, |
| 447 | | role: op.role || 'writer' |
| 448 | | }) |
| 449 | | // Propagate to the Autobase host so the new writer's core |
| 450 | | // participates in linearization. |
| 451 | | if (base && typeof base.addWriter === 'function') { |
| 452 | | try { |
| 453 | | await base.addWriter(b4a.from(op.writerKey, 'hex'), { |
| 454 | | indexer: op.role === 'indexer' |
| 455 | | }) |
| 456 | | } catch (err) { |
| 457 | | console.error('[IdentityApply] base.addWriter failed:', err.message) |
| 458 | | } |
| 459 | | } |
| 460 | | break |
| 461 | | } |
| 462 | | |
| 463 | | case OpTypes.REMOVE_WRITER: { |
| 464 | | await b.del(`${prefix}writer:${op.writerKey}`) |
| 465 | | if (base && typeof base.removeWriter === 'function') { |
| 466 | | try { |
| 467 | | await base.removeWriter(b4a.from(op.writerKey, 'hex')) |
| 468 | | } catch (err) { |
| 469 | | console.error('[IdentityApply] base.removeWriter failed:', err.message) |
| 470 | | } |
| 471 | | } |
| 472 | | break |
| 473 | | } |
| 474 | | |
| 475 | | case OpTypes.REGISTER_MIRROR_WRITERS: { |
| 476 | | // View-only record. The enclosing app watches this key |
| 477 | | // range and issues in-band addWriter ops on the matching |
| 478 | | // OTHER autobases it hosts. Apply must stay deterministic: |
| 479 | | // no side effects on other autobases from here. |
| 480 | | await b.put(`${prefix}mirror-writers:${op.devicePubkey}`, { |
| 481 | | keys: op.keys, |
| 482 | | recordedAt: at |
| 483 | | }) |
| 484 | | break |
| 485 | | } |
| 486 | | |
| 487 | | case OpTypes.REGISTER_IDENTITY: { |
| 488 | | // Full identity record into the view (replicated to mirrors). |
| 489 | | // Replaces the previous direct-write to a per-daemon |
| 490 | | // Hyperbee (`db`), which was local-only. Mirror peers now |
| 491 | | // see the full record + reverse indexes via standard |
| 492 | | // autobase replication. See pear-git-v3/test/ |
| 493 | | // identity-record-replication.test.js for the proof. |
| 494 | | const identity = op.identity |
| 495 | | if (!identity || !identity.identityId) break |
| 496 | | await b.put(`${prefix}identity:${identity.identityId}`, identity) |
| 497 | | if (identity.publicKey) { |
| 498 | | await b.put(`${prefix}pubkey:${identity.publicKey}`, { identityId: identity.identityId }) |
| 499 | | } |
| 500 | | if (identity.method === 'ssh-key' && identity.credentials && identity.credentials.fingerprint) { |
| 501 | | await b.put(`${prefix}sshkey:${identity.credentials.fingerprint}`, { identityId: identity.identityId }) |
| 502 | | } |
| 503 | | if (identity.method === 'noise-key' && identity.credentials && identity.credentials.publicKey) { |
| 504 | | await b.put(`${prefix}noisekey:${identity.credentials.publicKey}`, { identityId: identity.identityId }) |
| 505 | | } |
| 506 | | if (identity.method === 'atproto' && identity.credentials) { |
| 507 | | if (identity.credentials.did) { |
| 508 | | await b.put(`${prefix}atproto-did:${identity.credentials.did}`, { identityId: identity.identityId }) |
| 509 | | } |
| 510 | | if (identity.credentials.handle) { |
| 511 | | await b.put(`${prefix}atproto-handle:${identity.credentials.handle}`, { identityId: identity.identityId }) |
| 512 | | } |
| 513 | | } |
| 514 | | break |
| 515 | | } |
| 516 | | } |
| 517 | | } catch (err) { |
| 518 | | console.error('[IdentityApply] Skipping malformed op:', err.message) |
| 519 | | continue |
| 520 | | } |
| 521 | | } |
| 522 | | |
| 523 | | await b.flush() |
| 524 | | } catch (err) { |
| 525 | | console.error('[IdentityApply] Batch error:', err.message) |
| 526 | | await b.close() |
| 527 | | throw err |
| 528 | | } |
| 529 | | } |
| 530 | | } |
| 531 | | |
| 532 | | /** |
| 533 | | * Check if a writer has permission to execute an operation. |
| 534 | | * |
| 535 | | * Resolves the writer's key to a user by scanning all users' identities, |
| 536 | | * then checks if that user has the required permission level. |
| 537 | | * |
| 538 | | * @param {Object} b - Hyperbee batch |
| 539 | | * @param {string} prefix - Key prefix |
| 540 | | * @param {string} writerKey - Writer's Hypercore public key (hex) |
| 541 | | * @param {Object} op - The operation being executed |
| 542 | | * @returns {string|null} Violation reason, or null if authorized |
| 543 | | */ |
| 544 | | async function checkContract (b, prefix, writerKey, op) { |
| 545 | | // CREATE_USER is always allowed (autoRegister handles first-user-admin) |
| 546 | | if (op.type === OpTypes.CREATE_USER) return null |
| 547 | | |
| 548 | | // Find the user associated with this writer key |
| 549 | | const writerUser = await resolveWriterUser(b, prefix, writerKey) |
| 550 | | |
| 551 | | // If no user found for this writer, check if ANY users exist yet. |
| 552 | | // During bootstrap (empty registry), allow all ops from the first writer. |
| 553 | | if (!writerUser) { |
| 554 | | const hasUsers = await hasAnyUser(b, prefix) |
| 555 | | if (!hasUsers) return null // Bootstrap: empty registry, first writer is trusted |
| 556 | | return `Writer ${writerKey.slice(0, 16)} has no associated user` |
| 557 | | } |
| 558 | | |
| 559 | | const isAdmin = writerUser.globalPermissions && writerUser.globalPermissions.includes('admin') |
| 560 | | |
| 561 | | // Admin-only operations |
| 562 | | if (ADMIN_OPS.has(op.type)) { |
| 563 | | if (!isAdmin) return `${op.type} requires admin permissions` |
| 564 | | return null |
| 565 | | } |
| 566 | | |
| 567 | | // Self-or-admin operations |
| 568 | | if (SELF_OR_ADMIN_OPS.has(op.type)) { |
| 569 | | if (isAdmin) return null |
| 570 | | if (op.userId === writerUser.userId) return null |
| 571 | | return `${op.type} requires admin or self (writer is ${writerUser.userId}, op targets ${op.userId})` |
| 572 | | } |
| 573 | | |
| 574 | | return null // Unknown op types pass through (validated by validateOp) |
| 575 | | } |
| 576 | | |
| 577 | | /** |
| 578 | | * Find the user associated with a writer's Hypercore key. |
| 579 | | * Looks up the writer key as a pubkey identity, then resolves to user. |
| 580 | | */ |
| 581 | | async function resolveWriterUser (b, prefix, writerKey) { |
| 582 | | // Check pubkey reverse lookup (writer key may be registered as an identity) |
| 583 | | const pubkeyEntry = await b.get(`${prefix}pubkey:${writerKey}`) |
| 584 | | if (pubkeyEntry) { |
| 585 | | const identityLink = await b.get(`${prefix}user-identity:${pubkeyEntry.value.identityId}`) |
| 586 | | if (identityLink) { |
| 587 | | const userEntry = await b.get(`${prefix}user:${identityLink.value.userId}`) |
| 588 | | if (userEntry) return userEntry.value |
| 589 | | } |
| 590 | | } |
| 591 | | |
| 592 | | // Scan all users to find one with this writer key in their identities |
| 593 | | // (fallback for when the key isn't indexed as a pubkey) |
| 594 | | for await (const entry of b.createReadStream({ gt: `${prefix}user:`, lt: `${prefix}user:\xff` })) { |
| 595 | | const user = entry.value |
| 596 | | if (user.identities && user.identities.includes(writerKey)) { |
| 597 | | return user |
| 598 | | } |
| 599 | | } |
| 600 | | |
| 601 | | return null |
| 602 | | } |
| 603 | | |
| 604 | | async function hasAnyUser (b, prefix) { |
| 605 | | for await (const _ of b.createReadStream({ gt: `${prefix}user:`, lt: `${prefix}user:\xff`, limit: 1 })) { |
| 606 | | return true |
| 607 | | } |
| 608 | | return false |
| 609 | | } |
| 1 | // Moved to `hyper-identity-core`. Kept as a re-export — see identity-operations.js. |
| 2 | // |
| 3 | // ⚠ The core's apply speaks `addWriter(key, { isIndexer })`. This package is the AUTOBASE binding, |
| 4 | // so it passes an `adaptHost` that translates to autobase's `{ indexer }` — see |
| 5 | // identity-registry.js. Calling the core's apply from here WITHOUT that adapter would hand autobase |
| 6 | // an option it does not know, and autobase would create a plain writer where an indexer was meant. |
| 7 | export { createApplyFunction } from 'hyper-identity-core/apply' |