{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}
{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}
{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}
This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.
{record.id}
)}{save.last&&
{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}
}
{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}
>:surface==="bram"?<>
“You’re back.”
{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}
{harbor.heardBell&&
“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”
Choose an earned motif for one First Light lantern.
{session.state.workshop.motifs.map(m=>)}>:
{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}
}{!!session?.state.workshop.items.length&&Give a lantern
Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.
Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.
One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.
Light’s origin{previewOrigin?<>
Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.
Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.
{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}
{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}
{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}
{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}
}
{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}
>:surface==="bram"?<>
“You’re back.”
{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}
{harbor.heardBell&&
“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”
Choose an earned motif for one First Light lantern.
{session.state.workshop.motifs.map(m=>)}>:
{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}
}{!!session?.state.workshop.items.length&&Give a lantern
Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.
Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.
One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.
Light’s origin{previewOrigin?<>
Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.
Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.
{facts.reason??"It could not be opened."} Nothing unreadable is shown as Mochi's.
+
+ >:<>
+
{note.text}
+
+ >}
+
+ {facts.model&&
+ Turn the note over
+
+
Written by
{facts.model}, inside NEAR AI's confidential computing
+
Attestation
{facts.attestation}{facts.instances?` ${facts.instances} serving ${facts.instances===1?"instance":"instances"} checked; Intel status ${facts.tcbStatus}.`:""}
+
Checked
{facts.verifiedIn} The message and reply were encrypted to the model key with a one-use key from this browser. Familiar's harbor only passed the sealed bytes along and added the service key.
+ {facts.modelKey&&<>
Model key
{facts.modelKey}
>}
+ {facts.chatId&&<>
Note
{facts.chatId}
>}
+
What the seal means
The note was signed by the attested model key. NEAR AI's instances share that key, so the seal does not name one machine.
+
+ }
+ ;
+}
diff --git a/web/src/note/sealed-note.css b/web/src/note/sealed-note.css
new file mode 100644
index 0000000..7e496a4
--- /dev/null
+++ b/web/src/note/sealed-note.css
@@ -0,0 +1,25 @@
+.sn{margin:18px 0 6px;padding-top:16px;border-top:1px solid #c4ad7e}
+.sn-invite{font-family:"Fraunces Variable",serif;font-size:18px;line-height:1.3}
+.exp-panel .sn>button{width:100%}
+.sn-small{font-size:12px;color:#4d5a43;margin-top:8px!important}
+.sn-paper{position:relative;padding:20px 20px 16px;background:#fffaf0;color:#2e3a2c;border-radius:4px 14px 6px 12px;box-shadow:0 1px 0 #e6d6b2,0 6px 16px #4a3a1f2a;transform:rotate(-.6deg)}
+.sn-text{font-family:"Fraunces Variable",serif;font-size:19px;line-height:1.45;font-weight:420;max-width:62ch;white-space:pre-line;margin-bottom:16px!important}
+.sn-mark{display:flex;gap:10px;align-items:center;font-size:13px;line-height:1.35;padding-top:12px;border-top:1px dashed #cbb68b}
+.sn-mark strong{font-weight:800}
+.sn-seal{flex:0 0 40px;width:40px;height:40px}
+.sn-seal circle:first-child{fill:#9c3b2e}
+.sn-seal circle:last-of-type{fill:none;stroke:#e9b9a0;stroke-width:1.4}
+.sn-seal path{fill:none;stroke:#fff1e4;stroke-width:2.6;stroke-linecap:round;stroke-linejoin:round}
+.sn-sealed .sn-mark{color:#6e2b21}
+.sn-plain{background:#fbf6ea}
+.sn-plain .sn-mark{color:#5a4a2f}
+.sn-broken{background:#efe4cc;transform:none}
+.sn-broken h3{font-family:"Fraunces Variable",serif;font-size:20px;margin:0 0 8px}
+.sn-broken button{width:100%}
+.exp-panel .sn-back{margin:14px 0 0}
+.sn-back dl{margin:4px 0 0;font-size:13px;line-height:1.4}
+.sn-back dt{font-weight:800;margin-top:10px}
+.sn-back dd{margin:2px 0 0}
+.sn-code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;overflow-wrap:anywhere}
+@media(prefers-reduced-motion:no-preference){.sn-paper{animation:sn-unfold .5s cubic-bezier(.16,1,.3,1) both}}
+@keyframes sn-unfold{from{opacity:.4;transform:translateY(6px) rotate(-.6deg) scaleY(.96)}}
From 8052f2e7e2ac5c3a41e725114e2aee0d7f471ecd Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:49:27 +0100
Subject: [PATCH 06/21] fix(note): cap GLM-5.3 Flash reasoning with
thinking_token_budget 0
---
services/relayer/src/sealed-note.test.ts | 6 +++---
services/relayer/src/sealed-note.ts | 5 +++--
web/src/note/write.ts | 2 +-
3 files changed, 7 insertions(+), 6 deletions(-)
diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts
index 70321b9..46c01cc 100644
--- a/services/relayer/src/sealed-note.test.ts
+++ b/services/relayer/src/sealed-note.test.ts
@@ -10,7 +10,7 @@ const origin="https://familiar-two.vercel.app",root="familiar-game.testnet",acco
const key="synthetic-near-ai-key-never-real";
const enabled:TideboundHttpEnvironment={TIDEBOUND_HTTP_ENABLED:"true",ACCOUNT_PROVIDER:"privy",NEAR_NETWORK:"testnet",NEAR_ROOT:root,RELAYER_ID:`relayer.${root}`,RELAYER_PRIVATE_KEY:"synthetic-not-a-key",PRIVY_APP_ID:"synthetic-app",PRIVY_APP_SECRET:"synthetic-not-a-credential",NEAR_AI_API_KEY:key};
const clientKey="a".repeat(64),modelKey="b".repeat(64),cipher="0f".repeat(90);
-const body=(patch:Record={})=>JSON.stringify({model:NOTE_MODEL,messages:[{role:"system",content:cipher},{role:"user",content:cipher}],stream:false,max_tokens:120,chat_template_kwargs:{enable_thinking:false},...patch});
+const body=(patch:Record={})=>JSON.stringify({model:NOTE_MODEL,messages:[{role:"system",content:cipher},{role:"user",content:cipher}],stream:false,max_tokens:120,thinking_token_budget:0,...patch});
const completion='{"id":"chatcmpl-synthetic_1","object":"chat.completion","model":"z-ai/glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","content":"00ff"}}]}';
const signature='{"text":"z-ai/glm-5.3-flash:aa:bb","signature":"cc","signing_address":"dd","signing_algo":"ed25519","signature_kind":"provider_tee"}';
@@ -40,7 +40,7 @@ const post=(url:string,text:string,extra:Record={})=>fetch(url+"/
test("plain-field checks reject the wrong model, streaming, budget, message shape, extra fields and size",()=>{
const bytes=(text:string)=>new TextEncoder().encode(text);
expect(checkNoteBody(bytes(body()))).toBeNull();
- expect(checkNoteBody(bytes(body({chat_template_kwargs:undefined})))).toBeNull();
+ expect(checkNoteBody(bytes(body({thinking_token_budget:undefined})))).toBeNull();
const cases:[Record,string][]=[
[{model:"z-ai/glm-5.3"},"NOTE_MODEL"],[{model:"https://attacker.example/v1"},"NOTE_MODEL"],[{model:"../../v1/files"},"NOTE_MODEL"],
[{stream:true},"NOTE_STREAM"],[{stream:undefined},"NOTE_STREAM"],
@@ -49,7 +49,7 @@ test("plain-field checks reject the wrong model, streaming, budget, message shap
[{messages:[{role:"user",content:cipher},{role:"system",content:cipher}]},"NOTE_MESSAGES"],
[{messages:[{role:"system",content:"Write Mochi a note in plain text, please."+" ".repeat(120)},{role:"user",content:cipher}]},"NOTE_MESSAGES"],
[{messages:[{role:"system",content:cipher,name:"x"},{role:"user",content:cipher}]},"NOTE_MESSAGES"],
- [{tools:[]},"NOTE_FIELDS"],[{n:2},"NOTE_FIELDS"],[{chat_template_kwargs:{enable_thinking:true}},"NOTE_FIELDS"],
+ [{tools:[]},"NOTE_FIELDS"],[{n:2},"NOTE_FIELDS"],[{thinking_token_budget:null},"NOTE_FIELDS"],[{thinking_token_budget:8192},"NOTE_FIELDS"],[{chat_template_kwargs:{enable_thinking:false}},"NOTE_FIELDS"],
];
for(const [patch,code] of cases)expect(checkNoteBody(bytes(body(patch)))?.code).toBe(code);
expect(checkNoteBody(bytes("[]"))?.code).toBe("NOTE_BODY");
diff --git a/services/relayer/src/sealed-note.ts b/services/relayer/src/sealed-note.ts
index 9707073..fd762ef 100644
--- a/services/relayer/src/sealed-note.ts
+++ b/services/relayer/src/sealed-note.ts
@@ -10,7 +10,7 @@ const upstream="https://cloud-api.near.ai/v1";
const hexKey=/^[0-9a-f]{64}$/;
const ciphertext=/^(?:[0-9a-f]{2}){72,4000}$/;
const chatId=/^[A-Za-z0-9_-]{1,128}$/;
-const topLevel=new Set(["model","messages","stream","max_tokens","chat_template_kwargs"]);
+const topLevel=new Set(["model","messages","stream","max_tokens","thinking_token_budget"]);
export interface NoteChain {
/** Root `get_player` for the server-verified wallet key. */
@@ -40,7 +40,8 @@ export function checkNoteBody(bytes:Uint8Array):NoteRefusal|null {
if(value.model!==NOTE_MODEL)return {status:400,code:"NOTE_MODEL"};
if(value.stream!==false)return {status:400,code:"NOTE_STREAM"};
if(!Number.isSafeInteger(value.max_tokens)||(value.max_tokens as number)<1||(value.max_tokens as number)>NOTE_MAX_TOKENS)return {status:400,code:"NOTE_MAX_TOKENS"};
- if("chat_template_kwargs" in value&&JSON.stringify(value.chat_template_kwargs)!=='{"enable_thinking":false}')return {status:400,code:"NOTE_FIELDS"};
+ // GLM-5.3 Flash spends max_tokens on reasoning unless its documented reasoning budget is zero.
+ if("thinking_token_budget" in value&&value.thinking_token_budget!==0)return {status:400,code:"NOTE_FIELDS"};
const messages=value.messages;
if(!Array.isArray(messages)||messages.length!==2)return {status:400,code:"NOTE_MESSAGES"};
const roles=["system","user"];
diff --git a/web/src/note/write.ts b/web/src/note/write.ts
index 2d90839..9b2a114 100644
--- a/web/src/note/write.ts
+++ b/web/src/note/write.ts
@@ -42,7 +42,7 @@ export async function writeSealedNote(options:{
check(keys.size===1&&verified.every(v=>v.signer.signingAlgo==="ed25519"&&v.signer.signingAddress.toLowerCase()===v.signingPublicKey?.toLowerCase()),"The attested instances do not share one Ed25519 model key.");
key=[...keys][0]!;check(/^[0-9a-f]{64}$/.test(key),"The attested model key is malformed.");
Object.assign(back,{modelKey:key,instances:verified.length,tcbStatus:verified[0]!.tcbStatus});
- const body=JSON.stringify({model:NOTE_MODEL,messages:noteMessages(options.returns),stream:false,max_tokens:NOTE_MAX_TOKENS,chat_template_kwargs:{enable_thinking:false}});
+ const body=JSON.stringify({model:NOTE_MODEL,messages:noteMessages(options.returns),stream:false,max_tokens:NOTE_MAX_TOKENS,thinking_token_budget:0});
// The URL is never contacted; the SDK only encrypts this request and keeps the matching reply key.
prepared=await sdk.prepareE2eeChatRequest({request:new Request("https://note.invalid/v1/chat/completions",{method:"POST",headers:{"content-type":"application/json"},body}),modelKey:{signingAlgo:"ed25519",publicKey:key}});
requestBytes=new Uint8Array(await prepared.request.clone().arrayBuffer());
From a2ce62f750139c7e2c94eb54a90795b8b0d4fb88 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:49:27 +0100
Subject: [PATCH 07/21] chore(scripts): add a one-completion live sealed-note
check
---
scripts/sealed-note-live.ts | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
create mode 100644 scripts/sealed-note-live.ts
diff --git a/scripts/sealed-note-live.ts b/scripts/sealed-note-live.ts
new file mode 100644
index 0000000..d444cea
--- /dev/null
+++ b/scripts/sealed-note-live.ts
@@ -0,0 +1,34 @@
+// One live sealed note: real attestation, SDK E2EE, the relay's exact forwarding code and the browser seal decision.
+// Spends one NEAR AI chat completion. Pass only the key: `bun --env-file= scripts/sealed-note-live.ts`.
+// The player identity and journey eligibility are local stand-ins; no Privy, NEAR RPC or signing is used.
+import { createNoteRelay } from "../services/relayer/src/sealed-note";
+import { writeSealedNote } from "../web/src/note/write";
+import type { ReturnRecord } from "../web/src/expedition/return-record";
+
+const apiKey=process.env.NEAR_AI_API_KEY;
+if(!apiKey)throw Error("Set NEAR_AI_API_KEY in the process environment.");
+const root="familiar-game.testnet",account=`live-check.${root}`;
+// Records only upstream paths, statuses and error codes; never headers or bodies that could carry credentials.
+const upstream:{path:string;status:number;error?:unknown}[]=[];
+const relay=createNoteRelay({apiKey,chain:{player:async()=>account,confirmedClaims:async()=>1},fetch:async(url,init)=>{
+ const response=await fetch(url,init),path=new URL(url).pathname,entry:{path:string;status:number;error?:unknown}={path,status:response.status};upstream.push(entry);
+ if(!response.ok){const body=await response.clone().json().catch(()=>null) as {error?:{code?:unknown;type?:unknown};error_code?:unknown}|null;entry.error=body?.error?.code??body?.error?.type??body?.error_code??null;}
+ return response;
+}});
+const seen:{shape?:unknown;encryptionVersion?:string;signatureKind?:unknown;signedText?:unknown;status?:number}={};
+const send=(async(input:RequestInfo|URL,init?:RequestInit)=>{
+ const url=typeof input==="string"?input:input instanceof URL?input.href:input.url;
+ if(!url.startsWith("/api/"))return fetch(input,init);
+ const headers=new Headers(init!.headers);
+ const result=await relay.write({walletPublicKey:"ed25519:local-check",bytes:new Uint8Array(init!.body as Uint8Array),clientPublicKey:headers.get("x-client-pub-key")??undefined,modelPublicKey:headers.get("x-model-pub-key")??undefined});
+ seen.status=result.status;seen.encryptionVersion="3";
+ const body=result.body as {signature?:string|null;completion?:string};
+ // Plain response fields only: encrypted message values are reported by name and length, never decrypted here.
+ if(typeof body.completion==="string"){const c=JSON.parse(Buffer.from(body.completion,"base64").toString());const choice=c.choices?.[0];seen.shape={finish_reason:choice?.finish_reason,usage:c.usage,message:Object.fromEntries(Object.entries(choice?.message??{}).map(([k,v])=>[k,typeof v==="string"?`${k==="role"?v:"string:"+v.length}`:v===null?null:typeof v]))};}
+ if(typeof body.signature==="string"){const s=JSON.parse(Buffer.from(body.signature,"base64").toString());seen.signatureKind=s.signature_kind;seen.signedText=s.text;}
+ return Response.json(result.body,{status:result.status});
+}) as typeof fetch;
+const returns=[{schemaVersion:1,id:"live",operationId:"return:live",contentVersion:"first_light_v2",context:{authority:"near-testnet",network:"testnet",root,accountId:account,publicKey:"ed25519:local",companionId:`mochi.${root}`,revision:0,checkpointHash:"0".repeat(64),banked:[],lit:false,signaled:false},area:"beacon",tool:"rope",banked:[],commands:[],outcome:"returned",cargo:["lens"],disposition:"accepted",acceptedClaimId:"0".repeat(64)}] as unknown as ReturnRecord[];
+// SDK default quote/GPU verifiers for this runtime.
+const note=await writeSealedNote({returns,token:"local-check",relayUrl:"/api",fetch:send});
+console.info(JSON.stringify({state:note.state,text:"text" in note?note.text:null,back:note.back,relayStatus:seen.status,encryptionVersion:seen.encryptionVersion,signatureKind:seen.signatureKind,signedText:seen.signedText,shape:seen.shape,upstream},null,2));
From 38b1fac7311672df39860874c0af3a000b7e08ca Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:50:18 +0100
Subject: [PATCH 08/21] build: gate the sealed note behind an explicit
production opt-in
---
.env.example | 3 +++
scripts/build-release.test.ts | 10 ++++++----
scripts/build-release.ts | 7 ++++---
scripts/package-tidebound-review.ts | 3 ++-
4 files changed, 15 insertions(+), 8 deletions(-)
diff --git a/.env.example b/.env.example
index 8eb4345..4e2f4d5 100644
--- a/.env.example
+++ b/.env.example
@@ -47,4 +47,7 @@ TIDEBOUND_HTTP_ENABLED=false
# Harbor records panel (live public reads only). Off unless exactly "true".
VITE_RECORDS_ENABLED=false
+# Optional server-only key for Mochi's sealed note (/api/v1/privy/note). Unset keeps that endpoint disabled.
NEAR_AI_API_KEY=
+# Browser flag. Production builds enable it only when VITE_SEALED_NOTE_ENABLED is exactly true; previews never do.
+VITE_SEALED_NOTE_ENABLED=false
diff --git a/scripts/build-release.test.ts b/scripts/build-release.test.ts
index cbeb4e9..10078d9 100644
--- a/scripts/build-release.test.ts
+++ b/scripts/build-release.test.ts
@@ -6,10 +6,12 @@ import { releaseSettings } from "./build-release";
import { buildAccountFunction,currentRouting,HTTP_PATHS } from "./package-tidebound-review";
test("only production builds receive explicitly allowlisted public account settings",()=>{
- expect(releaseSettings({})).toEqual({appId:"",clientId:""});
- expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"prod-app",VITE_PRIVY_CLIENT_ID:"prod-client"})).toEqual({appId:"",clientId:""});
- expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app"})).toEqual({appId:"existing-app",clientId:""});
- expect(releaseSettings({VERCEL_ENV:"production",VITE_PRIVY_APP_ID:"public-app",PRIVY_APP_ID:"fallback",VITE_PRIVY_CLIENT_ID:"public-client"})).toEqual({appId:"public-app",clientId:"public-client"});
+ expect(releaseSettings({})).toEqual({appId:"",clientId:"",sealedNote:false});
+ expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"prod-app",VITE_PRIVY_CLIENT_ID:"prod-client",VITE_SEALED_NOTE_ENABLED:"true"})).toEqual({appId:"",clientId:"",sealedNote:false});
+ expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app"})).toEqual({appId:"existing-app",clientId:"",sealedNote:false});
+ expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEALED_NOTE_ENABLED:"1"}).sealedNote).toBe(false);
+ expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEALED_NOTE_ENABLED:"true"}).sealedNote).toBe(true);
+ expect(releaseSettings({VERCEL_ENV:"production",VITE_PRIVY_APP_ID:"public-app",PRIVY_APP_ID:"fallback",VITE_PRIVY_CLIENT_ID:"public-client"})).toEqual({appId:"public-app",clientId:"public-client",sealedNote:false});
for(const id of ["","invalid id", "a".repeat(129)])
expect(()=>releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:id})).toThrow();
expect(()=>releaseSettings({VERCEL_ENV:"production",PRIVY_APP_SECRET:"never-an-app-id"})).toThrow();
diff --git a/scripts/build-release.ts b/scripts/build-release.ts
index 5a0c3cb..3d9501d 100644
--- a/scripts/build-release.ts
+++ b/scripts/build-release.ts
@@ -3,11 +3,12 @@ import { join,resolve } from "node:path";
import { buildAccountFunction,buildGameSite,currentRouting } from "./package-tidebound-review";
export function releaseSettings(env:Record){
- if(env.VERCEL_ENV!=="production")return {appId:"",clientId:""};
+ if(env.VERCEL_ENV!=="production")return {appId:"",clientId:"",sealedNote:false};
const appId=env.VITE_PRIVY_APP_ID??env.PRIVY_APP_ID??"",clientId=env.VITE_PRIVY_CLIENT_ID??"";
const id=/^[A-Za-z0-9_-]{1,128}$/;
if(!id.test(appId)||(clientId&&!id.test(clientId)))throw Error("Production requires a valid public Privy app ID and, if supplied, a valid public client ID.");
- return {appId,clientId};
+ // Mochi's sealed note needs the account endpoints, so it is off unless production explicitly opts in.
+ return {appId,clientId,sealedNote:env.VITE_SEALED_NOTE_ENABLED==="true"};
}
export async function buildRelease(source:string,settings:ReturnType){
@@ -18,7 +19,7 @@ export async function buildRelease(source:string,settings:ReturnTypeid.includes("/phaser/")?"phaser":undefined}}}});
const staticReport=await copyGameStatic(overlay,site);
const runtimeAssets=await copyRuntimeAssets(join(source,"web/public"),site);
From f90e6372ca3adfd6909a249dc682b7f230d67007 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:53:26 +0100
Subject: [PATCH 09/21] docs: record the sealed-note relay, live seal and NEAR
AI discrepancies
---
JUDGES.md | 2 ++
PROGRESS.md | 10 ++++++++++
docs/ARCHITECTURE.md | 2 +-
docs/THREAT-MODEL.md | 13 ++++++++++++-
4 files changed, 25 insertions(+), 2 deletions(-)
diff --git a/JUDGES.md b/JUDGES.md
index 53dc552..2ee9a31 100644
--- a/JUDGES.md
+++ b/JUDGES.md
@@ -13,6 +13,8 @@ Current Familiar has one playable Phaser edition. The introduction stays first;
| TypeScript/Rust spatial transitions agree | `make test` | Shared fixture, solver and replay tests |
| Every listed pet keyless on pinned global code; replayed-court state and one-time Shells for the test player; player and admin keys disclosed | `make judge` | Live public-RPC state of `familiar-game.testnet`, not proof of deployed code (root code differs from the HEAD build); reports key permissions, cannot see custody |
| Doctored courts (historical and current rules), repeat Shell grants and out-of-scope signing are refused | `make break` | HEAD source in the contract unit runtime plus signer unit tests; full Wasm sandbox stays `bun run test:tidebound-sandbox` |
+| Mochi's sealed note: relay checks, E2EE v3 round trip (including NEAR AI's published Ed25519 vector) and the sealed/plain/broken decision | `bun test services/relayer/src/sealed-note.test.ts web/src/note` | Local key pairs and mocked NEAR AI responses; no network |
+| A live note seals: attested model key, E2EE v3, provider_tee signature over `model:sha256(request):sha256(response)` | `NEAR_AI_API_KEY= bun scripts/sealed-note-live.ts` | Spends one NEAR AI completion; player identity and journey eligibility are local stand-ins. The claim is only "signed by the attested model key": NEAR AI instances share that signing key, so no single machine is identified |
| Actual contract compatibility and original-operation invariants | `bun run build:contracts`, then `bun run test:tidebound-sandbox` | Separate same-layout local-chain test; deployed-byte upgrade mode additionally requires all five frozen original Wasm artifacts |
Only two report JSON files remain:
diff --git a/PROGRESS.md b/PROGRESS.md
index f098811..c6a5830 100644
--- a/PROGRESS.md
+++ b/PROGRESS.md
@@ -10,6 +10,16 @@ Full earlier progress and acceptance records are preserved in the [archive](docs
| 2026-11-13 | Artwork delivery and cleaned build verified | Full233 Bun tests/15490 assertions,123 Rust passes, build/typecheck/fmt; offline15 signatures/58 receipt graphs | Six generator-only WebPs/1536100 bytes moved outside public delivery; all19 shipped WebPs unchanged; all11 optimized outputs reproduce exact bytes. Original pose1123042 bytes archived. Source and prepared Chromium/WebKit routes preserve intro-first, nine entry URLs and original saves;390px Beacon/Wind/lantern origin/save/art-failure journey and both Bell/Reed/discovery browser routes pass. Prepared574iax has367 static files,370 output files;10 actual local secret values absent and private H1 handler remains SHA256e3cc0335191ce63946bcdf9fe772fed2ee5db2678f7c193a12c86cfb64800e03. Relayer Docker COPY set passes isolated frozen offline production install and runtime bundling; actual Docker daemon unavailable. Existing Phaser size warning persists. User image and protected environment/journals/Wasm untouched. No push or deployment; physical-device sound/full two-device recovery/human enjoyment unverified. |
| 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 | Mochi's sealed note on local branch `feat/sealed-note` (flagged off) | `bun run test` 247 pass/15677 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace` 123 pass/2 ignored; `make build`, `bun run build:release`, `make browser` (Chromium/WebKit), `make evidence` (15 signatures) pass; mocked note UI viewed at 390×844 and 1440×900; `bun --env-file= scripts/sealed-note-live.ts` | Live 2026-11-13: keyless `GET /v1/model/z-ai%2Fglm-5.3-flash` → `providerType:vllm, attestationSupported:true`; keyless `GET /v1/attestation/report` (ed25519, fresh nonce, `x-no-aliasing`) → 200 with 3 instances sharing key `5a0210f2…0caff`, all verified by SDK 0.3.0 (`UpToDate`, GPU evidence required); CORS allows the production origin. Three live completions with `X-Encryption-Version: 3`: chats `8af36ee4753d4228994b34ee1a8183ab` and `f63baa0caeb549f4932deb02daa59745` were broken (GLM spent all 120 tokens reasoning, `finish_reason:length`, empty content, despite `chat_template_kwargs.enable_thinking:false`); after switching to `thinking_token_budget:0`, chat `daa6b15838fc402689766a28b7826446` returned `provider_tee`, decrypted and **sealed**. Eligibility/identity in the live script were local stand-ins; no Privy session, NEAR RPC eligibility, deployed relay or Vercel variable was exercised. No push or deployment. |
| 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 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. |
| 2026-11-13 | `make judge` and `make break` added; NEAR claims table in README | `make judge` (live fastnear RPC, `familiar-game.testnet`): 16 PASS, 0 FAIL, all 4 pets from `nft_tokens`. `make break`: 7 Rust refusal/acceptance tests (first_light_v1 and v2) + 5 signer tests pass. Codex hostile review found 5 gaps (undefined-hash false PASS, hard-coded pet sample, v1-only court tests, snapshot-vs-code and custody overclaims); all fixed. Full `make check`: 235 Bun tests, 130 Rust passes, typecheck; `make evidence` 15 signatures offline | Judge confirms every pet has no keys and run global code `CQQ63d8…` = `get_config.pet_code_hash`; `qa-maker-h1` has 2 accepted claims and 12 Shells granted once. Reported, not claimed: player keys are FullAccess (Privy-held), the method limit is the off-chain signer; root/items keep FullAccess admin keys; deployed root code `66HumWXu…` differs from the HEAD build `4xtG2991…` recorded in FAMILIAR-GAMEPLAY.json. `.env` NEAR_ROOT still names the older `familiar-1105-28522e` stack; judge does not read `.env`. Threat model now states replay proves legal steps only, winning inputs are public, and one pet passed between accounts earns each account a commission. `make break` uses the contract unit runtime, not the Wasm sandbox. No deploy, no signing, no push. |
+
+## Recorded discrepancies (NEAR AI, 2026-11-13)
+
+- **E2EE version.** docs.near.ai's E2EE guide documents `X-Encryption-Version: 2` with no associated data. `@nearai/inference-sdk` 0.3.0 and nearai/inference-proxy `docs/e2ee.md` (commit 724cf65) use v3, which binds the reply key and a field label into each field's AEAD associated data, and say clients must not downgrade. The live gateway accepted v3 for `z-ai/glm-5.3-flash`. Familiar uses the SDK's v3 encryption; its test TEE reproduces the inference-proxy Ed25519 v3 vector. The SDK also sends `X-Encrypt-All-Fields: true`; the relay forwards it.
+- **Attestation key.** The installed NEAR AI Cloud skill and model-verification notes say model attestation reports require an API key. The current E2EE guide says the gateway attestation endpoint needs none, and keyless model reports returned 200 today. Familiar fetches them keyless from the browser. A future 401 makes the note broken; no relay attestation fallback exists.
+- **Reasoning control.** `chat_template_kwargs.enable_thinking:false` did not stop GLM-5.3 Flash reasoning (two live notes broke at `max_tokens`). docs.near.ai's reasoning-models page names `thinking_token_budget` for this model; `0` produced content.
+- **Signature URL.** The skill shows `/v1/signature/{id}?model=…&signing_algo=…`; the SDK and Familiar omit `model`, and the signature was found on the first try.
+- **Model tier.** `/v1/models` has no explicit tier field (`owned_by:"nearai"`). The SDK's attestation criterion (`/v1/model/{id}`: `providerType:"vllm"`, `attestationSupported:true`) is what Familiar checks.
+- **Brief vs repository.** The handoff said `.env.example` already had a `NEAR_AI_API_KEY` placeholder; it did not. The placeholder was added (empty).
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index cd0ee3b..de91293 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -36,7 +36,7 @@ flowchart TD
`tidebound/client.ts` persists canonical transaction bytes before provider navigation. It verifies the provider signature against those bytes, keeps an original envelope through unknown outcomes, and validates full finalized receipt graphs before settlement. Expiry clearing requires proof of permanent expiry plus an unused nonce at a pinned finalized block; it does not cancel a contract reservation or grant a refund. Ordinary movement, conversation, audio and presentation need no transaction.
-`services/relayer/src/tidebound-http.ts` is the Node H1 function entry used by the current prepared release. It accepts only `/api/health`, `/api/v1/privy/wallet` and `/api/v1/privy/player` with their configured methods. Private runtime configuration enables it separately. App-scoped identity, exact origin, strict body/size, canonical wallet ownership and bounded account setup remain server checks. It is not a general signing or transaction relay endpoint. The optional local Bun relayer retains older allowlisted protocol support for reproducible testnet tooling.
+`services/relayer/src/tidebound-http.ts` is the Node H1 function entry used by the current prepared release. It accepts only `/api/health`, `/api/v1/privy/wallet`, `/api/v1/privy/player` and `/api/v1/privy/note` with their configured methods. The note path is disabled unless `NEAR_AI_API_KEY` is set; it forwards Mochi's end-to-end encrypted note request to NEAR AI unchanged (see the threat model). Private runtime configuration enables it separately. App-scoped identity, exact origin, strict body/size, canonical wallet ownership and bounded account setup remain server checks. It is not a general signing or transaction relay endpoint. The optional local Bun relayer retains older allowlisted protocol support for reproducible testnet tooling.
## Contracts and compatibility
diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md
index df482a3..e99780f 100644
--- a/docs/THREAT-MODEL.md
+++ b/docs/THREAT-MODEL.md
@@ -6,7 +6,8 @@ Current source scope, November 13, 2026: browser game and supporting NEAR testne
| --- | --- | --- |
| Browser presentation | Pure replay rules, accessible DOM actions, saved turn before animation | Compromised frontend can mislead a player; device-only saves are not ledger achievements |
| Account provider | App-scoped Privy identity and exact canonical user-owned NEAR wallet; separately configured NEAR Auth provider | Email/provider administration, session availability and SDK integrity remain dependencies |
-| Account HTTP | Three exact H1 endpoints, origin/JWT/body/size/method checks, bounded setup | Process-local quotas are not durable anti-Sybil or cross-instance spending controls |
+| Account HTTP | Exact H1 endpoints (health, wallet, player, note), origin/JWT/body/size/method checks, bounded setup | Process-local quotas are not durable anti-Sybil or cross-instance spending controls |
+| Sealed-note relay | Exact `/api/v1/privy/note` path behind the same origin/JWT/body/size checks; off unless `NEAR_AI_API_KEY` is set; checks only model, `stream:false`, `max_tokens` ≤ 120, two ciphertext messages, size, a confirmed root journey claim, once per account and 3/hour per account | Process-local note-once and quotas reset on restart or another instance; the relay can deny or delay a note but cannot read it or forge a seal |
| Native transaction client | Exact canonical Borsh/signature/intent checks, durable original envelope, Web Locks, complete receipt graph | RPC outages or ambiguous consumed nonces may keep an action pending |
| Root registry/journey | Predecessor authorization, current companion ownership, checkpoint replay, accepted original input hashes | Administrative upgrade keys remain; source tests do not freeze deployed code. Court replay proves legal steps, not human play, and winning inputs are public; the commission is per account, so one pet passed between accounts can earn each account its own 12 Shells |
| Items | Current-holder checks, authenticated immutable mint evidence, one finish per token | Transferred ownership is distinct from maker achievement; stale UI alone is never ownership proof |
@@ -18,6 +19,16 @@ Login/restore never creates another wallet, provisions a player, adopts a compan
Server credentials stay in ignored private environment files or encrypted hosting configuration. The frontend receives public VITE configuration only. Current native pending envelopes contain signed transaction material and public account/game data, not private keys or JWTs by design. Earlier guest-key browser namespaces may contain sensitive secrets; cleanup must not reinterpret, clear or export them. Downloaded return memories exclude credentials and signed requests. Public evidence should include only the proof required for the claim, not identity tokens, private journals or raw private keys.
+## Mochi's sealed note
+
+Behind `VITE_SEALED_NOTE_ENABLED`, the browser fetches NEAR AI's model attestation for `z-ai/glm-5.3-flash` directly and without a key, with a fresh 32-byte nonce and `x-no-aliasing: true`, and verifies every returned instance with `@nearai/inference-sdk` 0.3.0 (TDX quote, NVIDIA GPU evidence required, nonce and signer binding). All instances must share one Ed25519 key. The SDK encrypts both messages to that key with E2EE v3 and a one-use reply key. Only the fixed harbor name and recent accepted return facts are sent; no player-written text.
+
+The relay receives the exact request bytes and the client/model public-key headers. It never decodes message content (it checks only that each content is ciphertext-shaped hex), never logs, and builds every upstream header itself: the server key, `X-Signing-Algo: ed25519`, `X-Encryption-Version: 3`, `X-Encrypt-All-Fields: true`, `x-no-aliasing: true` and `Accept-Encoding: identity`. The model and upstream URLs are constants and the chat id is pattern-checked before the signature URL, so neither the body nor the response can redirect the server key; redirects are refused. It returns the raw completion bytes and the raw `GET /v1/signature/?signing_algo=ed25519` bytes, retrying briefly.
+
+The browser decrypts with its one-use key and seals only when `signature_kind` is `provider_tee`, the signed text equals `z-ai/glm-5.3-flash:sha256(request bytes):sha256(response bytes)` and the Ed25519 signature verifies against the attested key. Anything else that still decrypts is a readable note labelled not sealed; anything unreadable is broken and shows no text. A replayed older signed response cannot seal a new request because the request hash covers fresh ciphertext bound to the new reply key.
+
+Limits: NEAR AI's instances share the model signing key, so the seal means only "signed by the attested model key", not a particular machine. No deployment measurement policy is pinned; the SDK's default accepted TCB statuses apply. If NEAR AI starts requiring a key for attestation, the note becomes broken; there is no relay fallback for attestation. A stored note in browser storage records the check made on that device; editing local storage can change what that device displays. Note-once and quotas are process-local.
+
## Uncertain outcomes and recoverable progress
Each prepared request retains its original operation, canonical bytes, hash, signature and context. A timeout, rejected browser write, stale snapshot, unknown receipt or consumed nonce never authorizes a replacement mint, payment, refund or unlock. Account/session changes fence late results. A single transaction hash or FINAL label is insufficient: receipt children must exist, be connected, have known terminal statuses and agree with the outer result.
From 2c5ecc81fb61dc80bcf860c3f2843144c1e56d1b Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:56:17 +0100
Subject: [PATCH 10/21] fix(relayer): accept only compact canonical note JSON
so duplicate keys cannot pass checks
---
services/relayer/src/sealed-note.test.ts | 7 +++++--
services/relayer/src/sealed-note.ts | 5 ++++-
web/src/note/note.test.ts | 1 +
3 files changed, 10 insertions(+), 3 deletions(-)
diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts
index 46c01cc..76470cd 100644
--- a/services/relayer/src/sealed-note.test.ts
+++ b/services/relayer/src/sealed-note.test.ts
@@ -53,6 +53,9 @@ test("plain-field checks reject the wrong model, streaming, budget, message shap
];
for(const [patch,code] of cases)expect(checkNoteBody(bytes(body(patch)))?.code).toBe(code);
expect(checkNoteBody(bytes("[]"))?.code).toBe("NOTE_BODY");
+ for(const twisted of [body().replace('"max_tokens":120','"max_tokens":100000,"max_tokens":120'),body().replace('"stream":false','"stream":true,"stream":false'),
+ body().replace(`"model":"${NOTE_MODEL}"`,`"model":"z-ai/glm-5.3","model":"${NOTE_MODEL}"`),` ${body()}`,`${body()}\n`,body().replace('"stream":false','"stream" : false'),body().replace("glm","gl\\u006d")])
+ expect(checkNoteBody(bytes(twisted))?.code).toBe("NOTE_BODY");
expect(checkNoteBody(bytes("{"))?.code).toBe("NOTE_BODY");
expect(checkNoteBody(bytes(body({messages:[{role:"system",content:"0f".repeat(4000)},{role:"user",content:cipher}]})))).toEqual({status:413,code:"NOTE_TOO_LARGE"});
});
@@ -90,8 +93,8 @@ test("requires a confirmed journey event for the server-derived account",async()
test("forwards the exact browser bytes with fixed headers, returns raw bytes and the retried signature, then writes once",async()=>{
const f=fixture({signatureMisses:2});
- // Unusual but valid JSON spacing proves the relay forwards bytes rather than a re-serialized body.
- const sent=` {"model":"${NOTE_MODEL}" , "messages":[{"role":"system","content":"${cipher}"},{"role":"user","content":"${cipher}"}],"stream":false,"max_tokens":96}\n`;
+ // Unusual key order proves the relay forwards bytes rather than a rebuilt body.
+ const sent=`{"max_tokens":96,"stream":false,"messages":[{"content":"${cipher}","role":"system"},{"content":"${cipher}","role":"user"}],"model":"${NOTE_MODEL}"}`;
await serve(enabled,f,async url=>{
const response=await post(url,sent);expect(response.status).toBe(200);
const envelope=await response.json();
diff --git a/services/relayer/src/sealed-note.ts b/services/relayer/src/sealed-note.ts
index fd762ef..89ff194 100644
--- a/services/relayer/src/sealed-note.ts
+++ b/services/relayer/src/sealed-note.ts
@@ -33,7 +33,10 @@ export type NoteFetch=(url:string,init:RequestInit)=>Promise;
export function checkNoteBody(bytes:Uint8Array):NoteRefusal|null {
if(bytes.byteLength>NOTE_BODY_LIMIT)return {status:413,code:"NOTE_TOO_LARGE"};
let body:unknown;
- try{body=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));}catch{return {status:400,code:"NOTE_BODY"};}
+ let text:string;
+ try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes);body=JSON.parse(text);}catch{return {status:400,code:"NOTE_BODY"};}
+ // Compact canonical JSON only: duplicate keys or alternate spellings could otherwise be read differently upstream.
+ if(JSON.stringify(body)!==text)return {status:400,code:"NOTE_BODY"};
if(!body||typeof body!=="object"||Array.isArray(body))return {status:400,code:"NOTE_BODY"};
const value=body as Record;
if(Object.keys(value).some(key=>!topLevel.has(key)))return {status:400,code:"NOTE_FIELDS"};
diff --git a/web/src/note/note.test.ts b/web/src/note/note.test.ts
index 5d95a9e..defc971 100644
--- a/web/src/note/note.test.ts
+++ b/web/src/note/note.test.ts
@@ -68,6 +68,7 @@ test("SDK v3 encryption round-trips through a locally generated model key pair",
expect(headers.get("x-client-pub-key")).toMatch(/^[0-9a-f]{64}$/);
const text=new TextDecoder().decode(bytes);expect(text).not.toContain("Pocket Harbor");expect(text).not.toContain("Mochi");
const sent=JSON.parse(text);expect(Object.keys(sent).sort()).toEqual(["max_tokens","messages","model","stream"]);
+ expect(JSON.stringify(sent)).toBe(text);
const tee=await mockTee(model,bytes,headers.get("x-client-pub-key")!);
expect(tee.plaintexts).toEqual(messages.map(m=>m.content));
const decrypted=await (await prepared.decryptResponse(new Response(tee.completion,{headers:{"content-type":"application/json"}}))).json();
From 4ceeed7c26523ee62671c01ddd037594a7918eb4 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:56:51 +0100
Subject: [PATCH 11/21] fix(note): keep the written note across later returns
and stop over-claiming plain notes
---
web/src/note/SealedNote.tsx | 18 ++++++++++--------
web/src/note/note.test.ts | 2 +-
web/src/note/write.ts | 5 +++--
3 files changed, 14 insertions(+), 11 deletions(-)
diff --git a/web/src/note/SealedNote.tsx b/web/src/note/SealedNote.tsx
index 9a3bb4c..4418371 100644
--- a/web/src/note/SealedNote.tsx
+++ b/web/src/note/SealedNote.tsx
@@ -14,13 +14,15 @@ export function SealedNote({returns,token,relayUrl=import.meta.env.VITE_RELAYER_
returns:readonly ReturnRecord[];token:()=>Promise;relayUrl?:string;
write?:typeof writeSealedNote;store?:Store|null;
}) {
- const latest=[...returns].reverse().find(r=>r.disposition==="accepted"&&r.acceptedClaimId);
- const key=latest&&latest.context.authority==="near-testnet"?noteKey(latest.context.root,latest.context.accountId,latest.acceptedClaimId!):null;
- const [note,setNote]=useState(()=>key&&store?readNote(store,key):null);
+ // Newest first. The one note stays attached to the return it was written for, even after later returns.
+ const keys=[...returns].reverse().flatMap(r=>r.disposition==="accepted"&&r.acceptedClaimId&&r.context.authority==="near-testnet"?[noteKey(r.context.root,r.context.accountId,r.acceptedClaimId)]:[]);
+ const key=keys[0]??null,keyList=keys.join("|");
+ const stored=()=>{for(const k of keys){const found=store?readNote(store,k):null;if(found)return found;}return null;};
+ const [note,setNote]=useState(stored);
const [busy,setBusy]=useState(false);
const alive=useRef(true);useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
- useEffect(()=>{setNote(key&&store?readNote(store,key):null);},[key,store]);
- if(!latest||!key)return null;
+ useEffect(()=>{setNote(stored());},[keyList,store]);
+ if(!key)return null;
async function ask(){
setBusy(true);
let result:Note;
@@ -42,21 +44,21 @@ export function SealedNote({returns,token,relayUrl=import.meta.env.VITE_RELAYER_
{note.state==="broken"?<>
The note got wet on the way.
{facts.reason??"It could not be opened."} Nothing unreadable is shown as Mochi's.
{facts.model}, inside NEAR AI's confidential computing
+ {note.state==="sealed"?<>
Written by
{facts.model}, inside NEAR AI's confidential computing
>:<>
Requested from
{facts.model}
>}
Attestation
{facts.attestation}{facts.instances?` ${facts.instances} serving ${facts.instances===1?"instance":"instances"} checked; Intel status ${facts.tcbStatus}.`:""}
Checked
{facts.verifiedIn} The message and reply were encrypted to the model key with a one-use key from this browser. Familiar's harbor only passed the sealed bytes along and added the service key.
{facts.modelKey&&<>
Model key
{facts.modelKey}
>}
diff --git a/web/src/note/note.test.ts b/web/src/note/note.test.ts
index defc971..8dea9c4 100644
--- a/web/src/note/note.test.ts
+++ b/web/src/note/note.test.ts
@@ -129,7 +129,7 @@ test("the browser flow returns sealed, plain and broken notes",async()=>{
expect((await unsigned.run()).state).toBe("plain");
const refused=flow({model,relay:async()=>Response.json({code:"NOTE_WRITTEN",error:"Mochi has already written this harbor's note."},{status:409})});
- expect(await refused.run()).toMatchObject({state:"broken",back:{reason:"Mochi has already written this harbor's note."}});
+ expect(await refused.run()).toMatchObject({state:"broken",back:{reason:"Mochi has already written this harbor's note.",code:"NOTE_WRITTEN"}});
const wrongKey=flow({model,relay:async(bytes,headers)=>{const other=teeKeys(),tee=await mockTee(model,bytes,headers.get("x-client-pub-key")!);void other;const forged=utf8(new TextDecoder().decode(tee.completion).replace(/"content":"[0-9a-f]+"/,`"content":"${sealTo("forged",other.publicKey)}"`));return envelope(forged,tee.signature);}});
expect((await wrongKey.run()).state).toBe("broken");
const split=flow({model,keys:[model.hex,teeKeys().hex],relay:async()=>{throw Error("unreachable");}});
diff --git a/web/src/note/write.ts b/web/src/note/write.ts
index 9b2a114..a3f23ab 100644
--- a/web/src/note/write.ts
+++ b/web/src/note/write.ts
@@ -9,7 +9,7 @@ export const NOTE_MAX_TOKENS=120;
/** What the back of the note can truthfully say about how it was made. */
export interface NoteBack {
model:string;modelKey?:string;instances?:number;tcbStatus?:string;
- attestation:string;verifiedIn:string;chatId?:string;reason?:string;
+ attestation:string;verifiedIn:string;chatId?:string;reason?:string;code?:string;
}
export type SealedNote=
|{state:"sealed";text:string;back:NoteBack}
@@ -58,7 +58,8 @@ export async function writeSealedNote(options:{
const envelope:unknown=await response.json().catch(()=>null);
if(!response.ok){
const error=envelope&&typeof envelope==="object"&&"error" in envelope&&typeof envelope.error==="string"?envelope.error:"The harbor could not deliver the note.";
- return {state:"broken",back:{...back,reason:error}};
+ const code=envelope&&typeof envelope==="object"&&"code" in envelope&&typeof envelope.code==="string"?envelope.code:undefined;
+ return {state:"broken",back:{...back,reason:error,...code?{code}:{}}};
}
check(envelope&&typeof envelope==="object"&&"completion" in envelope&&typeof envelope.completion==="string","The harbor's reply was malformed.");
completion=fromBase64(envelope.completion);
From f92cc40578440cd3cfe8f36a582279102d639f36 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Fri, 13 Nov 2026 23:59:39 +0100
Subject: [PATCH 12/21] chore(scripts): report the encryption header actually
sent upstream
---
scripts/sealed-note-live.ts | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/scripts/sealed-note-live.ts b/scripts/sealed-note-live.ts
index d444cea..09225e0 100644
--- a/scripts/sealed-note-live.ts
+++ b/scripts/sealed-note-live.ts
@@ -11,17 +11,17 @@ const root="familiar-game.testnet",account=`live-check.${root}`;
// Records only upstream paths, statuses and error codes; never headers or bodies that could carry credentials.
const upstream:{path:string;status:number;error?:unknown}[]=[];
const relay=createNoteRelay({apiKey,chain:{player:async()=>account,confirmedClaims:async()=>1},fetch:async(url,init)=>{
- const response=await fetch(url,init),path=new URL(url).pathname,entry:{path:string;status:number;error?:unknown}={path,status:response.status};upstream.push(entry);
+ const response=await fetch(url,init),path=new URL(url).pathname,entry:{path:string;status:number;error?:unknown;encryptionVersion?:string|null}={path,status:response.status,encryptionVersion:new Headers(init.headers).get("x-encryption-version")};upstream.push(entry);
if(!response.ok){const body=await response.clone().json().catch(()=>null) as {error?:{code?:unknown;type?:unknown};error_code?:unknown}|null;entry.error=body?.error?.code??body?.error?.type??body?.error_code??null;}
return response;
}});
-const seen:{shape?:unknown;encryptionVersion?:string;signatureKind?:unknown;signedText?:unknown;status?:number}={};
+const seen:{shape?:unknown;signatureKind?:unknown;signedText?:unknown;status?:number}={};
const send=(async(input:RequestInfo|URL,init?:RequestInit)=>{
const url=typeof input==="string"?input:input instanceof URL?input.href:input.url;
if(!url.startsWith("/api/"))return fetch(input,init);
const headers=new Headers(init!.headers);
const result=await relay.write({walletPublicKey:"ed25519:local-check",bytes:new Uint8Array(init!.body as Uint8Array),clientPublicKey:headers.get("x-client-pub-key")??undefined,modelPublicKey:headers.get("x-model-pub-key")??undefined});
- seen.status=result.status;seen.encryptionVersion="3";
+ seen.status=result.status;
const body=result.body as {signature?:string|null;completion?:string};
// Plain response fields only: encrypted message values are reported by name and length, never decrypted here.
if(typeof body.completion==="string"){const c=JSON.parse(Buffer.from(body.completion,"base64").toString());const choice=c.choices?.[0];seen.shape={finish_reason:choice?.finish_reason,usage:c.usage,message:Object.fromEntries(Object.entries(choice?.message??{}).map(([k,v])=>[k,typeof v==="string"?`${k==="role"?v:"string:"+v.length}`:v===null?null:typeof v]))};}
@@ -31,4 +31,4 @@ const send=(async(input:RequestInfo|URL,init?:RequestInit)=>{
const returns=[{schemaVersion:1,id:"live",operationId:"return:live",contentVersion:"first_light_v2",context:{authority:"near-testnet",network:"testnet",root,accountId:account,publicKey:"ed25519:local",companionId:`mochi.${root}`,revision:0,checkpointHash:"0".repeat(64),banked:[],lit:false,signaled:false},area:"beacon",tool:"rope",banked:[],commands:[],outcome:"returned",cargo:["lens"],disposition:"accepted",acceptedClaimId:"0".repeat(64)}] as unknown as ReturnRecord[];
// SDK default quote/GPU verifiers for this runtime.
const note=await writeSealedNote({returns,token:"local-check",relayUrl:"/api",fetch:send});
-console.info(JSON.stringify({state:note.state,text:"text" in note?note.text:null,back:note.back,relayStatus:seen.status,encryptionVersion:seen.encryptionVersion,signatureKind:seen.signatureKind,signedText:seen.signedText,shape:seen.shape,upstream},null,2));
+console.info(JSON.stringify({state:note.state,text:"text" in note?note.text:null,back:note.back,relayStatus:seen.status,signatureKind:seen.signatureKind,signedText:seen.signedText,shape:seen.shape,upstream},null,2));
From 78b0aa96113fec4f67d3aa3c2e62ea13b7cb79c5 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Sat, 14 Nov 2026 00:01:34 +0100
Subject: [PATCH 13/21] docs: record in-browser live seals and journey
eligibility reads
---
PROGRESS.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/PROGRESS.md b/PROGRESS.md
index c6a5830..b05eaca 100644
--- a/PROGRESS.md
+++ b/PROGRESS.md
@@ -10,7 +10,7 @@ Full earlier progress and acceptance records are preserved in the [archive](docs
| 2026-11-13 | Artwork delivery and cleaned build verified | Full233 Bun tests/15490 assertions,123 Rust passes, build/typecheck/fmt; offline15 signatures/58 receipt graphs | Six generator-only WebPs/1536100 bytes moved outside public delivery; all19 shipped WebPs unchanged; all11 optimized outputs reproduce exact bytes. Original pose1123042 bytes archived. Source and prepared Chromium/WebKit routes preserve intro-first, nine entry URLs and original saves;390px Beacon/Wind/lantern origin/save/art-failure journey and both Bell/Reed/discovery browser routes pass. Prepared574iax has367 static files,370 output files;10 actual local secret values absent and private H1 handler remains SHA256e3cc0335191ce63946bcdf9fe772fed2ee5db2678f7c193a12c86cfb64800e03. Relayer Docker COPY set passes isolated frozen offline production install and runtime bundling; actual Docker daemon unavailable. Existing Phaser size warning persists. User image and protected environment/journals/Wasm untouched. No push or deployment; physical-device sound/full two-device recovery/human enjoyment unverified. |
| 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 | Mochi's sealed note on local branch `feat/sealed-note` (flagged off) | `bun run test` 247 pass/15677 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace` 123 pass/2 ignored; `make build`, `bun run build:release`, `make browser` (Chromium/WebKit), `make evidence` (15 signatures) pass; mocked note UI viewed at 390×844 and 1440×900; `bun --env-file= scripts/sealed-note-live.ts` | Live 2026-11-13: keyless `GET /v1/model/z-ai%2Fglm-5.3-flash` → `providerType:vllm, attestationSupported:true`; keyless `GET /v1/attestation/report` (ed25519, fresh nonce, `x-no-aliasing`) → 200 with 3 instances sharing key `5a0210f2…0caff`, all verified by SDK 0.3.0 (`UpToDate`, GPU evidence required); CORS allows the production origin. Three live completions with `X-Encryption-Version: 3`: chats `8af36ee4753d4228994b34ee1a8183ab` and `f63baa0caeb549f4932deb02daa59745` were broken (GLM spent all 120 tokens reasoning, `finish_reason:length`, empty content, despite `chat_template_kwargs.enable_thinking:false`); after switching to `thinking_token_budget:0`, chat `daa6b15838fc402689766a28b7826446` returned `provider_tee`, decrypted and **sealed**. Eligibility/identity in the live script were local stand-ins; no Privy session, NEAR RPC eligibility, deployed relay or Vercel variable was exercised. No push or deployment. |
+| 2026-11-13 | Mochi's sealed note on local branch `feat/sealed-note` (flagged off) | `bun run test` 247 pass/15685 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace` 123 pass/2 ignored; `make build`, `bun run build:release`, `make browser` (Chromium/WebKit), `make evidence` (15 signatures) pass; mocked note UI viewed at 390×844 and 1440×900; `bun --env-file= scripts/sealed-note-live.ts` | Live 2026-11-13: keyless `GET /v1/model/z-ai%2Fglm-5.3-flash` → `providerType:vllm, attestationSupported:true`; keyless `GET /v1/attestation/report` (ed25519, fresh nonce, `x-no-aliasing`) → 200 with 3 instances sharing key `5a0210f2…0caff`, all verified by SDK 0.3.0 (`UpToDate`, GPU evidence required); CORS allows the production origin. Three live completions with `X-Encryption-Version: 3`: chats `8af36ee4753d4228994b34ee1a8183ab` and `f63baa0caeb549f4932deb02daa59745` were broken (GLM spent all 120 tokens reasoning, `finish_reason:length`, empty content, despite `chat_template_kwargs.enable_thinking:false`); after switching to `thinking_token_budget:0`, chat `daa6b15838fc402689766a28b7826446` returned `provider_tee`, decrypted and **sealed**. Then the real `writeSealedNote` ran inside Playwright Chromium and WebKit (SDK default browser verifiers via NEAR AI's PCCS/NRAS proxies, WebCrypto Ed25519) against the relay code in-process: chats `20d3c9c6263b42edac0533dd02eb89d4` (Chromium) and `d8b367f524824d53ad99bb8f2849d736` (WebKit) both **sealed**, and the note stayed attached after a later accepted return. Five live completions in total. Read-only testnet views: `tidebound_journey` on `familiar-game.testnet` returns `claims` (qa-maker-v2: 2, dadadave80: 0) and `rpcNoteChain` reads them; unregistered keys resolve to no player. Eligibility/identity in the live runs were local stand-ins; no Privy JWT, deployed relay or Vercel variable was exercised. The in-game satchel with the flag on was not viewed; the note component was viewed standalone with mocked results and in the live browser run. No push or deployment. |
| 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 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. |
| 2026-11-13 | `make judge` and `make break` added; NEAR claims table in README | `make judge` (live fastnear RPC, `familiar-game.testnet`): 16 PASS, 0 FAIL, all 4 pets from `nft_tokens`. `make break`: 7 Rust refusal/acceptance tests (first_light_v1 and v2) + 5 signer tests pass. Codex hostile review found 5 gaps (undefined-hash false PASS, hard-coded pet sample, v1-only court tests, snapshot-vs-code and custody overclaims); all fixed. Full `make check`: 235 Bun tests, 130 Rust passes, typecheck; `make evidence` 15 signatures offline | Judge confirms every pet has no keys and run global code `CQQ63d8…` = `get_config.pet_code_hash`; `qa-maker-h1` has 2 accepted claims and 12 Shells granted once. Reported, not claimed: player keys are FullAccess (Privy-held), the method limit is the off-chain signer; root/items keep FullAccess admin keys; deployed root code `66HumWXu…` differs from the HEAD build `4xtG2991…` recorded in FAMILIAR-GAMEPLAY.json. `.env` NEAR_ROOT still names the older `familiar-1105-28522e` stack; judge does not read `.env`. Threat model now states replay proves legal steps only, winning inputs are public, and one pet passed between accounts earns each account a commission. `make break` uses the contract unit runtime, not the Wasm sandbox. No deploy, no signing, no push. |
From c148a69797f7ddb47dfac27a137fb46f44795def Mon Sep 17 00:00:00 2001
From: David Dada
Date: Sat, 14 Nov 2026 00:10:11 +0100
Subject: [PATCH 14/21] fix(relayer): allow note retries within a daily
allowance and time out upstream calls
---
docs/THREAT-MODEL.md | 8 ++--
services/relayer/src/sealed-note.test.ts | 47 +++++++++++++++++++++---
services/relayer/src/sealed-note.ts | 32 +++++++++-------
web/src/note/SealedNote.tsx | 2 +-
web/src/note/note.test.ts | 4 +-
5 files changed, 67 insertions(+), 26 deletions(-)
diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md
index e99780f..009fc65 100644
--- a/docs/THREAT-MODEL.md
+++ b/docs/THREAT-MODEL.md
@@ -7,7 +7,7 @@ Current source scope, November 13, 2026: browser game and supporting NEAR testne
| Browser presentation | Pure replay rules, accessible DOM actions, saved turn before animation | Compromised frontend can mislead a player; device-only saves are not ledger achievements |
| Account provider | App-scoped Privy identity and exact canonical user-owned NEAR wallet; separately configured NEAR Auth provider | Email/provider administration, session availability and SDK integrity remain dependencies |
| Account HTTP | Exact H1 endpoints (health, wallet, player, note), origin/JWT/body/size/method checks, bounded setup | Process-local quotas are not durable anti-Sybil or cross-instance spending controls |
-| Sealed-note relay | Exact `/api/v1/privy/note` path behind the same origin/JWT/body/size checks; off unless `NEAR_AI_API_KEY` is set; checks only model, `stream:false`, `max_tokens` ≤ 120, two ciphertext messages, size, a confirmed root journey claim, once per account and 3/hour per account | Process-local note-once and quotas reset on restart or another instance; the relay can deny or delay a note but cannot read it or forge a seal |
+| Sealed-note relay | Exact `/api/v1/privy/note` path behind the same origin/JWT/body/size checks; off unless `NEAR_AI_API_KEY` is set; checks only model, `stream:false`, `max_tokens` ≤ 120, two ciphertext messages, size, a confirmed root journey claim, 3 notes per account per UTC day, 3/hour per account and 120/hour overall; a 35 s completion timeout and a 10 s signature window | Process-local quotas reset on restart or another instance; the relay can deny or delay a note but cannot read it or forge a seal |
| Native transaction client | Exact canonical Borsh/signature/intent checks, durable original envelope, Web Locks, complete receipt graph | RPC outages or ambiguous consumed nonces may keep an action pending |
| Root registry/journey | Predecessor authorization, current companion ownership, checkpoint replay, accepted original input hashes | Administrative upgrade keys remain; source tests do not freeze deployed code. Court replay proves legal steps, not human play, and winning inputs are public; the commission is per account, so one pet passed between accounts can earn each account its own 12 Shells |
| Items | Current-holder checks, authenticated immutable mint evidence, one finish per token | Transferred ownership is distinct from maker achievement; stale UI alone is never ownership proof |
@@ -23,11 +23,13 @@ Server credentials stay in ignored private environment files or encrypted hostin
Behind `VITE_SEALED_NOTE_ENABLED`, the browser fetches NEAR AI's model attestation for `z-ai/glm-5.3-flash` directly and without a key, with a fresh 32-byte nonce and `x-no-aliasing: true`, and verifies every returned instance with `@nearai/inference-sdk` 0.3.0 (TDX quote, NVIDIA GPU evidence required, nonce and signer binding). All instances must share one Ed25519 key. The SDK encrypts both messages to that key with E2EE v3 and a one-use reply key. Only the fixed harbor name and recent accepted return facts are sent; no player-written text.
-The relay receives the exact request bytes and the client/model public-key headers. It never decodes message content (it checks only that each content is ciphertext-shaped hex), never logs, and builds every upstream header itself: the server key, `X-Signing-Algo: ed25519`, `X-Encryption-Version: 3`, `X-Encrypt-All-Fields: true`, `x-no-aliasing: true` and `Accept-Encoding: identity`. The model and upstream URLs are constants and the chat id is pattern-checked before the signature URL, so neither the body nor the response can redirect the server key; redirects are refused. It returns the raw completion bytes and the raw `GET /v1/signature/?signing_algo=ed25519` bytes, retrying briefly.
+The relay receives the exact request bytes and the client/model public-key headers. It never decodes message content (it checks only that each content is ciphertext-shaped hex), never logs, and builds every upstream header itself: the server key, `X-Signing-Algo: ed25519`, `X-Encryption-Version: 3`, `X-Encrypt-All-Fields: true`, `x-no-aliasing: true` and `Accept-Encoding: identity`. The model and upstream URLs are constants and the chat id is pattern-checked before the signature URL, so neither the body nor the response can redirect the server key; redirects are refused. It returns the raw completion bytes and the raw `GET /v1/signature/?signing_algo=ed25519` bytes, polling for up to 10 seconds. The completion call is aborted after 35 seconds so the function ends inside its 60 second limit.
+
+The relay does not lock an account after one note: a broken or unrecorded result can be asked again within 3 notes per account per UTC day, 3 per hour per account and 120 per hour overall. Showing one note per accepted claim is a browser concern, kept in browser storage.
The browser decrypts with its one-use key and seals only when `signature_kind` is `provider_tee`, the signed text equals `z-ai/glm-5.3-flash:sha256(request bytes):sha256(response bytes)` and the Ed25519 signature verifies against the attested key. Anything else that still decrypts is a readable note labelled not sealed; anything unreadable is broken and shows no text. A replayed older signed response cannot seal a new request because the request hash covers fresh ciphertext bound to the new reply key.
-Limits: NEAR AI's instances share the model signing key, so the seal means only "signed by the attested model key", not a particular machine. No deployment measurement policy is pinned; the SDK's default accepted TCB statuses apply. If NEAR AI starts requiring a key for attestation, the note becomes broken; there is no relay fallback for attestation. A stored note in browser storage records the check made on that device; editing local storage can change what that device displays. Note-once and quotas are process-local.
+Limits: NEAR AI's instances share the model signing key, so the seal means only "signed by the attested model key", not a particular machine. No deployment measurement policy is pinned; the SDK's default accepted TCB statuses apply. If NEAR AI starts requiring a key for attestation, the note becomes broken; there is no relay fallback for attestation. A stored note in browser storage records the check made on that device; editing local storage can change what that device displays. Note quotas are process-local.
## Uncertain outcomes and recoverable progress
diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts
index 76470cd..d7117ca 100644
--- a/services/relayer/src/sealed-note.test.ts
+++ b/services/relayer/src/sealed-note.test.ts
@@ -4,7 +4,7 @@ import type { AddressInfo } from "node:net";
import { createTideboundHttpHandler, type TideboundHttpEnvironment } from "./tidebound-http";
import type { Backend } from "./app";
import type { PrivyService } from "./auth/privy";
-import { checkNoteBody, NOTE_MODEL, type NoteChain, type NoteFetch } from "./sealed-note";
+import { checkNoteBody, createNoteRelay, NOTE_MODEL, type NoteChain, type NoteFetch } from "./sealed-note";
const origin="https://familiar-two.vercel.app",root="familiar-game.testnet",account=`mochi.${root}`;
const key="synthetic-near-ai-key-never-real";
@@ -91,8 +91,8 @@ test("requires a confirmed journey event for the server-derived account",async()
}
});
-test("forwards the exact browser bytes with fixed headers, returns raw bytes and the retried signature, then writes once",async()=>{
- const f=fixture({signatureMisses:2});
+test("forwards the exact browser bytes with fixed headers, returns raw bytes and the retried signature, and allows a retry",async()=>{
+ const f=fixture({signatureMisses:1});
// Unusual key order proves the relay forwards bytes rather than a rebuilt body.
const sent=`{"max_tokens":96,"stream":false,"messages":[{"content":"${cipher}","role":"system"},{"content":"${cipher}","role":"user"}],"model":"${NOTE_MODEL}"}`;
await serve(enabled,f,async url=>{
@@ -101,13 +101,15 @@ test("forwards the exact browser bytes with fixed headers, returns raw bytes and
expect(Buffer.from(envelope.completion,"base64").toString()).toBe(completion);
expect(Buffer.from(envelope.signature,"base64").toString()).toBe(signature);
expect(JSON.stringify(envelope)).not.toContain(key);
- const again=await post(url,body());expect(again.status).toBe(409);expect((await again.json()).code).toBe("NOTE_WRITTEN");
+ expect((await post(url,body())).status).toBe(200);
});
- const [chat,...signatures]=f.forwarded;
+ const [chat,...rest]=f.forwarded;
+ const signatures=rest.slice(0,2);
+ expect(rest.length).toBe(4);
expect(chat!.url).toBe("https://cloud-api.near.ai/v1/chat/completions");
expect(new TextDecoder().decode(chat!.body!)).toBe(sent);
expect(chat!.headers).toEqual({authorization:`Bearer ${key}`,"content-type":"application/json","accept-encoding":"identity","x-signing-algo":"ed25519","x-encryption-version":"3","x-encrypt-all-fields":"true","x-no-aliasing":"true","x-client-pub-key":clientKey,"x-model-pub-key":modelKey});
- expect(signatures.map(s=>s.url)).toEqual(Array(3).fill("https://cloud-api.near.ai/v1/signature/chatcmpl-synthetic_1?signing_algo=ed25519"));
+ expect(signatures.map(s=>s.url)).toEqual(Array(2).fill("https://cloud-api.near.ai/v1/signature/chatcmpl-synthetic_1?signing_algo=ed25519"));
expect(signatures.every(s=>s.method==="GET"&&s.headers.authorization===`Bearer ${key}`&&!("x-client-pub-key" in s.headers))).toBe(true);
expect(f.views).toEqual([`player:ed25519:synthetic`,`journey:${account}`,`player:ed25519:synthetic`,`journey:${account}`]);
});
@@ -120,3 +122,36 @@ test("a failed upstream call releases the note; repeated attempts hit the per-ac
});
expect(f.forwarded.filter(r=>r.url.endsWith("/chat/completions")).length).toBe(3);
});
+
+const direct=(fetch:NoteFetch,options:{now?:()=>number;completionTimeoutMs?:number;signatureWindowMs?:number;signatureDelayMs?:number}={})=>
+ createNoteRelay({apiKey:key,chain:{player:async()=>account,confirmedClaims:async()=>1},fetch,...options});
+const input={walletPublicKey:"ed25519:synthetic",bytes:new TextEncoder().encode(body()) as Uint8Array,clientPublicKey:clientKey,modelPublicKey:modelKey};
+const answers:NoteFetch=async url=>new Response(url.endsWith("/chat/completions")?completion:signature);
+
+test("allows three notes per account per UTC day across hourly windows, then resets the next day",async()=>{
+ let clock=Date.parse("2026-11-14T00:30:00Z");
+ const relay=direct(answers,{now:()=>clock});
+ for(let i=0;i<3;i++)expect((await relay.write(input)).status).toBe(200);
+ expect((await relay.write(input)).status).toBe(429);
+ clock=Date.parse("2026-11-14T22:00:00Z");
+ const daily=await relay.write(input);expect(daily.status).toBe(429);expect(daily.body).toMatchObject({code:"QUOTA"});
+ clock=Date.parse("2026-11-15T00:01:00Z");
+ expect((await relay.write(input)).status).toBe(200);
+});
+
+test("a hung completion times out as a retryable upstream failure",async()=>{
+ const hang:NoteFetch=(_url,init)=>new Promise((_,reject)=>init.signal!.addEventListener("abort",()=>reject(init.signal!.reason)));
+ const started=Date.now();
+ const result=await direct(hang,{completionTimeoutMs:50}).write(input);
+ expect(result).toMatchObject({status:502,body:{code:"NOTE_UPSTREAM"}});
+ expect(Date.now()-started).toBeLessThan(1_000);
+});
+
+test("signature polling stops at its window and returns the completion without a signature",async()=>{
+ let polls=0;
+ const missing:NoteFetch=async url=>{if(url.endsWith("/chat/completions"))return new Response(completion);polls++;return new Response("{}",{status:404});};
+ const started=Date.now();
+ const result=await direct(missing,{signatureWindowMs:120,signatureDelayMs:20}).write(input);
+ expect(result.status).toBe(200);expect((result.body as {signature:unknown}).signature).toBeNull();
+ expect(polls).toBeGreaterThan(2);expect(Date.now()-started).toBeLessThan(1_000);
+});
diff --git a/services/relayer/src/sealed-note.ts b/services/relayer/src/sealed-note.ts
index 89ff194..d13842d 100644
--- a/services/relayer/src/sealed-note.ts
+++ b/services/relayer/src/sealed-note.ts
@@ -60,17 +60,23 @@ export function checkNoteBody(bytes:Uint8Array):NoteRefusal|null {
const wait=(ms:number)=>new Promise(resolve=>setTimeout(resolve,ms));
const base64=(bytes:Uint8Array)=>Buffer.from(bytes).toString("base64");
-export function createNoteRelay(options:{apiKey:string;chain:NoteChain;fetch?:NoteFetch;signatureAttempts?:number;signatureDelayMs?:number}) {
+export const NOTES_PER_ACCOUNT_DAY=3;
+/** Worst case stays inside the 60 s function limit: views, a 35 s completion, then at most 10 s of signature polling. */
+export const COMPLETION_TIMEOUT_MS=35_000,SIGNATURE_WINDOW_MS=10_000;
+
+export function createNoteRelay(options:{apiKey:string;chain:NoteChain;fetch?:NoteFetch;signatureWindowMs?:number;signatureDelayMs?:number;completionTimeoutMs?:number;now?:()=>number}) {
const send=options.fetch??((url,init)=>fetch(url,init));
- const attempts=options.signatureAttempts??6,delay=options.signatureDelayMs??500;
- const perAccount=new Quota(3,3_600_000),all=new Quota(120,3_600_000,1);
- // Process-local, like the existing account quotas. A restart or another instance allows another note.
- const written=new Set();
+ const window=options.signatureWindowMs??SIGNATURE_WINDOW_MS,delay=options.signatureDelayMs??1_000,now=options.now??Date.now;
+ // Process-local, like the existing account quotas. A broken note can be retried within the allowance;
+ // showing one note per accepted claim is the client's job.
+ const daily=new Quota(NOTES_PER_ACCOUNT_DAY,86_400_000),perAccount=new Quota(3,3_600_000),all=new Quota(120,3_600_000,1);
async function signature(id:string):Promise {
- for(let attempt=0;attemptnull);
if(!response)continue;
const bytes=new Uint8Array(await response.arrayBuffer().catch(()=>new ArrayBuffer(0)));
@@ -88,12 +94,11 @@ export function createNoteRelay(options:{apiKey:string;chain:NoteChain;fetch?:No
return {status:400,body:{code:"NOTE_KEYS",error:"Mochi's note needs both sealing keys."}};
const account=await options.chain.player(input.walletPublicKey);
if(!account||await options.chain.confirmedClaims(account)<1)return {status:409,body:{code:"NOTE_NO_EVENT",error:"Mochi writes after an accepted return."}};
- if(written.has(account))return {status:409,body:{code:"NOTE_WRITTEN",error:"Mochi has already written this harbor's note."}};
- if(!perAccount.take(account)||!all.take("all"))return {status:429,body:{code:"QUOTA",error:"Mochi is resting the pen. Try again later."}};
- written.add(account);
+ const day=new Date(now()).toISOString().slice(0,10);
+ if(!daily.take(`${account}:${day}`,now())||!perAccount.take(account,now())||!all.take("all",now()))return {status:429,body:{code:"QUOTA",error:"Mochi is resting the pen. Try again tomorrow."}};
let completion:Uint8Array;
try{
- const response=await send(`${upstream}/chat/completions`,{method:"POST",redirect:"error",body:input.bytes,headers:{
+ const response=await send(`${upstream}/chat/completions`,{method:"POST",redirect:"error",body:input.bytes,signal:AbortSignal.timeout(options.completionTimeoutMs??COMPLETION_TIMEOUT_MS),headers:{
authorization:`Bearer ${options.apiKey}`,"content-type":"application/json","accept-encoding":"identity",
"x-signing-algo":"ed25519","x-encryption-version":"3","x-encrypt-all-fields":"true","x-no-aliasing":"true",
"x-client-pub-key":input.clientPublicKey,"x-model-pub-key":input.modelPublicKey,
@@ -101,8 +106,7 @@ export function createNoteRelay(options:{apiKey:string;chain:NoteChain;fetch?:No
completion=new Uint8Array(await response.arrayBuffer());
if(!response.ok||completion.byteLength>65_536)throw Error("upstream");
}catch{
- written.delete(account);
- return {status:502,body:{code:"NOTE_UPSTREAM",error:"The note could not reach Mochi. Nothing was written."}};
+ return {status:502,body:{code:"NOTE_UPSTREAM",error:"The note could not reach Mochi. Try again."}};
}
let id:unknown;
try{id=JSON.parse(new TextDecoder().decode(completion)).id;}catch{id=null;}
diff --git a/web/src/note/SealedNote.tsx b/web/src/note/SealedNote.tsx
index 4418371..db97e17 100644
--- a/web/src/note/SealedNote.tsx
+++ b/web/src/note/SealedNote.tsx
@@ -44,7 +44,7 @@ export function SealedNote({returns,token,relayUrl=import.meta.env.VITE_RELAYER_
{note.state==="broken"?<>
The note got wet on the way.
{facts.reason??"It could not be opened."} Nothing unreadable is shown as Mochi's.
- {note.state==="unrecorded"&&again}
+ {note.state==="unrecorded"&&}
>}
{facts.model&&
From 4ecee1ece6df72fbfc9b0771bf7588890e1fab60 Mon Sep 17 00:00:00 2001
From: David Dada
Date: Sat, 14 Nov 2026 00:29:23 +0100
Subject: [PATCH 21/21] fix(note): keep a readable note when a retry fails and
name late refusals
---
PROGRESS.md | 2 +-
services/relayer/src/sealed-note.test.ts | 2 +-
services/relayer/src/sealed-note.ts | 2 +-
web/src/note/SealedNote.tsx | 7 ++++++-
4 files changed, 9 insertions(+), 4 deletions(-)
diff --git a/PROGRESS.md b/PROGRESS.md
index 61ee891..39df622 100644
--- a/PROGRESS.md
+++ b/PROGRESS.md
@@ -15,7 +15,7 @@ Full earlier progress and acceptance records are preserved in the [archive](docs
| 2026-11-13 | `make judge` and `make break` added; NEAR claims table in README | `make judge` (live fastnear RPC, `familiar-game.testnet`): 16 PASS, 0 FAIL, all 4 pets from `nft_tokens`. `make break`: 7 Rust refusal/acceptance tests (first_light_v1 and v2) + 5 signer tests pass. Codex hostile review found 5 gaps (undefined-hash false PASS, hard-coded pet sample, v1-only court tests, snapshot-vs-code and custody overclaims); all fixed. Full `make check`: 235 Bun tests, 130 Rust passes, typecheck; `make evidence` 15 signatures offline | Judge confirms every pet has no keys and run global code `CQQ63d8…` = `get_config.pet_code_hash`; `qa-maker-h1` has 2 accepted claims and 12 Shells granted once. Reported, not claimed: player keys are FullAccess (Privy-held), the method limit is the off-chain signer; root/items keep FullAccess admin keys; deployed root code `66HumWXu…` differs from the HEAD build `4xtG2991…` recorded in FAMILIAR-GAMEPLAY.json. `.env` NEAR_ROOT still names the older `familiar-1105-28522e` stack; judge does not read `.env`. Threat model now states replay proves legal steps only, winning inputs are public, and one pet passed between accounts earns each account a commission. `make break` uses the contract unit runtime, not the Wasm sandbox. No deploy, no signing, no push. |
| 2026-11-13 | Mochi's sealed note on local branch `feat/sealed-note` (flagged off) | `bun run test` 247 pass/15685 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace` 123 pass/2 ignored; `make build`, `bun run build:release`, `make browser` (Chromium/WebKit), `make evidence` (15 signatures) pass; mocked note UI viewed at 390×844 and 1440×900; `bun --env-file= scripts/sealed-note-live.ts` | Live 2026-11-13: keyless `GET /v1/model/z-ai%2Fglm-5.3-flash` → `providerType:vllm, attestationSupported:true`; keyless `GET /v1/attestation/report` (ed25519, fresh nonce, `x-no-aliasing`) → 200 with 3 instances sharing key `5a0210f2…0caff`, all verified by SDK 0.3.0 (`UpToDate`, GPU evidence required); CORS allows the production origin. Three live completions with `X-Encryption-Version: 3`: chats `8af36ee4753d4228994b34ee1a8183ab` and `f63baa0caeb549f4932deb02daa59745` were broken (GLM spent all 120 tokens reasoning, `finish_reason:length`, empty content, despite `chat_template_kwargs.enable_thinking:false`); after switching to `thinking_token_budget:0`, chat `daa6b15838fc402689766a28b7826446` returned `provider_tee`, decrypted and **sealed**. Then the real `writeSealedNote` ran inside Playwright Chromium and WebKit (SDK default browser verifiers via NEAR AI's PCCS/NRAS proxies, WebCrypto Ed25519) against the relay code in-process: chats `20d3c9c6263b42edac0533dd02eb89d4` (Chromium) and `d8b367f524824d53ad99bb8f2849d736` (WebKit) both **sealed**, and the note stayed attached after a later accepted return. Five live completions in total. Read-only testnet views: `tidebound_journey` on `familiar-game.testnet` returns `claims` (qa-maker-v2: 2, dadadave80: 0) and `rpcNoteChain` reads them; unregistered keys resolve to no player. Eligibility/identity in the live runs were local stand-ins; no Privy JWT, deployed relay or Vercel variable was exercised. The in-game satchel with the flag on was not viewed; the note component was viewed standalone with mocked results and in the live browser run. No push or deployment. |
| 2026-11-14 | Sealed-note review fixes on `feat/sealed-note` (still flagged off) | `bun run typecheck`; `bun run test` 250 pass/15699 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace` 123 pass/2 ignored; `make build`, `bun run build:release`, `make browser` (Chromium/WebKit), `make evidence` (15 signatures) pass; mocked note UI at 390×844 and 1440×900 (all five states, no horizontal overflow, no console errors); offline in-browser seal check in Chromium and WebKit with a locally signed `provider_tee` record | Relay: the note-once lock is replaced by 3 notes per account per UTC day plus 3/hour per account and 120/hour overall, so a broken note can be asked again; the completion call aborts after 35 s and signature polling runs for up to 10 s (tests cover the daily reset, a hung upstream and the polling window). Browser: a missing signature is a distinct "seal not recorded yet" state that is shown, retryable and never stored; the final Ed25519 check is the SDK's `verifyModelResponse` (tweetnacl), and the offline browser check sealed in both engines with `crypto.subtle.verify`/`importKey` disabled and rejected a flipped signature. The back of each note states only what that note established (sealed: full claim and shared-key limit; not sealed/unrecorded: attestation, encryption and the exact reason; broken: model and what happened). Keyboard focus moves to the note and a polite status region announces the outcome (checked in Chromium via the mocked fixture; no screen reader was run). No live NEAR AI completion was made for these fixes; no push or deployment. |
-| 2026-11-14 | Sealed-note second review fixes | Independent re-review (2 reviewers, each finding verified) confirmed 5 issues; `bun test services/relayer/src/sealed-note.test.ts web/src/note` 18 pass; full `bun run test`, `make build`, `make browser` (Chromium/WebKit), `make evidence` pass | All three note allowances are checked before any is charged (a refusal no longer uses up the next day); daily refusal is `QUOTA_DAY`, hourly/global `QUOTA` keeps Ask again; register reads (8 s each), completion and signature lookup are bounded from request start (55 s budget) and a late request is refused before charging; invite copy back to “One note per harbor.” to match the component; unrecorded notes offer “Ask for a new note”. Not run against live NEAR AI. |
+| 2026-11-14 | Sealed-note second review fixes | Independent re-review (2 reviewers, each finding verified) confirmed 5 issues; `bun test services/relayer/src/sealed-note.test.ts web/src/note` 18 pass; full `bun run test`, `make build`, `make browser` (Chromium/WebKit), `make evidence` pass | All three note allowances are checked before any is charged (a refusal no longer uses up the next day); daily refusal is `QUOTA_DAY`, hourly/global `QUOTA` keeps Ask again; register reads (8 s each), completion and signature lookup are bounded from request start (55 s budget) and a late request is refused before charging; invite copy back to “One note per harbor.” to match the component; unrecorded notes offer “Ask for a new note”. Final check of these fixes confirmed two more and both are fixed: a failed retry keeps the readable unrecorded note and says so visibly and to screen readers, and a request refused for lack of time returns `NOTE_LATE` instead of claiming the register was unreadable. The retry-keeps-note path is typechecked but not exercised in a browser. Not run against live NEAR AI. |
## Recorded discrepancies (NEAR AI, 2026-11-13)
diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts
index c446c36..2473036 100644
--- a/services/relayer/src/sealed-note.test.ts
+++ b/services/relayer/src/sealed-note.test.ts
@@ -180,6 +180,6 @@ test("a request that starts too late for a full completion is refused without ch
const counting:NoteFetch=async url=>{sent++;return new Response(url.endsWith("/chat/completions")?completion:signature);};
const relay=direct(counting);
const late=await relay.write({...input,startedAt:Date.now()-NOTE_DEADLINE_MS+SIGNATURE_WINDOW_MS+1_000});
- expect(late.status).toBe(503);expect(sent).toBe(0);
+ expect(late.status).toBe(503);expect(late.body).toMatchObject({code:"NOTE_LATE"});expect(sent).toBe(0);
for(let i=0;i<3;i++)expect((await relay.write(input)).status).toBe(200);
});
diff --git a/services/relayer/src/sealed-note.ts b/services/relayer/src/sealed-note.ts
index ad938e3..a22d5c8 100644
--- a/services/relayer/src/sealed-note.ts
+++ b/services/relayer/src/sealed-note.ts
@@ -103,7 +103,7 @@ export function createNoteRelay(options:{apiKey:string;chain:NoteChain;fetch?:No
if(!account)return {status:409,body:{code:"NOTE_NO_EVENT",error:"Mochi writes after an accepted return."}};
// Leave room for the signature lookup; refuse before charging anything if the completion would be cut short.
const completionMs=Math.min(options.completionTimeoutMs??COMPLETION_TIMEOUT_MS,deadline-now()-Math.min(window,SIGNATURE_WINDOW_MS));
- if(completionMs(stored);
const [busy,setBusy]=useState(false);
const [announcement,setAnnouncement]=useState("");
+ const [retryFailed,setRetryFailed]=useState(null);
const paper=useRef(null),focusPaper=useRef(false);
const alive=useRef(true);useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
useEffect(()=>{setNote(stored());},[keyList,store]);
@@ -36,7 +37,10 @@ export function SealedNote({returns,token,relayUrl=import.meta.env.VITE_RELAYER_
}catch{result={state:"broken",back:{model:"",attestation:"",verifiedIn:"",reason:"The note could not be opened."}};}
// Only finished outcomes are kept. Broken and unrecorded notes can be asked for again.
if(result.state==="sealed"||result.state==="plain")try{store?.setItem(key!,JSON.stringify(result));}catch{ /* The note still shows for this visit. */ }
- if(alive.current){focusPaper.current=true;setNote(result);setBusy(false);setAnnouncement(ANNOUNCE[result.state]);}
+ if(!alive.current)return;
+ // A failed retry never replaces a note the player can already read.
+ if(result.state==="broken"&¬e&¬e.state!=="broken"){const kept=`No new note this time. ${result.back.reason??"It could not be opened."} The note you have is still here.`;setBusy(false);setRetryFailed(kept);setAnnouncement(kept);return;}
+ focusPaper.current=true;setRetryFailed(null);setNote(result);setBusy(false);setAnnouncement(ANNOUNCE[result.state]);
}
const status=