From 51768aaa2f8de00381b2cb39affc5e3c8c1e96e8 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 22:56:41 +0100 Subject: [PATCH 1/6] feat(records): build harbor records from live public reads --- web/src/expedition/records.test.ts | 167 +++++++++++++++++++++++++++++ web/src/expedition/records.ts | 149 +++++++++++++++++++++++++ 2 files changed, 316 insertions(+) create mode 100644 web/src/expedition/records.test.ts create mode 100644 web/src/expedition/records.ts diff --git a/web/src/expedition/records.test.ts b/web/src/expedition/records.test.ts new file mode 100644 index 0000000..0d7115f --- /dev/null +++ b/web/src/expedition/records.test.ts @@ -0,0 +1,167 @@ +import {expect,test} from "bun:test"; +import {readFileSync} from "node:fs"; +import {adminRecord,keyRecord,loadRecords,refereeRecord,selfRecord,SIGNER_ACTIONS,type HarborRecord,type Read} from "./records"; + +// Shapes captured from https://test.rpc.fastnear.com (finality final) on 2026-11-13. +const root="familiar-game.testnet",pet=`qa-mochi-h1.${root}`,player=`qa-maker-h1.${root}`,items=`items.${root}`; +const pinned="CQQ63d8dNsM8oVCeEsU57USX212396zFmhtnqjgeXi1J"; +const signer="ed25519:2DP5Amx7h1JJ17P2B1VvwHMYf9adeuKuitqEEqWsRXt5"; +const account={amount:"300000000000000000000000",block_hash:"EAcU",block_height:277567587,code_hash:"11111111111111111111111111111111",global_contract_hash:pinned,locked:"0",storage_paid_at:0,storage_usage:397}; +const noKeys={block_hash:"38XB",block_height:277567588,keys:[]}; +const full=(public_key:string)=>({access_key:{nonce:1,permission:"FullAccess"},public_key}); +const playerKeys={block_hash:"38XB",block_height:1,keys:[full(signer),full("ed25519:Di7QPiWUz21DnQucab8pe6qYPAnWpZnQWXYPfwa8kn3S")]}; +const adminKeys={block_hash:"38XB",block_height:1,keys:[full("ed25519:9gqucqLaUsuGCLoK9HFDthu5nDXXZmzASyE6rZa6QNw")]}; +const config={relayer:`relayer.${root}`,pet_code_hash:pinned,items}; +const token={token_id:pet,owner_id:player,metadata:{title:pet},approved_account_ids:{}}; +const claim=(id:string)=>({operation_id:"op",id,input_hash:"0a35",lens:true,moth:false,rules_version:"tidebound_h1_v1",content_version:"first_light_v1"}); +const journey={revision:11,shells:0,burned_shells:12,commission_fulfilled:true,claims:[claim("8c5cbc6a02e6a0878b90723334c9e2e682e690a76758922ee445225a560072e5"),claim("be6ec9d4bde579ad041995d9a5a17d3473b77fd24c9866535cf1ed5a7fdf5c39")]}; +const protocol={network:"testnet",rules_version:"tidebound_h1_v1",content_version:"first_light_v1",items,registry:root}; +const ok=(value:T):Read=>({ok:true,value}),fail:Read={ok:false}; +const texts=(r:HarborRecord)=>r.lines.map(l=>l.text); +const states=(r:HarborRecord)=>r.lines.map(l=>l.state); +const self=(over:Partial[0]>={})=>selfRecord({root,player,pet,account:ok(account),keys:ok(noKeys),token:ok(token),config:ok(config),...over}); + +test("Mochi's papers state each live read",()=>{ + const r=self(); + expect(states(r)).toEqual(["read","read","read","read"]); + expect(texts(r)).toEqual([ + `Mochi’s own account is ${pet}.`, + `The harbor register lists you, ${player}, as Mochi’s keeper.`, + "No keys: no one, not you and not Familiar, can sign as Mochi’s account.", + "Runs the shared Mochi code the harbor pins; Mochi’s account carries no separate code.", + ]); + expect(r.lines[3]!.detail).toBe(`Shared code CQQ63d…Xi1J · pinned by ${root}`); +}); + +test("Mochi's papers never claim success without the read",()=>{ + const r=self({account:fail,keys:fail,token:fail,config:fail}); + expect(states(r)).toEqual(["unchecked","unchecked","unchecked","unchecked"]); + expect(texts(r).join(" ")).not.toMatch(/No keys|pins;|lists you/); + // A missing keys field is not zero keys. + expect(self({keys:ok({block_hash:"x"})}).lines[2]!.state).toBe("unchecked"); + // Config failure: the code is reported, the pin comparison is not. + const noPin=self({config:fail}).lines[3]!; + expect(noPin.state).toBe("unchecked");expect(noPin.text).toContain("couldn’t be checked"); +}); + +test("Mochi's papers report findings as findings",()=>{ + expect(self({token:ok(null)}).lines[1]).toEqual({state:"finding",text:`The harbor register has no papers for ${pet}.`}); + expect(self({token:ok({...token,owner_id:`bob.${root}`})}).lines[1]!.text).toBe(`The harbor register lists bob.${root} as Mochi’s keeper, not ${player}.`); + expect(self({token:ok({...token,token_id:`other.${root}`})}).lines[1]!.state).toBe("unchecked"); + expect(self({keys:ok(playerKeys)}).lines[2]).toMatchObject({state:"finding",text:"Mochi’s account has 2 keys, so it is not keyless."}); + expect(self({account:ok({...account,global_contract_hash:"Other1111111111111111111111"})}).lines[3]!.state).toBe("finding"); + expect(self({account:ok({...account,code_hash:"Own1111111111111111111111111111"})}).lines[3]!.text).toContain("separate code"); +}); + +test("key line reports the permission exactly and never claims a function-call key",()=>{ + const r=keyRecord({player,signerKey:signer,provider:"privy",keys:ok(playerKeys)}); + expect(texts(r).slice(0,3)).toEqual([ + "Your harbor key lives in your Privy wallet, not with Familiar.", + "This sign-in’s key: FullAccess: full control of the account.", + "Another key: FullAccess: full control of the account.", + ]); + expect(r.lines[1]!.detail).toBe("ed25519:2DP5Amx7…"); + expect(texts(r).join(" ")).not.toMatch(/FunctionCall/); + expect(r.lines.at(-1)).toMatchObject({state:"source"}); + expect(r.lines.at(-1)!.text).toContain("the chain enforces only the key permission above"); + const fc=keyRecord({player,signerKey:signer,provider:"other",keys:ok({keys:[{public_key:signer,access_key:{nonce:1,permission:{FunctionCall:{receiver_id:root,method_names:["adopt"],allowance:null}}}}]})}); + expect(texts(fc).slice(0,2)).toEqual(["The key this sign-in uses is on your account, not with Familiar.",`This sign-in’s key: FunctionCall: only ${root}, adopt.`]); +}); + +test("key line without the read or without the sign-in key says so",()=>{ + const failed=keyRecord({player,signerKey:signer,provider:"privy",keys:fail}); + expect(states(failed)).toEqual(["unchecked","source"]); + expect(texts(failed).join(" ")).not.toContain("Privy wallet"); + const missing=keyRecord({player,signerKey:"ed25519:Elsewhere",provider:"privy",keys:ok(playerKeys)}); + expect(missing.lines[0]).toEqual({state:"finding",text:"The key this sign-in uses isn’t on your account right now."}); + expect(keyRecord({player,signerKey:signer,provider:"privy",keys:ok({keys:[{public_key:signer,access_key:{permission:"Weird"}}]})}).lines[0]!.state).toBe("unchecked"); +}); + +test("signer allowlist matches every method the signer accepts",()=>{ + const source=readFileSync(new URL("../../../services/relayer/src/auth/sign.ts",import.meta.url),"utf8"); + const body=source.slice(source.indexOf("export function validateNativeIntent"),source.indexOf("export function validateSigningRequest")); + const accepted=new Set([...body.matchAll(/case "([a-z_]+)"/g),...body.matchAll(/methodName==="([a-z_]+)"/g)].map(m=>m[1]!)); + accepted.add("transfer"); + expect(new Set(SIGNER_ACTIONS.map(a=>a.method))).toEqual(accepted); +}); + +test("Tidekeeper's stamp says what the contract checks",()=>{ + const r=refereeRecord({journey:ok(journey),protocol:ok(protocol)}); + expect(texts(r)).toEqual([ + "The harbor replayed your steps and agreed they bring Mochi home.", + "Accepted return 8c5cbc…72e5","Accepted return be6ec9…5c39", + "Shells: 0 held, 12 spent.","Bram’s workshop commission is fulfilled.", + "The harbor currently plays rules tidebound_h1_v1, content first_light_v1.", + ]); + expect(r.lines[1]!.detail).toBe("Rules tidebound_h1_v1 · content first_light_v1"); + expect(texts(r).join(" ")).not.toMatch(/human|person|you played|proves/i); +}); + +test("Tidekeeper's stamp without claims or reads",()=>{ + const empty=refereeRecord({journey:ok({...journey,claims:[],shells:0,burned_shells:0,commission_fulfilled:false}),protocol:fail}); + expect(texts(empty)).not.toContain("The harbor replayed your steps and agreed they bring Mochi home."); + expect(empty.lines.at(-1)!.state).toBe("unchecked"); + const failed=refereeRecord({journey:fail,protocol:fail}); + expect(states(failed)).toEqual(["unchecked","unchecked","unchecked","unchecked"]); + // The real Journey parser lacks claims; a journey without them must not read as zero returns. + expect(refereeRecord({journey:ok({...journey,claims:undefined}),protocol:ok(protocol)}).lines[0]!.state).toBe("unchecked"); +}); + +test("admin disclosure reads both keys and says full-access only when reported",()=>{ + const r=adminRecord({root,items,rootKeys:ok(adminKeys),itemsKeys:ok(adminKeys)}); + expect(texts(r)).toEqual([ + "Root and Items still have full-access admin keys on testnet, so the whole harbor is not immutable: their code can still be changed.", + `${root} still has 1 full-access admin key.`,`${items} still has 1 full-access admin key.`, + ]); + const partial=adminRecord({root,items,rootKeys:ok(adminKeys),itemsKeys:fail}); + expect(texts(partial)[0]).toBe("Part of the harbor still has a full-access admin key on testnet, so it is not immutable."); + expect(partial.lines[2]!.state).toBe("unchecked"); + expect(states(adminRecord({root,items,rootKeys:fail,itemsKeys:fail}))).toEqual(["unchecked","unchecked"]); + expect(texts(adminRecord({root,items,rootKeys:ok(noKeys),itemsKeys:ok(noKeys)}))).toEqual([`${root} has no full-access keys.`,`${items} has no full-access keys.`]); +}); + +const encode=(v:unknown)=>[...new TextEncoder().encode(JSON.stringify(v))]; +function chain(override:(body:{params:Record})=>unknown|undefined=()=>undefined){ + const calls:string[]=[]; + const fetcher=async(_url:string,init:{body:string})=>{ + const body=JSON.parse(init.body) as {params:Record};calls.push(`${body.params.request_type}:${body.params.account_id}:${body.params.method_name??""}`); + expect(body.params.finality).toBe("final"); + const custom=override(body);if(custom!==undefined)return custom as {ok:boolean;json():Promise}; + const p=body.params,args=p.args_base64?JSON.parse(atob(p.args_base64)):null; + let result:unknown; + if(p.request_type==="view_account")result=account; + else if(p.request_type==="view_access_key_list")result=p.account_id===pet?noKeys:p.account_id===player?playerKeys:adminKeys; + else result={block_hash:"x",logs:[],result:encode(({get_config:config,nft_token:args?.token_id===pet?token:null,tidebound_journey:journey,tidebound_protocol:protocol} as Record)[p.method_name!])}; + return {ok:true,json:async()=>({jsonrpc:"2.0",id:"x",result})}; + }; + return {calls,fetcher}; +} +const target={rpcUrl:"https://rpc.test",root,player,pet,signerKey:signer,provider:"privy" as const}; + +test("loadRecords reads each fact from its own account",async()=>{ + const {calls,fetcher}=chain(); + const records=await loadRecords(target,fetcher); + expect(records.map(r=>r.kind)).toEqual(["self","key","referee","admin"]); + expect(records.flatMap(r=>r.lines).filter(l=>l.state==="unchecked")).toEqual([]); + expect(calls.sort()).toEqual([ + `call_function:${root}:get_config`,`call_function:${root}:nft_token`,`call_function:${root}:tidebound_journey`,`call_function:${root}:tidebound_protocol`, + `view_access_key_list:${root}:`,`view_access_key_list:${items}:`,`view_access_key_list:${player}:`,`view_access_key_list:${pet}:`,`view_account:${pet}:`, + ]); +}); + +test("loadRecords isolates each failure shape to its own line",async()=>{ + const {fetcher}=chain(({params})=>{ + if(params.request_type==="view_account")return {ok:true,json:async()=>({jsonrpc:"2.0",error:{name:"HANDLER_ERROR",cause:{name:"UNKNOWN_ACCOUNT"}}})}; + if(params.method_name==="tidebound_journey")return {ok:true,json:async()=>({jsonrpc:"2.0",result:{error:"wasm execution failed with error: MethodResolveError(MethodNotFound)",logs:[]}})}; + if(params.account_id===player)return {ok:false,json:async()=>{throw Error("502");}}; + if(params.account_id===items)return {ok:true,json:async()=>{throw SyntaxError("not json");}}; + if(params.method_name==="get_config")return Promise.reject(Error("offline")); + return undefined; + }); + const [s,k,r,a]=await loadRecords(target,fetcher); + expect(states(s!)).toEqual(["unchecked","read","read","unchecked"]); + expect(states(k!)).toEqual(["unchecked","source"]); + expect(states(r!)).toEqual(["unchecked","unchecked","unchecked","read"]); + expect(texts(a!)[0]).toBe("Part of the harbor still has a full-access admin key on testnet, so it is not immutable."); + expect(a!.lines[2]!.state).toBe("unchecked"); +}); diff --git a/web/src/expedition/records.ts b/web/src/expedition/records.ts new file mode 100644 index 0000000..9f28cfd --- /dev/null +++ b/web/src/expedition/records.ts @@ -0,0 +1,149 @@ +/** Harbor records: each line states only what one live public read showed. */ +export type Read={ok:true;value:T}|{ok:false}; +export interface RecordLine {text:string;detail?:string;state:"read"|"unchecked"|"finding"|"source"} +export interface HarborRecord {kind:"self"|"key"|"referee"|"admin";title:string;lines:RecordLine[]} +export interface RecordsTarget {rpcUrl:string;root:string;player:string;pet:string;signerKey:string;provider:"privy"|"other"} + +/** Mirrors validateNativeIntent in services/relayer/src/auth/sign.ts; records.test.ts keeps the two in step. */ +export const SIGNER_ACTIONS:readonly {receiver:"root"|"items"|"self";method:string;label:string}[]=[ + {receiver:"root",method:"adopt",label:"bring Mochi home"}, + {receiver:"root",method:"tidebound_claim",label:"record a return"}, + {receiver:"root",method:"tidebound_restore",label:"restore the beacon or signal"}, + {receiver:"root",method:"tidebound_commission",label:"Bram’s workshop commission"}, + {receiver:"root",method:"tidebound_craft",label:"craft a lantern"}, + {receiver:"root",method:"tidebound_polish",label:"polish a lantern"}, + {receiver:"root",method:"tidebound_cancel_polish",label:"settle an unfinished polish"}, + {receiver:"root",method:"tidebound_place",label:"place a lantern"}, + {receiver:"root",method:"tidebound_reconcile",label:"check an original request"}, + {receiver:"root",method:"tidebound_retry_operation",label:"retry an original request"}, + {receiver:"items",method:"mt_transfer",label:"gift a lantern"}, + {receiver:"items",method:"storage_deposit",label:"cover a lantern’s storage"}, + {receiver:"self",method:"transfer",label:"an empty, zero-value check on your own account"}, +]; + +const ONES="11111111111111111111111111111111"; +const obj=(v:unknown):v is Record=>!!v&&typeof v==="object"&&!Array.isArray(v); +const str=(v:unknown):v is string=>typeof v==="string"&&v.length>0; +const count=(v:unknown):v is number=>Number.isSafeInteger(v)&&(v as number)>=0; +export const shortHash=(h:string)=>h.length>14?`${h.slice(0,6)}…${h.slice(-4)}`:h; +export const shortKey=(k:string)=>{const [curve,body]=k.includes(":")?k.split(":",2) as [string,string]:["",k];return `${curve?curve+":":""}${body.slice(0,8)}…`;}; +const plural=(n:number,one:string,many=one+"s")=>`${n} ${n===1?one:many}`; + +type Key={public_key:string;permission:"FullAccess"|{receiver:string;methods:string[]}}; +function keyList(read:Read):Key[]|null { + if(!read.ok||!obj(read.value)||!Array.isArray(read.value.keys))return null; + const out:Key[]=[]; + for(const raw of read.value.keys){ + if(!obj(raw)||!str(raw.public_key)||!obj(raw.access_key))return null; + const p=raw.access_key.permission; + if(p==="FullAccess")out.push({public_key:raw.public_key,permission:"FullAccess"}); + else if(obj(p)&&obj(p.FunctionCall)&&str(p.FunctionCall.receiver_id)&&Array.isArray(p.FunctionCall.method_names)&&p.FunctionCall.method_names.every(str)) + out.push({public_key:raw.public_key,permission:{receiver:p.FunctionCall.receiver_id,methods:p.FunctionCall.method_names as string[]}}); + else return null; + } + return out; +} +const permissionText=(k:Key)=>k.permission==="FullAccess"?"FullAccess: full control of the account":`FunctionCall: only ${k.permission.receiver}, ${k.permission.methods.length?k.permission.methods.join(", "):"any method"}`; + +export function selfRecord(i:{root:string;player:string;pet:string;account:Read;keys:Read;token:Read;config:Read}):HarborRecord { + const lines:RecordLine[]=[]; + const account=i.account.ok&&obj(i.account.value)&&str(i.account.value.code_hash)?i.account.value:null; + lines.push(account?{state:"read",text:`Mochi’s own account is ${i.pet}.`}:{state:"unchecked",text:`Mochi’s account, ${i.pet}, couldn’t be checked just now.`}); + if(!i.token.ok)lines.push({state:"unchecked",text:"Mochi’s keeper couldn’t be checked just now."}); + else if(i.token.value===null)lines.push({state:"finding",text:`The harbor register has no papers for ${i.pet}.`}); + else if(obj(i.token.value)&&i.token.value.token_id===i.pet&&str(i.token.value.owner_id)){ + const owner=i.token.value.owner_id; + lines.push({state:"read",text:owner===i.player?`The harbor register lists you, ${owner}, as Mochi’s keeper.`:`The harbor register lists ${owner} as Mochi’s keeper, not ${i.player}.`,detail:`Register: ${i.root}`}); + } else lines.push({state:"unchecked",text:"Mochi’s papers came back in a shape this record doesn’t recognise, so the keeper couldn’t be checked."}); + const keys=keyList(i.keys); + if(!keys)lines.push({state:"unchecked",text:"Whether anyone holds a key to Mochi’s account couldn’t be checked."}); + else if(!keys.length)lines.push({state:"read",text:"No keys: no one, not you and not Familiar, can sign as Mochi’s account."}); + else lines.push({state:"finding",text:`Mochi’s account has ${plural(keys.length,"key")}, so it is not keyless.`,detail:keys.map(k=>`${shortKey(k.public_key)} ${k.permission==="FullAccess"?"FullAccess":"FunctionCall"}`).join(" · ")}); + const pinned=i.config.ok&&obj(i.config.value)&&str(i.config.value.pet_code_hash)?i.config.value.pet_code_hash:null; + if(!account)lines.push({state:"unchecked",text:"Which code Mochi’s account runs couldn’t be checked."}); + else { + const global=str(account.global_contract_hash)?account.global_contract_hash:null,own=account.code_hash!==ONES; + if(own)lines.push({state:"finding",text:"Mochi’s account carries separate code, not only the harbor’s shared code.",detail:`Own code ${shortHash(account.code_hash as string)}`}); + else if(!global)lines.push({state:"finding",text:"Mochi’s account runs no code at all."}); + else if(!pinned)lines.push({state:"unchecked",text:"Mochi runs shared code, but the code the harbor pins couldn’t be checked to compare.",detail:`Shared code ${shortHash(global)}`}); + else if(global===pinned)lines.push({state:"read",text:"Runs the shared Mochi code the harbor pins; Mochi’s account carries no separate code.",detail:`Shared code ${shortHash(global)} · pinned by ${i.root}`}); + else lines.push({state:"finding",text:"Mochi runs shared code that is not the code the harbor pins.",detail:`Runs ${shortHash(global)} · pinned ${shortHash(pinned)}`}); + } + return {kind:"self",title:"Mochi’s papers",lines}; +} + +export function keyRecord(i:{player:string;signerKey:string;provider:"privy"|"other";keys:Read}):HarborRecord { + const keys=keyList(i.keys),lines:RecordLine[]=[]; + if(!keys)lines.push({state:"unchecked",text:`The keys on ${i.player} couldn’t be checked just now.`}); + else { + const mine=keys.find(k=>k.public_key===i.signerKey); + lines.push(mine?{state:"read",text:i.provider==="privy"?"Your harbor key lives in your Privy wallet, not with Familiar.":"The key this sign-in uses is on your account, not with Familiar."} + :{state:"finding",text:"The key this sign-in uses isn’t on your account right now."}); + if(!keys.length)lines.push({state:"read",text:`${i.player} has no keys.`}); + for(const k of keys)lines.push({state:"read",text:`${k.public_key===i.signerKey?"This sign-in’s key":"Another key"}: ${permissionText(k)}.`,detail:shortKey(k.public_key)}); + } + lines.push({state:"source",text:`Familiar’s signer only prepares these harbor actions: ${SIGNER_ACTIONS.map(a=>a.label).join("; ")}. That list lives in Familiar’s code; the chain enforces only the key permission above.`}); + return {kind:"key",title:"The Register’s key line",lines}; +} + +export function refereeRecord(i:{journey:Read;protocol:Read}):HarborRecord { + const lines:RecordLine[]=[],j=i.journey.ok&&obj(i.journey.value)?i.journey.value:null; + const claims=j&&Array.isArray(j.claims)&&j.claims.every(c=>obj(c)&&str(c.id)&&str(c.rules_version)&&str(c.content_version))?j.claims as {id:string;rules_version:string;content_version:string}[]:null; + if(!claims)lines.push({state:"unchecked",text:"Your accepted returns couldn’t be checked just now."}); + else if(!claims.length)lines.push({state:"read",text:"No accepted returns yet. The Tidekeeper has nothing to stamp."}); + else { + lines.push({state:"read",text:"The harbor replayed your steps and agreed they bring Mochi home."}); + for(const c of claims)lines.push({state:"read",text:`Accepted return ${shortHash(c.id)}`,detail:`Rules ${c.rules_version} · content ${c.content_version}`}); + } + if(j&&count(j.shells)&&count(j.burned_shells))lines.push({state:"read",text:`Shells: ${j.shells} held, ${j.burned_shells} spent.`}); + else lines.push({state:"unchecked",text:"Your Shells couldn’t be checked just now."}); + if(j&&typeof j.commission_fulfilled==="boolean")lines.push({state:"read",text:j.commission_fulfilled?"Bram’s workshop commission is fulfilled.":"Bram’s workshop commission isn’t fulfilled yet."}); + else lines.push({state:"unchecked",text:"Bram’s workshop commission couldn’t be checked just now."}); + const p=i.protocol.ok&&obj(i.protocol.value)&&str(i.protocol.value.rules_version)&&str(i.protocol.value.content_version)?i.protocol.value:null; + lines.push(p?{state:"read",text:`The harbor currently plays rules ${p.rules_version}, content ${p.content_version}.`}:{state:"unchecked",text:"The harbor’s current rules couldn’t be checked just now."}); + return {kind:"referee",title:"The Tidekeeper’s stamp",lines}; +} + +export function adminRecord(i:{root:string;items:string;rootKeys:Read;itemsKeys:Read}):HarborRecord { + const lines:RecordLine[]=[],full:boolean[]=[]; + for(const [id,read] of [[i.root,i.rootKeys],[i.items,i.itemsKeys]] as const){ + const keys=keyList(read); + if(!keys){lines.push({state:"unchecked",text:`The admin keys on ${id} couldn’t be checked just now.`});continue;} + const n=keys.filter(k=>k.permission==="FullAccess").length;full.push(n>0); + lines.push(n?{state:"finding",text:`${id} still has ${plural(n,"full-access admin key")}.`,detail:keys.filter(k=>k.permission==="FullAccess").map(k=>shortKey(k.public_key)).join(" · ")}:{state:"read",text:`${id} has no full-access keys.`}); + } + if(full.length===2&&full.every(Boolean))lines.unshift({state:"finding",text:"Root and Items still have full-access admin keys on testnet, so the whole harbor is not immutable: their code can still be changed."}); + else if(full.some(Boolean))lines.unshift({state:"finding",text:"Part of the harbor still has a full-access admin key on testnet, so it is not immutable."}); + return {kind:"admin",title:"Who can still change the harbor",lines}; +} + +type Fetcher=(url:string,init:{method:string;headers:Record;body:string})=>Promise<{ok:boolean;json():Promise}>; +export async function rpcQuery(rpcUrl:string,params:Record,fetcher:Fetcher=fetch):Promise { + const res=await fetcher(rpcUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"familiar-records",method:"query",params:{finality:"final",...params}})}); + if(!res.ok)throw Error("The public record did not answer."); + const body=await res.json(); + if(!obj(body)||body.error!==undefined||!obj(body.result)||body.result.error!==undefined)throw Error("The public record returned an error."); + return body.result; +} +const base64=(text:string)=>{let s="";for(const b of new TextEncoder().encode(text))s+=String.fromCharCode(b);return btoa(s);}; +export async function viewCall(rpcUrl:string,account_id:string,method_name:string,args:object,fetcher?:Fetcher):Promise { + const r=await rpcQuery(rpcUrl,{request_type:"call_function",account_id,method_name,args_base64:base64(JSON.stringify(args))},fetcher) as {result?:unknown}; + if(!Array.isArray(r.result)||!r.result.every(b=>Number.isInteger(b)&&b>=0&&b<256))throw Error("The public record returned an unreadable view."); + return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(Uint8Array.from(r.result as number[]))); +} +const settle=(p:Promise):Promise>=>p.then(value=>({ok:true as const,value}),()=>({ok:false as const})); + +export async function loadRecords(t:RecordsTarget,fetcher?:Fetcher):Promise { + const items=`items.${t.root}`,q=(params:Record)=>settle(rpcQuery(t.rpcUrl,params,fetcher)),v=(m:string,a:object={})=>settle(viewCall(t.rpcUrl,t.root,m,a,fetcher)); + const keys=(account_id:string)=>q({request_type:"view_access_key_list",account_id}); + const [account,petKeys,token,config,playerKeys,journey,protocol,rootKeys,itemsKeys]=await Promise.all([ + q({request_type:"view_account",account_id:t.pet}),keys(t.pet),v("nft_token",{token_id:t.pet}),v("get_config"), + keys(t.player),v("tidebound_journey",{account_id:t.player}),v("tidebound_protocol"),keys(t.root),keys(items), + ]); + return [ + selfRecord({root:t.root,player:t.player,pet:t.pet,account,keys:petKeys,token,config}), + keyRecord({player:t.player,signerKey:t.signerKey,provider:t.provider,keys:playerKeys}), + refereeRecord({journey,protocol}), + adminRecord({root:t.root,items,rootKeys,itemsKeys}), + ]; +} From 5e9494844c319df7e429466511e93ec307d37d09 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:02:16 +0100 Subject: [PATCH 2/6] feat(records): show harbor records in the account panel behind VITE_RECORDS_ENABLED --- .env.example | 3 +++ web/src/expedition/HarborRecords.tsx | 27 +++++++++++++++++++++++++ web/src/expedition/game.css | 1 + web/src/expedition/harbor-controller.ts | 1 + web/src/expedition/harbor-session.tsx | 4 ++++ web/src/expedition/records.test.ts | 4 ++-- web/src/expedition/records.ts | 2 +- 7 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 web/src/expedition/HarborRecords.tsx diff --git a/.env.example b/.env.example index 35da51c..5422782 100644 --- a/.env.example +++ b/.env.example @@ -44,3 +44,6 @@ VITE_PRIVY_APP_ID= VITE_PRIVY_CLIENT_ID= # Separate full H1 HTTP entry; requires its exact compatible testnet tuple. TIDEBOUND_HTTP_ENABLED=false + +# Harbor records panel (live public reads only). Off unless exactly "true". +VITE_RECORDS_ENABLED=false diff --git a/web/src/expedition/HarborRecords.tsx b/web/src/expedition/HarborRecords.tsx new file mode 100644 index 0000000..6984505 --- /dev/null +++ b/web/src/expedition/HarborRecords.tsx @@ -0,0 +1,27 @@ +import {useEffect,useId,useRef,useState} from "react"; +import {loadRecords,type HarborRecord,type RecordsTarget} from "./records"; + +/** Opens on request; every line comes from a fresh public read. Remount with a new key when the account or Mochi changes. */ +export default function HarborRecords({target}:{target:RecordsTarget}) { + const [open,setOpen]=useState(false),[records,setRecords]=useState(null),[reading,setReading]=useState(false),[failed,setFailed]=useState(false); + const request=useRef(0),id=useId(); + useEffect(()=>()=>{request.current++;},[]); + async function read(){ + const mine=++request.current;setReading(true);setFailed(false);setRecords(null); + try{const next=await loadRecords(target);if(mine===request.current)setRecords(next);} + catch{if(mine===request.current)setFailed(true);} + finally{if(mine===request.current)setReading(false);} + } + return
+ + {open&&
+

Fresh reads of NEAR testnet’s public record. Each line says only what its read showed, or that it couldn’t be checked.

+

{reading?"Reading the harbor records…":failed?"The harbor records couldn’t be read just now. Nothing here is confirmed.":""}

+ {records?.map(record=>
+

{record.title}

+
    {record.lines.map((line,index)=>
  • {line.text}{line.detail&&{line.detail}}
  • )}
+
)} + {(records||failed)&&} +
} +
; +} diff --git a/web/src/expedition/game.css b/web/src/expedition/game.css index bcf1ca4..23bc5b6 100644 --- a/web/src/expedition/game.css +++ b/web/src/expedition/game.css @@ -94,3 +94,4 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .exp-home-places .exp-place-workbench { top:auto; bottom:60px; } .exp-game[data-mode=harbor] .exp-departure { grid-row:2; position:static; margin:0 12px max(10px,env(safe-area-inset-bottom)); } } +.exp-panel .exp-records{margin:16px 0 6px;padding-top:12px;border-top:1px solid #c4ad7e}.exp-records-intro{font-size:14px}.exp-records-status:empty{display:none}.exp-panel .exp-record h3{font-family:"Fraunces Variable",serif;font-size:19px;line-height:1.2;letter-spacing:-.02em;margin:18px 0 8px}.exp-record ul{list-style:none;margin:0;padding:0;display:grid;gap:9px}.exp-record li{position:relative;padding-left:17px;font-size:15px;line-height:1.4;overflow-wrap:anywhere}.exp-record li::before{content:"";position:absolute;left:1px;top:.5em;width:7px;height:7px;border-radius:50%;background:#3c6555}.exp-record li[data-state=finding]::before{background:#9a5a1c}.exp-record li[data-state=unchecked]{color:#6b4a26}.exp-record li[data-state=unchecked]::before{background:none;box-shadow:inset 0 0 0 1.5px #6b4a26}.exp-record li[data-state=source]::before{background:#8b734c;border-radius:1px}.exp-record li small{display:block;margin-top:2px;font-size:12px;color:#485744;font-variant-numeric:tabular-nums} diff --git a/web/src/expedition/harbor-controller.ts b/web/src/expedition/harbor-controller.ts index a05716d..d23dc0b 100644 --- a/web/src/expedition/harbor-controller.ts +++ b/web/src/expedition/harbor-controller.ts @@ -31,6 +31,7 @@ export class HarborController implements HarborSession { constructor(private readonly connection:HarborConnection|null,private readonly store:Pick,recordLock?:ReturnRecordLock){this.records=new ReturnRecords(store,recordLock);} get state(){return this.value;} get configured(){return !!this.connection;} + get root(){return this.connection?.client.root??null;} subscribe=(listener:()=>void)=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};}; private update(next:Partial) { const value={...this.value,...next}; diff --git a/web/src/expedition/harbor-session.tsx b/web/src/expedition/harbor-session.tsx index 8375915..6d5a5ad 100644 --- a/web/src/expedition/harbor-session.tsx +++ b/web/src/expedition/harbor-session.tsx @@ -4,6 +4,7 @@ import {validName} from "../rules"; import type {UsernameAvailability} from "../account/names"; import {TideboundClient} from "../tidebound/client"; import {HarborController,type HarborConnection} from "./harbor-controller"; +import HarborRecords from "./HarborRecords"; import type {HarborSession} from "./harbor-port"; export type {HarborSession,HarborState,RunContext,HomeCheckpoint,WorldIntent,WorldReview,WorkshopModel} from "./harbor-port"; export type {ReturnRecord} from "./return-record"; @@ -42,6 +43,8 @@ export function HarborAccountPanel() { async function act(work:()=>Promise) {setBusy(true);setProblem("");try{await work();}catch(error){if(alive.current)setProblem(error instanceof Error?error.message:"The original harbor could not be checked.");}finally{if(alive.current)setBusy(false);}} function downloadMemories(){try{const url=URL.createObjectURL(new Blob([controller!.exportReturns()],{type:"application/json"})),link=document.createElement("a");link.href=url;link.download="familiar-return-memories.json";link.click();setTimeout(()=>URL.revokeObjectURL(url),0);}catch{setProblem("The return memories could not be exported. Their original browser records are preserved.");}} const blocked=busy||state.busy,checked=availability?.username===username&&availability.available; + const pet=state.binding&&state.snapshot?.binding.nearAccountId===state.binding.nearAccountId?state.snapshot.pets[0]?.token_id:undefined; + const recordsTarget=import.meta.env.VITE_RECORDS_ENABLED==="true"&&state.binding&&pet&&controller.root?{rpcUrl:import.meta.env.VITE_NEAR_RPC_URL??"https://test.rpc.fastnear.com",root:controller.root,player:state.binding.nearAccountId,pet,signerKey:state.binding.signerPublicKey,provider:import.meta.env.VITE_ACCOUNT_PROVIDER==="privy"?"privy" as const:"other" as const}:null; return

Your saved harbor

{state.binding?<> @@ -50,6 +53,7 @@ export function HarborAccountPanel() { {state.snapshot?.pets.length?

Mochi is home · confirmed for this saved account.

:null} + {recordsTarget&&} {state.mode==="saved"&&state.snapshot&&!state.snapshot.pets.length&&} :<> diff --git a/web/src/expedition/records.test.ts b/web/src/expedition/records.test.ts index 0d7115f..e64dcec 100644 --- a/web/src/expedition/records.test.ts +++ b/web/src/expedition/records.test.ts @@ -56,7 +56,7 @@ test("Mochi's papers report findings as findings",()=>{ test("key line reports the permission exactly and never claims a function-call key",()=>{ const r=keyRecord({player,signerKey:signer,provider:"privy",keys:ok(playerKeys)}); expect(texts(r).slice(0,3)).toEqual([ - "Your harbor key lives in your Privy wallet, not with Familiar.", + "Your harbor key lives in your Privy wallet.", "This sign-in’s key: FullAccess: full control of the account.", "Another key: FullAccess: full control of the account.", ]); @@ -65,7 +65,7 @@ test("key line reports the permission exactly and never claims a function-call k expect(r.lines.at(-1)).toMatchObject({state:"source"}); expect(r.lines.at(-1)!.text).toContain("the chain enforces only the key permission above"); const fc=keyRecord({player,signerKey:signer,provider:"other",keys:ok({keys:[{public_key:signer,access_key:{nonce:1,permission:{FunctionCall:{receiver_id:root,method_names:["adopt"],allowance:null}}}}]})}); - expect(texts(fc).slice(0,2)).toEqual(["The key this sign-in uses is on your account, not with Familiar.",`This sign-in’s key: FunctionCall: only ${root}, adopt.`]); + expect(texts(fc).slice(0,2)).toEqual(["The key this sign-in uses is on your account.",`This sign-in’s key: FunctionCall: only ${root}, adopt.`]); }); test("key line without the read or without the sign-in key says so",()=>{ diff --git a/web/src/expedition/records.ts b/web/src/expedition/records.ts index 9f28cfd..bf6efca 100644 --- a/web/src/expedition/records.ts +++ b/web/src/expedition/records.ts @@ -77,7 +77,7 @@ export function keyRecord(i:{player:string;signerKey:string;provider:"privy"|"ot if(!keys)lines.push({state:"unchecked",text:`The keys on ${i.player} couldn’t be checked just now.`}); else { const mine=keys.find(k=>k.public_key===i.signerKey); - lines.push(mine?{state:"read",text:i.provider==="privy"?"Your harbor key lives in your Privy wallet, not with Familiar.":"The key this sign-in uses is on your account, not with Familiar."} + lines.push(mine?{state:"read",text:i.provider==="privy"?"Your harbor key lives in your Privy wallet.":"The key this sign-in uses is on your account."} :{state:"finding",text:"The key this sign-in uses isn’t on your account right now."}); if(!keys.length)lines.push({state:"read",text:`${i.player} has no keys.`}); for(const k of keys)lines.push({state:"read",text:`${k.public_key===i.signerKey?"This sign-in’s key":"Another key"}: ${permissionText(k)}.`,detail:shortKey(k.public_key)}); From 491cdbc492821f096d3b8d90c57657cdbbb473f3 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:02:17 +0100 Subject: [PATCH 3/6] test(records): browser check over live-shaped RPC answers --- package.json | 3 +- scripts/test-records-browser.ts | 99 +++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 scripts/test-records-browser.ts diff --git a/package.json b/package.json index e7db625..9c4d8f8 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,8 @@ "preflight:tidebound": "bun scripts/tidebound-preflight.ts", "test:privy-lifecycle-browser": "bun scripts/test-privy-lifecycle-browser.ts", "package:tidebound-review": "bun --env-file=.env.privy.local scripts/package-tidebound-review.ts", - "test:routing-browser": "bun scripts/test-routing-browser.ts" + "test:routing-browser": "bun scripts/test-routing-browser.ts", + "test:records-browser": "bun scripts/test-records-browser.ts" }, "dependencies": { "@fontsource-variable/figtree": "5.3.0", diff --git a/scripts/test-records-browser.ts b/scripts/test-records-browser.ts new file mode 100644 index 0000000..d2ccdd7 --- /dev/null +++ b/scripts/test-records-browser.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import {mkdtemp} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join,resolve} from "node:path"; +import {chromium,expect,type Page} from "@playwright/test"; +import {createServer,transformWithOxc} from "vite"; + +// Real Game, account panel and records UI over a synthetic session. RPC answers are intercepted +// with response shapes captured from https://test.rpc.fastnear.com on 2026-11-13; nothing reaches the network. +const shots=process.argv[2]; +const root="familiar-game.testnet",player=`qa-maker-h1.${root}`,pet=`qa-mochi-h1.${root}`,items=`items.${root}`; +const signer="ed25519:2DP5Amx7h1JJ17P2B1VvwHMYf9adeuKuitqEEqWsRXt5",pinned="CQQ63d8dNsM8oVCeEsU57USX212396zFmhtnqjgeXi1J",RPC="https://rpc.records.fixture/"; +const entry=` +import '/src/browser-globals.ts'; +import React from 'react';import{createRoot}from'react-dom/client'; +import{HarborSessionProvider,HarborAccountPanel,useHarborSession}from'/src/expedition/harbor-session.tsx'; +const root=${JSON.stringify(root)}; +const owner={playerId:'fixture',network:'testnet',nearAccountId:${JSON.stringify(player)},signerPublicKey:${JSON.stringify(signer)},signerBindingId:'fixture'}; +const journey={revision:11,banked:[],lit:false,signaled:false,lens_claim:null,moth_claim:null,credit:'unclaimed',workshop_salvage:1,bram_budget:0,shells:0,burned_shells:0,commission_fulfilled:false,craft:null,polish:null,placement:null}; +const pets=location.search.includes('nopet')?[]:[{token_id:${JSON.stringify(pet)}}]; +const connection={adapter:{accountRoot:root,async restoreSession(){return location.search.includes('signedout')?null:owner},async authenticate(){return owner},async endSession(){},async provisionAccount(){throw Error('no')}},accountExists:async()=>{},client:{root,itemsContract:'items.'+root, + async snapshot(binding){return structuredClone({readAt:'synthetic',binding,journey,checkpointHash:'a'.repeat(64),pets,items:[],nextItemIndex:null})}, + async verifyStack(){},pending(){return null},async send(){throw Error('no sends')},async resumeNative(){throw Error('no')},async reconcileNative(){return 'checked'},async resolveExpiredNative(){return 'not proven'},async view(){throw Error('no view')}}}; +const Game=React.lazy(()=>import('/src/expedition/Game.tsx')); +function GameProbe(){const session=useHarborSession();return Opening

}>}/>
} +createRoot(document.getElementById('root')).render(); +`; +const encode=(v:unknown)=>[...new TextEncoder().encode(JSON.stringify(v))]; +const full=(public_key:string,nonce:number)=>({access_key:{nonce,permission:"FullAccess"},public_key}); +function answer(params:Record):unknown { + const args=params.args_base64?JSON.parse(atob(params.args_base64)):{}; + if(params.request_type==="view_account")return {result:{amount:"300000000000000000000000",block_hash:"EAcUNYLRd1NFDZqD3bw66pk9Rei3pYhMGR9pN8XCSg3N",block_height:277567587,code_hash:"11111111111111111111111111111111",global_contract_hash:pinned,locked:"0",storage_paid_at:0,storage_usage:397}}; + if(params.request_type==="view_access_key_list"){ + const keys=params.account_id===pet?[]:params.account_id===player?[full(signer,277414125000020),full("ed25519:Di7QPiWUz21DnQucab8pe6qYPAnWpZnQWXYPfwa8kn3S",277418725000001)]:[full("ed25519:9gqucqLaUsuGCLoK9HFDthu5nDXXZmzASyE6rZa6QNw",277411058000019)]; + return {result:{block_hash:"38XBR8EXcvJ8dcZkv4JSSp2FGyR2FMkufzjBWPeBbVCf",block_height:277567588,keys}}; + } + const claim=(operation_id:string,id:string,lens:boolean)=>({operation_id,id,input_hash:"0a356c5cedbc1382d38a7d20487cdba3851ec4d8bf79716341300e053ecfa2aa",lens,moth:lens,rules_version:"tidebound_h1_v1",content_version:"first_light_v1"}); + const views:Record={ + get_config:{relayer:`relayer.${root}`,pet_code_hash:pinned,items,bakery:`bakery.${root}`,market:`market.${root}`,pool:"kiln.pool.f863973.m0"}, + nft_token:args.token_id===pet?{token_id:pet,owner_id:player,metadata:{title:pet},approved_account_ids:{}}:null, + tidebound_journey:{revision:11,shells:0,burned_shells:12,commission_fulfilled:true,claims:[claim("operator-qa:maker-lens-moth","8c5cbc6a02e6a0878b90723334c9e2e682e690a76758922ee445225a560072e5",true),claim("operator-qa:maker-wind-vane","be6ec9d4bde579ad041995d9a5a17d3473b77fd24c9866535cf1ed5a7fdf5c39",false)]}, + tidebound_protocol:{network:"testnet",rules_version:"tidebound_h1_v1",content_version:"first_light_v1",supported_content_versions:["first_light_v1","first_light_v2"],items,registry:root}, + }; + return {result:{block_hash:"GoSh9zRcxKwqSxwpgpGtibiegXckia6jF9To3xofH1if",block_height:277567589,logs:[],result:encode(views[params.method_name!])}}; +} +async function serve(records:boolean) { + const dir=await mkdtemp(join(tmpdir(),"familiar-records-")),id="\0records-fixture.tsx"; + const server=await createServer({configFile:false,root:resolve(import.meta.dir,"../web"),envDir:false,envPrefix:[],cacheDir:join(dir,"vite-cache"),logLevel:"error", + define:{"import.meta.env.VITE_RECORDS_ENABLED":JSON.stringify(records?"true":"false"),"import.meta.env.VITE_NEAR_RPC_URL":JSON.stringify(RPC),"import.meta.env.VITE_ACCOUNT_PROVIDER":JSON.stringify("privy")}, + plugins:[{name:"records-fixture",resolveId(source){if(source==="/__records-fixture.tsx")return id;},async load(source){if(source===id)return (await transformWithOxc(entry,"records-fixture.tsx")).code;}, + configureServer(s){s.middlewares.use((req,res,next)=>{if((req.url??"").split("?")[0]!=="/__records"){next();return;}res.setHeader("Content-Type","text/html");res.end('
');});}}], + optimizeDeps:{include:["react","react-dom","react-dom/client","react/jsx-dev-runtime"]},server:{host:"127.0.0.1",port:0}}); + await server.listen();return {server,origin:server.resolvedUrls!.local[0]!.replace(/\/$/,"")}; +} +async function openAccount(page:Page,url:string,rpc:{count:number;fail?:boolean}) { + await page.route(RPC,async route=>{rpc.count++;const body=JSON.parse(route.request().postData()!);assert.equal(body.params.finality,"final"); + await route.fulfill(rpc.fail?{status:502,body:"bad gateway"}:{contentType:"application/json",body:JSON.stringify({jsonrpc:"2.0",id:body.id,...answer(body.params) as object})});}); + await page.goto(url);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:20000}); + await page.getByRole("button",{name:"Game menu",exact:true}).click();await page.getByRole("button",{name:"Account & recovery",exact:true}).click(); +} +const browser=await chromium.launch({headless:true}),on=await serve(true),off=await serve(false); +try { + // Let each dev server finish its first dependency optimisation before any checked page loads. + for(const origin of [on.origin,off.origin]){const warm=await browser.newPage();await warm.goto(origin+"/__records?signedout");await warm.getByTestId("expedition-world").waitFor({timeout:30000}).catch(()=>{});await warm.waitForTimeout(1500);await warm.close();} + for(const [width,height] of [[390,844],[1440,900]] as const){ + const page=await browser.newPage({viewport:{width,height}}),errors:string[]=[],external:string[]=[],rpc={count:0}; + page.on("pageerror",e=>errors.push(e.message));page.on("request",r=>{const u=r.url();if(!u.startsWith(on.origin)&&!u.startsWith(RPC)&&!u.startsWith("blob:")&&!u.startsWith("data:"))external.push(u);}); + await openAccount(page,on.origin+"/__records",rpc); + await expect(page.getByText("Mochi is home · confirmed for this saved account.")).toBeVisible(); + const toggle=page.getByRole("button",{name:"Read the harbor records",exact:true});await expect(toggle).toHaveAttribute("aria-expanded","false"); + assert.equal(rpc.count,0,"no reads before a record is opened"); + await toggle.focus();await page.keyboard.press("Enter"); + await expect(page.getByText("The harbor replayed your steps and agreed they bring Mochi home.")).toBeVisible(); + assert.equal(rpc.count,9); + for(const text of [`The harbor register lists you, ${player}, as Mochi’s keeper.`,"No keys: no one, not you and not Familiar, can sign as Mochi’s account.","Runs the shared Mochi code the harbor pins; Mochi’s account carries no separate code.","Your harbor key lives in your Privy wallet.","Shells: 0 held, 12 spent.","Root and Items still have full-access admin keys on testnet, so the whole harbor is not immutable: their code can still be changed."]) + await expect(page.getByText(text,{exact:true})).toBeVisible(); + const panel=page.getByRole("dialog"); + const small=await panel.locator("button:visible").evaluateAll(nodes=>nodes.map(n=>n.getBoundingClientRect()).filter(r=>r.height<44||r.width<44).length);assert.equal(small,0,"44px targets"); + const again=page.getByRole("button",{name:"Check again",exact:true}); + for(let i=0;i<30&&!(await again.evaluate(n=>n===document.activeElement));i++)await page.keyboard.press("Tab"); + await expect(again).toBeFocused(); + const scroll=await panel.evaluate(n=>n.scrollWidth<=n.clientWidth);assert(scroll,"no horizontal scroll in the panel"); + if(shots)for(const [name,at] of [["top",0],["middle",.5],["end",1]] as const){await panel.evaluate((n,f)=>n.scrollTo(0,(n.scrollHeight-n.clientHeight)*f),at);await page.screenshot({path:join(shots,`records-${width}x${height}-${name}.png`)});} + assert.deepEqual(errors,[]);assert.deepEqual(external,[]);await page.close(); + console.log(`records ${width}x${height}: live-shape records, keyboard path, 44px targets passed`); + } + {const page=await browser.newPage({viewport:{width:390,height:844}}),rpc={count:0,fail:true}; + await openAccount(page,on.origin+"/__records",rpc);await page.getByRole("button",{name:"Read the harbor records",exact:true}).click(); + await expect(page.getByText("Mochi’s keeper couldn’t be checked just now.",{exact:true})).toBeVisible(); + for(const claim of ["No keys:","Privy wallet","replayed your steps","still has"])assert.equal(await page.getByText(claim).count(),0,`no ${claim} without its read`); + if(shots)await page.screenshot({path:join(shots,"records-390x844-unreachable.png")}); + await page.close();console.log("records: failed reads say they couldn't be checked");} + for(const [label,url] of [["signed out",on.origin+"/__records?signedout"],["no Mochi",on.origin+"/__records?nopet"],["flag off",off.origin+"/__records"]] as const){ + const page=await browser.newPage({viewport:{width:390,height:844}}),rpc={count:0},errors:string[]=[];page.on("pageerror",e=>errors.push(e.message));await openAccount(page,url,rpc); + await expect(page.getByRole("heading",{name:"Your saved harbor"})).toBeVisible();await page.waitForTimeout(300); + assert.equal(await page.getByRole("button",{name:"Read the harbor records"}).count(),0,`${label}: no records`);assert.equal(rpc.count,0);assert.deepEqual(errors,[]); + await page.close();console.log(`records ${label}: hidden, no reads`); + } +} finally {await browser.close();await on.server.close();await off.server.close();} From 8e873bbff21e77157b9ace366ff1c1caf8c7ddc1 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:05:49 +0100 Subject: [PATCH 4/6] docs(records): record verification and name the self-transfer plainly --- PROGRESS.md | 1 + web/src/expedition/records.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/PROGRESS.md b/PROGRESS.md index a049d28..e756708 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -11,3 +11,4 @@ Full earlier progress and acceptance records are preserved in the [archive](docs | 2026-11-13 | Documentation trimmed; Make shortcuts added | `make check`, `make typecheck`, `make browser`, `make evidence` | Full233 Bun tests/15490 assertions,123 Rust passes, typecheck/build and Chromium/WebKit route/save checks pass. Ten remaining historical JSONs/535460 bytes and full earlier JUDGES/PROGRESS snapshots archived byte-for-byte outside Git. Only gameplay proof and original-deployment guard JSONs remain. Make forwards to Bun/Cargo without deploy/signing recipes. Game, contract, recovery and original-operation implementations unchanged. No push/deployment or history rewrite; prior physical/human validation gaps remain. | | 2026-11-13 | GitHub source release prepared |235 Bun tests,123 Rust passes, type/build,15 recorded signatures/58 receipts; independent deployment review | Source build emits complete production game plus the same Node24 H1 handler; preview omits account functions. GitHub checks use pinned actions, read-only permissions, Bun/Rust tests, evidence and synthetic production/preview builds. Reachable history:788 blobs/56236965 bytes scanned against10 actual local secret values with zero matches;31 generic scanner findings independently verified public storage keys/block hashes/client ID/storage-key names. User explicitly authorized public repo; private environment/journals and untracked image excluded. Actual native Git trigger/alias checks remain to be recorded after connection. | | 2026-11-13 | Public repository and native Git connection established | https://github.com/dadadave80/familiar; GitHub branch-protection readback; existing-project Git link | User explicitly chose public visibility. Initial source23a576d uploaded to main; required PR checks, strict up-to-date main and admin enforcement enabled, force pushes/deletion disabled. Existing Vercel project linked to this repository without replacing encrypted environment or current public alias. This documentation PR is the end-to-end trigger check; its production result is not yet claimed here. | +| 2026-11-13 | Harbor records (Mochi’s papers, key line, Tidekeeper’s stamp, admin disclosure) behind `VITE_RECORDS_ENABLED`, default off | `bun run test` 246 pass; Rust 123 pass/2 ignored; `make build`; `make browser`; `make evidence`; `bun run test:records-browser` (Chromium 390×844/1440×900) | Each line comes from a public `finality: final` read and says “couldn’t be checked” when its read fails. Browser check intercepts RPC with shapes captured live from test.rpc.fastnear.com; a separate read-only Bun run of the same builder against live testnet (qa-maker-h1/qa-mochi-h1) produced all lines as read. Player key is reported as RPC lists it (currently FullAccess); no key changed. A real signed-in Privy session showing the panel is unverified. Flag-off build omits the records code. No push or deployment. | diff --git a/web/src/expedition/records.ts b/web/src/expedition/records.ts index bf6efca..cff8e10 100644 --- a/web/src/expedition/records.ts +++ b/web/src/expedition/records.ts @@ -18,7 +18,7 @@ export const SIGNER_ACTIONS:readonly {receiver:"root"|"items"|"self";method:stri {receiver:"root",method:"tidebound_retry_operation",label:"retry an original request"}, {receiver:"items",method:"mt_transfer",label:"gift a lantern"}, {receiver:"items",method:"storage_deposit",label:"cover a lantern’s storage"}, - {receiver:"self",method:"transfer",label:"an empty, zero-value check on your own account"}, + {receiver:"self",method:"transfer",label:"a zero-value transfer to your own account"}, ]; const ONES="11111111111111111111111111111111"; From c48889682a6c092ca800e89de334690efe83e8f1 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:10:59 +0100 Subject: [PATCH 5/6] fix(records): keep records and focus while checking again --- PROGRESS.md | 2 +- scripts/test-records-browser.ts | 4 +++- web/src/expedition/HarborRecords.tsx | 15 ++++++++------- web/src/expedition/records.test.ts | 1 + web/src/expedition/records.ts | 2 +- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index e756708..175dad5 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -11,4 +11,4 @@ Full earlier progress and acceptance records are preserved in the [archive](docs | 2026-11-13 | Documentation trimmed; Make shortcuts added | `make check`, `make typecheck`, `make browser`, `make evidence` | Full233 Bun tests/15490 assertions,123 Rust passes, typecheck/build and Chromium/WebKit route/save checks pass. Ten remaining historical JSONs/535460 bytes and full earlier JUDGES/PROGRESS snapshots archived byte-for-byte outside Git. Only gameplay proof and original-deployment guard JSONs remain. Make forwards to Bun/Cargo without deploy/signing recipes. Game, contract, recovery and original-operation implementations unchanged. No push/deployment or history rewrite; prior physical/human validation gaps remain. | | 2026-11-13 | GitHub source release prepared |235 Bun tests,123 Rust passes, type/build,15 recorded signatures/58 receipts; independent deployment review | Source build emits complete production game plus the same Node24 H1 handler; preview omits account functions. GitHub checks use pinned actions, read-only permissions, Bun/Rust tests, evidence and synthetic production/preview builds. Reachable history:788 blobs/56236965 bytes scanned against10 actual local secret values with zero matches;31 generic scanner findings independently verified public storage keys/block hashes/client ID/storage-key names. User explicitly authorized public repo; private environment/journals and untracked image excluded. Actual native Git trigger/alias checks remain to be recorded after connection. | | 2026-11-13 | Public repository and native Git connection established | https://github.com/dadadave80/familiar; GitHub branch-protection readback; existing-project Git link | User explicitly chose public visibility. Initial source23a576d uploaded to main; required PR checks, strict up-to-date main and admin enforcement enabled, force pushes/deletion disabled. Existing Vercel project linked to this repository without replacing encrypted environment or current public alias. This documentation PR is the end-to-end trigger check; its production result is not yet claimed here. | -| 2026-11-13 | Harbor records (Mochi’s papers, key line, Tidekeeper’s stamp, admin disclosure) behind `VITE_RECORDS_ENABLED`, default off | `bun run test` 246 pass; Rust 123 pass/2 ignored; `make build`; `make browser`; `make evidence`; `bun run test:records-browser` (Chromium 390×844/1440×900) | Each line comes from a public `finality: final` read and says “couldn’t be checked” when its read fails. Browser check intercepts RPC with shapes captured live from test.rpc.fastnear.com; a separate read-only Bun run of the same builder against live testnet (qa-maker-h1/qa-mochi-h1) produced all lines as read. Player key is reported as RPC lists it (currently FullAccess); no key changed. A real signed-in Privy session showing the panel is unverified. Flag-off build omits the records code. No push or deployment. | +| 2026-11-13 | Harbor records (Mochi’s papers, key line, Tidekeeper’s stamp, admin disclosure) behind `VITE_RECORDS_ENABLED`, default off | `bun run test` 246 pass; Rust 123 pass/2 ignored; `make build`; `make browser`; `make evidence`; `bun run test:records-browser` (Chromium only, 390×844/1440×900, mocked RPC, includes Check again keeping focus) | Each line comes from a public `finality: final` read and says “couldn’t be checked” when its read fails. Browser check intercepts RPC with shapes captured live from test.rpc.fastnear.com; a separate read-only Bun run of the same builder against live testnet (qa-maker-h1/qa-mochi-h1) returned no line as unchecked (records lines read; admin keys reported as findings). A Chromium page on a local origin fetched the public RPC directly (CORS allowed). Player key is reported as RPC lists it (currently FullAccess); no key changed. A real signed-in Privy session showing the panel is unverified. Flag-off build omits the records code. No push or deployment. | diff --git a/scripts/test-records-browser.ts b/scripts/test-records-browser.ts index d2ccdd7..f12f1aa 100644 --- a/scripts/test-records-browser.ts +++ b/scripts/test-records-browser.ts @@ -79,8 +79,10 @@ try { const again=page.getByRole("button",{name:"Check again",exact:true}); for(let i=0;i<30&&!(await again.evaluate(n=>n===document.activeElement));i++)await page.keyboard.press("Tab"); await expect(again).toBeFocused(); + await page.keyboard.press("Enter");await expect.poll(()=>rpc.count).toBe(18);await expect(again).toHaveText("Check again"); + assert(await panel.evaluate(n=>n.contains(document.activeElement)),"focus stays in the panel after checking again");await expect(again).toBeFocused(); const scroll=await panel.evaluate(n=>n.scrollWidth<=n.clientWidth);assert(scroll,"no horizontal scroll in the panel"); - if(shots)for(const [name,at] of [["top",0],["middle",.5],["end",1]] as const){await panel.evaluate((n,f)=>n.scrollTo(0,(n.scrollHeight-n.clientHeight)*f),at);await page.screenshot({path:join(shots,`records-${width}x${height}-${name}.png`)});} + if(shots)for(const [name,at] of [["top",0],["middle",.5],["end",1]] as const){await panel.evaluate((n,f)=>n.scrollTo(0,(n.scrollHeight-n.clientHeight)*f),at);await page.waitForTimeout(250);await page.screenshot({path:join(shots,`records-${width}x${height}-${name}.png`)});} assert.deepEqual(errors,[]);assert.deepEqual(external,[]);await page.close(); console.log(`records ${width}x${height}: live-shape records, keyboard path, 44px targets passed`); } diff --git a/web/src/expedition/HarborRecords.tsx b/web/src/expedition/HarborRecords.tsx index 6984505..b049b64 100644 --- a/web/src/expedition/HarborRecords.tsx +++ b/web/src/expedition/HarborRecords.tsx @@ -4,24 +4,25 @@ import {loadRecords,type HarborRecord,type RecordsTarget} from "./records"; /** Opens on request; every line comes from a fresh public read. Remount with a new key when the account or Mochi changes. */ export default function HarborRecords({target}:{target:RecordsTarget}) { const [open,setOpen]=useState(false),[records,setRecords]=useState(null),[reading,setReading]=useState(false),[failed,setFailed]=useState(false); - const request=useRef(0),id=useId(); + const request=useRef(0),busy=useRef(false),id=useId(); useEffect(()=>()=>{request.current++;},[]); async function read(){ - const mine=++request.current;setReading(true);setFailed(false);setRecords(null); + if(busy.current)return; + const mine=++request.current;busy.current=true;setReading(true);setFailed(false); try{const next=await loadRecords(target);if(mine===request.current)setRecords(next);} - catch{if(mine===request.current)setFailed(true);} - finally{if(mine===request.current)setReading(false);} + catch{if(mine===request.current){setRecords(null);setFailed(true);}} + finally{if(mine===request.current){busy.current=false;setReading(false);}} } return
- + {open&&

Fresh reads of NEAR testnet’s public record. Each line says only what its read showed, or that it couldn’t be checked.

-

{reading?"Reading the harbor records…":failed?"The harbor records couldn’t be read just now. Nothing here is confirmed.":""}

+

{reading?records?"Reading the harbor records again. The lines below are from the last read.":"Reading the harbor records…":failed?"The harbor records couldn’t be read just now. Nothing here is confirmed.":""}

{records?.map(record=>

{record.title}

    {record.lines.map((line,index)=>
  • {line.text}{line.detail&&{line.detail}}
  • )}
)} - {(records||failed)&&} + {(records||failed)&&}
}
; } diff --git a/web/src/expedition/records.test.ts b/web/src/expedition/records.test.ts index e64dcec..1bbbc1c 100644 --- a/web/src/expedition/records.test.ts +++ b/web/src/expedition/records.test.ts @@ -71,6 +71,7 @@ test("key line reports the permission exactly and never claims a function-call k test("key line without the read or without the sign-in key says so",()=>{ const failed=keyRecord({player,signerKey:signer,provider:"privy",keys:fail}); expect(states(failed)).toEqual(["unchecked","source"]); + expect(failed.lines[1]!.text).toEndWith("the chain enforces only your key’s permission, which couldn’t be checked just now."); expect(texts(failed).join(" ")).not.toContain("Privy wallet"); const missing=keyRecord({player,signerKey:"ed25519:Elsewhere",provider:"privy",keys:ok(playerKeys)}); expect(missing.lines[0]).toEqual({state:"finding",text:"The key this sign-in uses isn’t on your account right now."}); diff --git a/web/src/expedition/records.ts b/web/src/expedition/records.ts index cff8e10..2a5e09b 100644 --- a/web/src/expedition/records.ts +++ b/web/src/expedition/records.ts @@ -82,7 +82,7 @@ export function keyRecord(i:{player:string;signerKey:string;provider:"privy"|"ot if(!keys.length)lines.push({state:"read",text:`${i.player} has no keys.`}); for(const k of keys)lines.push({state:"read",text:`${k.public_key===i.signerKey?"This sign-in’s key":"Another key"}: ${permissionText(k)}.`,detail:shortKey(k.public_key)}); } - lines.push({state:"source",text:`Familiar’s signer only prepares these harbor actions: ${SIGNER_ACTIONS.map(a=>a.label).join("; ")}. That list lives in Familiar’s code; the chain enforces only the key permission above.`}); + lines.push({state:"source",text:`Familiar’s signer only prepares these harbor actions: ${SIGNER_ACTIONS.map(a=>a.label).join("; ")}. That list lives in Familiar’s code; the chain enforces only ${keys?"the key permission above":"your key’s permission, which couldn’t be checked just now"}.`}); return {kind:"key",title:"The Register’s key line",lines}; } From 3cd9c89ae46772127d2fdb50753e439836c734a7 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:36:20 +0100 Subject: [PATCH 6/6] fix: Mochi is her in player-facing text David chose her. Bram stays he. --- web/src/expedition/Game.tsx | 6 +++--- web/src/opening/Opening.tsx | 2 +- web/src/opening/Storyboard.tsx | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index d923f72..a0e3f1c 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -44,7 +44,7 @@ function writeLocal(next:LocalSave,key:string){const text=JSON.stringify(next);l export function eventDescription(event:CourtEvent,area?:Area):string{ switch(event.kind){ - case"move":return Math.abs(event.to.y-event.from.y)>1?"Mochi crosses the bridge.":"Mochi finds his footing."; + case"move":return Math.abs(event.to.y-event.from.y)>1?"Mochi crosses the bridge.":"Mochi finds her footing."; case"telegraph":return area==="wind"?`${columns[event.column]} source marked. The wheel determines its exit.`:`${columns[event.column]} is marked. The next surge follows that source.`; case"redirect":return `The lantern draws the source to ${columns[event.to]}.`; case"rotate":return event.to===0?"Mochi seats the wheel in its alignment notch.":"Mochi turns the wheel one notch. The outlets shift."; @@ -54,7 +54,7 @@ export function eventDescription(event:CourtEvent,area?:Area):string{ case"hit":return `The surge washes Mochi down to safe ground. Resolve ${event.resolve} of 3.`; case"pickup":return `Mochi ${event.rope?"reels in":"carefully carries"} the ${names[event.item]}.`; case"return":return event.cargo.length?`Home with ${event.cargo.map(i=>names[i]).join(" and ")}.`:"Mochi returns safely to the harbor."; - case"rescue":return event.reason==="resolve"?"The last splash used Mochi’s Resolve. Bram brings him home; the unbanked cargo stays behind.":"The tide closed after 24 decisions. Bram brings Mochi home; the unbanked cargo stays behind."; + case"rescue":return event.reason==="resolve"?"The last splash used Mochi’s Resolve. Bram brings her home; the unbanked cargo stays behind.":"The tide closed after 24 decisions. Bram brings Mochi home; the unbanked cargo stays behind."; } } function Icon({kind}:{kind:"menu"|"close"|"bag"|"sound"|"silent"|"north"|"south"|"west"|"east"}){ @@ -331,7 +331,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in onSail={choice=>{setArea(choice);open("sail");}} onCrossing={departPassage} onRepair={()=>open("beacon")} onRest={()=>{setSurface(null);setGreeting(0);setResting(true);if(sound)audio.current?.playMusic("harbor");}}/>:surface==="crossings"?<>

The harbor crossing

-

{harbor.heardBell?"Bram’s bell pull is rigged at the far-center landing on both crossings. Once per outing, call a marked surge left.":chapterComplete?"Mochi pricks his ears toward Bell Steps. The old far-left arch falls quiet at low water.":"One line, two landings. Choose which way to rig the boat."}

+

{harbor.heardBell?"Bram’s bell pull is rigged at the far-center landing on both crossings. Once per outing, call a marked surge left.":chapterComplete?"Mochi pricks her ears toward Bell Steps. The old far-left arch falls quiet at low water.":"One line, two landings. Choose which way to rig the boat."}

diff --git a/web/src/opening/Opening.tsx b/web/src/opening/Opening.tsx index 1e8c14d..0d05a7a 100644 --- a/web/src/opening/Opening.tsx +++ b/web/src/opening/Opening.tsx @@ -264,7 +264,7 @@ export default class Opening extends Component { this.cHints(to); v.gx = P.x; v.gy = P.y; void this.tw(n, "ghostA", .45, 200); await this.wait(820); if (!ok()) return; void this.tw(n, "ghostA", 0, 140); v.rings = []; v.pose = dxx < 0 ? "turn-left" : dxx > 0 ? "turn-right" : "curious"; v.sq = .93; await this.wait(130); if (!ok()) return; v.sq = 1; v.flip = dxx < 0; v.wf = { x: v.mx, y: v.my }; v.wt = P; v.walk = cross ? 2 : 1; this.sfx("step"); const d = cross ? 720 : 440; void this.tw(n, "mx", P.x, d, "io"); await this.tw(n, "my", P.y, d, "io"); if (!ok()) return; - v.walk = 0; v.flip = false; v.pose = "neutral"; v.sq = .95; c.pos = to; this.say("Mochi finds his footing."); await this.wait(110); v.sq = 1; + v.walk = 0; v.flip = false; v.pose = "neutral"; v.sq = .95; c.pos = to; this.say("Mochi finds her footing."); await this.wait(110); v.sq = 1; const ph = c.turn % 3; c.turn++; if (ph === 1) { await this.wait(350); if (!ok()) return; c.locked = to.x; v.laneX = P.x; v.pose = "brace"; this.setState({ lane: "IN + OUT · " + COLS[to.x]!.toUpperCase() }); diff --git a/web/src/opening/Storyboard.tsx b/web/src/opening/Storyboard.tsx index c23958b..4970808 100644 --- a/web/src/opening/Storyboard.tsx +++ b/web/src/opening/Storyboard.tsx @@ -93,7 +93,7 @@ export default function Storyboard() {
  • Today’s Tide is not built. Its scroll says “Coming soon” and no account or link appears.
  • The menu offers Continue when this device has a harbor and New Harbor otherwise. Starting over needs its own beat.
  • The court shown after 20 s is a scripted demo, not playable from the title.
  • -
  • The brief calls Mochi “her”; the shipped strings say “his”. Shipped strings are untouched and nothing new uses a pronoun.
  • +
  • Mochi is “her” throughout; Bram is “he”.