effect-ownership.spec.ts (20454B)
1 import { expect, test, type Page } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { fileURLToPath } from 'node:url'; 4 import { createHash } from 'node:crypto'; 5 import { createStaticHarness } from '../integration/harness/static.ts'; 6 import type * as Effects from './harness/effect-ownership.ts'; 7 import type { PublicRecordHandle } from '../../src/lib/persistence/records.ts'; 8 import type { PublicQuotaRepository } from '../../src/lib/persistence/quota.ts'; 9 import type { BrowserDatabase } from '../../src/lib/persistence/database.ts'; 10 import type { 11 ExtensionAdapter, 12 ApprovedSignResult 13 } from '../../src/lib/nostr/extension.ts'; 14 import type { ApprovedPublicSigning } from '../../src/lib/nostr/approved-signing.ts'; 15 import type { 16 PublicEffectLease, 17 PublicEffectResult 18 } from '../../src/lib/runtime/effect-ownership.ts'; 19 declare global { 20 interface Window { 21 hcp054: typeof Effects; 22 hcp054Fixture: ReturnType<typeof Effects.makeFixture>; 23 hcp054Record: PublicRecordHandle; 24 hcp054Repository: PublicQuotaRepository; 25 hcp054Database: BrowserDatabase; 26 hcp054Adapter: ExtensionAdapter; 27 hcp054Approval: ApprovedPublicSigning; 28 hcp054Owner: string; 29 hcp054Id: string; 30 hcp054Wire: string; 31 hcp054Counts: { keys: number; signs: number; work: number }; 32 hcp054Release: () => void; 33 hcp054SignStarted: () => void; 34 hcp054Inner: ApprovedSignResult; 35 hcp054Lease: PublicEffectLease; 36 hcp054Task: Promise<PublicEffectResult<unknown>>; 37 } 38 } 39 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; 40 test.beforeAll(async () => { 41 server = await createStaticHarness(); 42 const result = await build({ 43 configFile: false, 44 logLevel: 'silent', 45 build: { 46 write: false, 47 minify: false, 48 lib: { 49 entry: fileURLToPath( 50 new URL('./harness/effect-ownership.ts', import.meta.url) 51 ), 52 name: 'hcp054', 53 formats: ['iife'] 54 } 55 } 56 }); 57 const output = Array.isArray(result) ? result[0] : result; 58 if (!('output' in output)) throw new Error('missing bundle'); 59 const chunks = output.output.filter((item) => item.type === 'chunk'); 60 expect(chunks).toHaveLength(1); 61 bundle = chunks[0].code; 62 console.log( 63 JSON.stringify({ 64 fixture: 'HCP054_ACTUAL_WEB_LOCKS_IDB_SDK_MULTITAB', 65 bundleSha256: createHash('sha256').update(bundle).digest('hex'), 66 moduleIds: Object.keys(chunks[0].modules), 67 qualification: 68 'real local Chromium/source only; no named extension/externalclient/global cancellation claim' 69 }) 70 ); 71 }); 72 test.afterAll(async () => server.close()); 73 type Shared = { owner: string; id: string; wire: string }; 74 async function load(page: Page, shared?: Shared): Promise<Shared> { 75 await page.goto(server.url + '/search'); 76 await page.addScriptTag({ content: bundle }); 77 return page.evaluate(async (shared) => { 78 const s = window.hcp054; 79 const f = shared ? undefined : s.makeFixture(); 80 if (f) window.hcp054Fixture = f; 81 const owner = shared?.owner ?? f!.owner, 82 id = shared?.id ?? f!.id, 83 wire = shared?.wire ?? s.publicRecordWire(f!.record, owner, id)!; 84 const decoded = s.decodePublicRecord(wire, owner, id); 85 if (!decoded.ok) throw new Error('invalid public fixture'); 86 window.hcp054Owner = owner; 87 window.hcp054Id = id; 88 window.hcp054Wire = wire; 89 window.hcp054Record = decoded.value; 90 const opened = await s.openBrowserDatabase(); 91 if (opened.state !== 'ready') throw new Error(opened.reason); 92 window.hcp054Database = opened.owner; 93 const repo = s.createPublicQuotaRepository(opened.owner, owner); 94 if (!repo) throw new Error('invalid repository'); 95 window.hcp054Repository = repo; 96 window.hcp054Counts = { keys: 0, signs: 0, work: 0 }; 97 window.nostr = { 98 getPublicKey: () => { 99 window.hcp054Counts.keys++; 100 return Promise.resolve(owner); 101 }, 102 signEvent: ( 103 template: Parameters<ReturnType<typeof s.makeFixture>['sign']>[0] 104 ) => { 105 window.hcp054Counts.signs++; 106 if (!f) throw new Error('unexpected second-tab signature'); 107 return Promise.resolve(f.sign(template)); 108 } 109 }; 110 window.hcp054Adapter = s.createExtensionAdapter(); 111 await s.connectExtensionAdapter(window.hcp054Adapter); 112 const approval = s.approveCapturedPublicSigning( 113 decoded.value, 114 owner, 115 id, 116 'reviewed_captured_operation' 117 ); 118 if (!approval) throw new Error('missing approval'); 119 window.hcp054Approval = approval; 120 window.hcp054Counts = { keys: 0, signs: 0, work: 0 }; 121 return { owner, id, wire }; 122 }, shared); 123 } 124 async function begin( 125 page: Page, 126 mode: 'hold' | 'sign_hold' | 'forgotten' | 'commit' | 'wrong_session' = 'hold' 127 ) { 128 await page.evaluate((mode) => { 129 const s = window.hcp054, 130 context = s.extensionOwnershipCapture(window.hcp054Adapter); 131 if (!context) throw new Error('missing context'); 132 const signStarted = new Promise<void>((resolve) => { 133 window.hcp054SignStarted = resolve; 134 }); 135 if (mode === 'sign_hold' || mode === 'forgotten') 136 window.nostr = { 137 getPublicKey: () => { 138 window.hcp054Counts.keys++; 139 return Promise.resolve(window.hcp054Owner); 140 }, 141 signEvent: ( 142 template: Parameters<ReturnType<typeof s.makeFixture>['sign']>[0] 143 ) => { 144 window.hcp054Counts.signs++; 145 window.hcp054SignStarted(); 146 return new Promise((resolve) => { 147 window.hcp054Release = () => 148 resolve(window.hcp054Fixture.sign(template)); 149 }); 150 } 151 }; 152 const captured = 153 mode === 'wrong_session' ? { ...context, session: Symbol() } : context; 154 window.hcp054Task = s.runCapturedPublicEffect( 155 window.hcp054Repository, 156 window.hcp054Record, 157 window.hcp054Id, 158 captured, 159 'reviewed_captured_operation', 160 async (lease) => { 161 window.hcp054Counts.work++; 162 window.hcp054Lease = lease; 163 if (mode === 'hold') { 164 await new Promise<void>((resolve) => { 165 window.hcp054Release = resolve; 166 }); 167 return 'original'; 168 } 169 if (mode === 'forgotten') { 170 void s 171 .signApprovedExtensionAdapter( 172 window.hcp054Adapter, 173 window.hcp054Approval, 174 lease 175 ) 176 .then((result) => { 177 window.hcp054Inner = result; 178 }); 179 await signStarted; 180 return 'forgotten'; 181 } 182 const result = await s.signApprovedExtensionAdapter( 183 window.hcp054Adapter, 184 window.hcp054Approval, 185 lease 186 ); 187 if (mode !== 'commit' || result.status !== 'signed') return result; 188 const next = s.preparePublicArtifactTransition( 189 window.hcp054Record, 190 window.hcp054Owner, 191 window.hcp054Id, 192 result.artifact 193 ); 194 if (!next.ok) throw new Error(next.reason); 195 const stored = await s.commitPublicOperationTransition( 196 window.hcp054Repository, 197 next.value 198 ); 199 if (!stored.ok) throw new Error(stored.reason); 200 return s.capturedArtifactSnapshot(result.artifact)?.wire; 201 } 202 ); 203 }, mode); 204 } 205 async function retry(page: Page) { 206 return page.evaluate(async () => { 207 const s = window.hcp054, 208 context = s.extensionOwnershipCapture(window.hcp054Adapter); 209 if (!context) throw new Error('missing context'); 210 const result = await s.runCapturedPublicEffect( 211 window.hcp054Repository, 212 window.hcp054Record, 213 window.hcp054Id, 214 context, 215 'reviewed_captured_operation', 216 () => { 217 window.hcp054Counts.work++; 218 return Promise.resolve('unexpected replay'); 219 } 220 ); 221 const row = 222 'record' in result 223 ? s.publicRecordSnapshot( 224 result.record, 225 window.hcp054Owner, 226 window.hcp054Id 227 ) 228 : undefined; 229 return { status: result.status, row, counts: window.hcp054Counts }; 230 }); 231 } 232 test.afterEach(async ({ context }) => { 233 for (const page of context.pages()) 234 if (!page.isClosed()) 235 await page.evaluate(() => { 236 window.hcp054Fixture?.close(); 237 if (window.hcp054Database) 238 window.hcp054.closeBrowserDatabase(window.hcp054Database); 239 }); 240 }); 241 test('two tabs same command create one durable original plan and only one active callback', async ({ 242 page, 243 context 244 }) => { 245 const original = await load(page), 246 other = await context.newPage(); 247 await load(other, original); 248 await begin(page); 249 await expect 250 .poll(() => page.evaluate(() => window.hcp054Counts.work)) 251 .toBe(1); 252 expect((await retry(other)).status).toBe('busy'); 253 expect((await retry(other)).counts).toEqual({ keys: 0, signs: 0, work: 0 }); 254 await page.evaluate(() => window.hcp054Release()); 255 expect( 256 await page.evaluate(async () => (await window.hcp054Task).status) 257 ).toBe('completed'); 258 const recovered = await retry(other); 259 expect(recovered.status).toBe('unknown'); 260 expect( 261 recovered.row && 262 recovered.row.family !== 'public_draft' && 263 recovered.row.capture.wire 264 ).toBe( 265 (JSON.parse(original.wire) as { capture: { wire: string } }).capture.wire 266 ); 267 expect(recovered.counts.work).toBe(0); 268 }); 269 test('page loss during actual SDK prompt retains original unknown capture without replan or signature', async ({ 270 page, 271 context 272 }) => { 273 const original = await load(page), 274 other = await context.newPage(); 275 await load(other, original); 276 await begin(page, 'sign_hold'); 277 await expect 278 .poll(() => page.evaluate(() => window.hcp054Counts.signs)) 279 .toBe(1); 280 expect((await retry(other)).status).toBe('busy'); 281 await page.evaluate(() => window.hcp054Fixture.close()); 282 await page.close(); 283 const recovered = await retry(other); 284 expect(recovered.status).toBe('unknown'); 285 expect( 286 recovered.row && 287 recovered.row.family !== 'public_draft' && 288 recovered.row.artifact 289 ).toBeNull(); 290 expect(recovered.row && JSON.stringify(recovered.row)).toBe(original.wire); 291 expect(recovered.counts).toEqual({ keys: 0, signs: 0, work: 0 }); 292 }); 293 test('forgotten SDK await keeps the browser lock and reports unknown after actual settlement', async ({ 294 page, 295 context 296 }) => { 297 const original = await load(page), 298 other = await context.newPage(); 299 await load(other, original); 300 await begin(page, 'forgotten'); 301 await expect 302 .poll(() => page.evaluate(() => window.hcp054Counts.signs)) 303 .toBe(1); 304 expect((await retry(other)).status).toBe('busy'); 305 await page.evaluate(() => window.hcp054Release()); 306 expect( 307 await page.evaluate(async () => (await window.hcp054Task).status) 308 ).toBe('unknown'); 309 expect((await retry(other)).status).toBe('unknown'); 310 }); 311 test('explicit stop during prompt fences late signature and retains lock until settlement', async ({ 312 page, 313 context 314 }) => { 315 const original = await load(page), 316 other = await context.newPage(); 317 await load(other, original); 318 await begin(page, 'sign_hold'); 319 await expect 320 .poll(() => page.evaluate(() => window.hcp054Counts.signs)) 321 .toBe(1); 322 await page.evaluate(() => window.hcp054.stopPublicEffect(window.hcp054Lease)); 323 expect((await retry(other)).status).toBe('busy'); 324 await page.evaluate(() => window.hcp054Release()); 325 expect( 326 await page.evaluate(async () => (await window.hcp054Task).status) 327 ).toBe('unknown'); 328 expect(await page.evaluate(() => window.hcp054Counts)).toEqual({ 329 keys: 1, 330 signs: 1, 331 work: 1 332 }); 333 }); 334 test('unrelated owners acquire independent locks while same owner remains busy', async ({ 335 page, 336 context 337 }) => { 338 await load(page); 339 const other = await context.newPage(); 340 await load(other); 341 await begin(page); 342 await begin(other); 343 await expect 344 .poll(() => other.evaluate(() => window.hcp054Counts.work)) 345 .toBe(1); 346 await page.evaluate(() => window.hcp054Release()); 347 await other.evaluate(() => window.hcp054Release()); 348 expect( 349 await page.evaluate(async () => (await window.hcp054Task).status) 350 ).toBe('completed'); 351 expect( 352 await other.evaluate(async () => (await window.hcp054Task).status) 353 ).toBe('completed'); 354 }); 355 test('unsupported locks perform zero writes/signing and public browsing remains usable', async ({ 356 page 357 }) => { 358 await load(page); 359 await page.evaluate(() => 360 Object.defineProperty(navigator, 'locks', { 361 value: undefined, 362 configurable: true 363 }) 364 ); 365 expect((await retry(page)).status).toBe('unavailable'); 366 const size = await page.evaluate(async () => { 367 const s = window.hcp054, 368 inventory = await s.inspectPublicStorage(window.hcp054Repository); 369 return inventory.ok 370 ? s.publicInventorySnapshot(window.hcp054Repository, inventory.value) 371 ?.rows.length 372 : -1; 373 }); 374 expect(size).toBe(0); 375 expect(await page.evaluate(() => window.hcp054Counts)).toEqual({ 376 keys: 0, 377 signs: 0, 378 work: 0 379 }); 380 expect(page.url()).toContain('/search'); 381 }); 382 test('a genuine lease with another session cannot authorize any SDK call', async ({ 383 page 384 }) => { 385 await load(page); 386 await begin(page, 'wrong_session'); 387 const result = await page.evaluate(async () => { 388 const value = await window.hcp054Task; 389 return { 390 status: value.status, 391 inner: 392 'value' in value ? (value.value as { status: string }).status : null, 393 counts: window.hcp054Counts 394 }; 395 }); 396 expect(result.inner).toBe('invalid_ownership'); 397 expect(result.counts).toEqual({ keys: 0, signs: 0, work: 1 }); 398 }); 399 test('retained signed artifact stays exact and conflicting capture cannot create another effect', async ({ 400 page, 401 context 402 }) => { 403 const original = await load(page); 404 await begin(page, 'commit'); 405 const signed = await page.evaluate(async () => { 406 const value = await window.hcp054Task; 407 return 'value' in value ? value.value : undefined; 408 }); 409 expect(typeof signed).toBe('string'); 410 const other = await context.newPage(); 411 await load(other, original); 412 const replay = await retry(other); 413 expect(replay.status).toBe('retained'); 414 expect( 415 replay.row && 416 replay.row.family !== 'public_draft' && 417 replay.row.artifact?.wire 418 ).toBe(signed); 419 expect(replay.counts).toEqual({ keys: 0, signs: 0, work: 0 }); 420 const conflict = await other.evaluate(async () => { 421 const s = window.hcp054, 422 row = s.publicRecordSnapshot( 423 window.hcp054Record, 424 window.hcp054Owner, 425 window.hcp054Id 426 ); 427 if (!row || row.family === 'public_draft') 428 throw new Error('invalid fixture'); 429 const decoded = s.decodePublicRecord( 430 JSON.stringify({ 431 ...row, 432 capture: { ...row.capture, targets: ['wss://other.example.org'] } 433 }), 434 window.hcp054Owner, 435 window.hcp054Id 436 ); 437 if (!decoded.ok) throw new Error(decoded.reason); 438 const capture = s.extensionOwnershipCapture(window.hcp054Adapter)!; 439 return ( 440 await s.runCapturedPublicEffect( 441 window.hcp054Repository, 442 decoded.value, 443 window.hcp054Id, 444 capture, 445 'reviewed_captured_operation', 446 () => Promise.resolve('forbidden') 447 ) 448 ).status; 449 }); 450 expect(conflict).toBe('conflict'); 451 }); 452 453 test('one captured lease never signs the same operation twice', async ({ 454 page 455 }) => { 456 await load(page); 457 const result = await page.evaluate(async () => { 458 const s = window.hcp054, 459 context = s.extensionOwnershipCapture(window.hcp054Adapter)!; 460 const result = await s.runCapturedPublicEffect( 461 window.hcp054Repository, 462 window.hcp054Record, 463 window.hcp054Id, 464 context, 465 'reviewed_captured_operation', 466 async (lease) => { 467 const first = await s.signApprovedExtensionAdapter( 468 window.hcp054Adapter, 469 window.hcp054Approval, 470 lease 471 ); 472 const second = await s.signApprovedExtensionAdapter( 473 window.hcp054Adapter, 474 window.hcp054Approval, 475 lease 476 ); 477 return { 478 first: first.status, 479 second: second.status, 480 secondArtifact: 'artifact' in second 481 }; 482 } 483 ); 484 return { result, counts: window.hcp054Counts }; 485 }); 486 expect(result.counts.signs).toBe(1); 487 expect(result.counts.keys).toBe(2); 488 expect(result.result.status).toBe('completed'); 489 expect('value' in result.result ? result.result.value : null).toEqual({ 490 first: 'signed', 491 second: 'stale', 492 secondArtifact: false 493 }); 494 }); 495 496 test('orphaned signing job cannot expose a late artifact or issue another SDK call', async ({ 497 page 498 }) => { 499 await load(page); 500 await begin(page, 'forgotten'); 501 await expect 502 .poll(() => page.evaluate(() => window.hcp054Counts.signs)) 503 .toBe(1); 504 await page.evaluate(() => window.hcp054Release()); 505 expect( 506 await page.evaluate(async () => (await window.hcp054Task).status) 507 ).toBe('unknown'); 508 await expect 509 .poll(() => page.evaluate(() => window.hcp054Inner?.status)) 510 .toBe('unknown'); 511 expect(await page.evaluate(() => 'artifact' in window.hcp054Inner)).toBe( 512 false 513 ); 514 expect(await page.evaluate(() => window.hcp054Counts.keys)).toBe(1); 515 }); 516 test('same author different operation contends before creating a second durable plan', async ({ 517 page, 518 context 519 }) => { 520 const original = await load(page), 521 other = await context.newPage(); 522 const id = crypto.randomUUID(), 523 row = JSON.parse(original.wire) as { id: string }; 524 await load(other, { ...original, id, wire: JSON.stringify({ ...row, id }) }); 525 await begin(page); 526 await expect 527 .poll(() => page.evaluate(() => window.hcp054Counts.work)) 528 .toBe(1); 529 expect((await retry(other)).status).toBe('busy'); 530 expect( 531 await other.evaluate(async () => { 532 const s = window.hcp054, 533 read = await s.inspectPublicStorage(window.hcp054Repository); 534 return read.ok 535 ? s.publicInventorySnapshot(window.hcp054Repository, read.value)?.rows 536 .length 537 : -1; 538 }) 539 ).toBe(1); 540 expect(await other.evaluate(() => window.hcp054Counts)).toEqual({ 541 keys: 0, 542 signs: 0, 543 work: 0 544 }); 545 await page.evaluate(() => window.hcp054Release()); 546 await page.evaluate(() => window.hcp054Task); 547 await begin(other); 548 await expect 549 .poll(() => other.evaluate(() => window.hcp054Counts.work)) 550 .toBe(1); 551 await other.evaluate(() => window.hcp054Release()); 552 expect( 553 await other.evaluate(async () => (await window.hcp054Task).status) 554 ).toBe('completed'); 555 }); 556 test('mismatched full-record approval and fabricated lease perform zero SDK calls', async ({ 557 page 558 }) => { 559 await load(page); 560 const result = await page.evaluate(async () => { 561 const s = window.hcp054, 562 capture = s.extensionOwnershipCapture(window.hcp054Adapter)!; 563 const row = s.publicRecordSnapshot( 564 window.hcp054Record, 565 window.hcp054Owner, 566 window.hcp054Id 567 ); 568 if (!row || row.family === 'public_draft') 569 throw new Error('invalid fixture'); 570 const changed = s.decodePublicRecord( 571 JSON.stringify({ 572 ...row, 573 capture: { ...row.capture, targets: ['wss://other.example.org'] } 574 }), 575 window.hcp054Owner, 576 window.hcp054Id 577 ); 578 if (!changed.ok) throw new Error(changed.reason); 579 const approval = s.approveCapturedPublicSigning( 580 changed.value, 581 window.hcp054Owner, 582 window.hcp054Id, 583 'reviewed_captured_operation' 584 ); 585 if (!approval) throw new Error('invalid changed approval'); 586 return s.runCapturedPublicEffect( 587 window.hcp054Repository, 588 window.hcp054Record, 589 window.hcp054Id, 590 capture, 591 'reviewed_captured_operation', 592 async (lease) => { 593 const mismatched = await s.signApprovedExtensionAdapter( 594 window.hcp054Adapter, 595 approval, 596 lease 597 ); 598 const forged = await s.signApprovedExtensionAdapter( 599 window.hcp054Adapter, 600 window.hcp054Approval, 601 {} as PublicEffectLease 602 ); 603 return { 604 mismatched: mismatched.status, 605 forged: forged.status, 606 counts: window.hcp054Counts 607 }; 608 } 609 ); 610 }); 611 expect(result.status).toBe('completed'); 612 expect('value' in result ? result.value : null).toEqual({ 613 mismatched: 'invalid_ownership', 614 forged: 'invalid_ownership', 615 counts: { keys: 0, signs: 0, work: 0 } 616 }); 617 });