From af0721dad29066b3fd7c29aa06ee16d98e0fbfa9 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:37:46 +0100 Subject: [PATCH 01/21] feat(relayer): forward Mochi's sealed note to NEAR AI with plain-field checks --- .env.example | 1 + services/relayer/src/app.ts | 13 ++- services/relayer/src/sealed-note.test.ts | 119 +++++++++++++++++++++++ services/relayer/src/sealed-note.ts | 110 +++++++++++++++++++++ services/relayer/src/tidebound-http.ts | 14 ++- 5 files changed, 251 insertions(+), 6 deletions(-) create mode 100644 services/relayer/src/sealed-note.test.ts create mode 100644 services/relayer/src/sealed-note.ts diff --git a/.env.example b/.env.example index 5422782..8eb4345 100644 --- a/.env.example +++ b/.env.example @@ -47,3 +47,4 @@ TIDEBOUND_HTTP_ENABLED=false # Harbor records panel (live public reads only). Off unless exactly "true". VITE_RECORDS_ENABLED=false +NEAR_AI_API_KEY= diff --git a/services/relayer/src/app.ts b/services/relayer/src/app.ts index 5fdb13f..c5a0076 100644 --- a/services/relayer/src/app.ts +++ b/services/relayer/src/app.ts @@ -6,6 +6,7 @@ import { Quota, STAMPS } from "./relay"; import { validName } from "../../../web/src/rules"; import { UsernameError, usernameErrors, type UsernameAvailability } from "../../../web/src/account/names"; import { PrivyBridgeError, type PrivyService } from "./auth/privy"; +import type { NoteRelay } from "./sealed-note"; export type RelayResult = { hash: string; @@ -24,6 +25,7 @@ export function createApp( config: { origins: string[]; root: string }, backend?: Backend, privy?: PrivyService, + notes?: NoteRelay, ) { const app = new Hono(); const guests = new Quota(200, 86_400_000, 1); @@ -35,7 +37,7 @@ export function createApp( cors({ origin: config.origins, allowMethods: ["GET", "POST", "OPTIONS"], - allowHeaders: ["Content-Type", "Authorization"], + allowHeaders: ["Content-Type", "Authorization", "X-Client-Pub-Key", "X-Model-Pub-Key"], }), ); app.use("*", async (c, next) => { @@ -92,6 +94,15 @@ export function createApp( const accountId=await backend.guest(wallet.publicKey,body.username); return c.json({accountId,root:config.root,network:"testnet"}); }); + // Exact encrypted bytes; only plain routing/budget fields are checked. Message content is never decoded or logged. + app.post("/v1/privy/note",async c=>{ + if(!notes)return c.json({code:"NOTE_DISABLED",error:"Mochi's sealed note is not enabled for this harbor."},503); + const bytes=new Uint8Array(await c.req.arrayBuffer()); + const wallet=await privy!.wallet(c.req.header("authorization")!.slice(7),false); + if(!wallet)return c.json({code:"ERR_PRIVY_WALLET_REQUIRED",error:"Create your recoverable wallet explicitly before asking for a note."},409); + const result=await notes.write({walletPublicKey:wallet.publicKey,bytes,clientPublicKey:c.req.header("x-client-pub-key"),modelPublicKey:c.req.header("x-model-pub-key")}); + return c.json(result.body as Record,result.status as 200); + }); app.use("/v1/*", async (c, next) => { if (!backend) return c.json( diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts new file mode 100644 index 0000000..72959fc --- /dev/null +++ b/services/relayer/src/sealed-note.test.ts @@ -0,0 +1,119 @@ +import { expect, test } from "bun:test"; +import { createServer } from "node:http"; +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"; + +const origin="https://familiar-two.vercel.app",root="familiar-game.testnet",account=`mochi.${root}`; +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 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"}'; + +function fixture(options:{claims?:number;player?:string|null;signatureMisses?:number;upstreamStatus?:number}={}) { + const forwarded:{url:string;method:string;headers:Record;body:Uint8Array|null}[]=[]; + let misses=options.signatureMisses??0; + const noteFetch:NoteFetch=async(url,init)=>{ + forwarded.push({url,method:init.method!,headers:Object.fromEntries(new Headers(init.headers).entries()),body:init.body?new Uint8Array(init.body as Uint8Array):null}); + if(url.endsWith("/chat/completions"))return new Response(completion,{status:options.upstreamStatus??200}); + if(misses-->0)return new Response('{"error_code":"not_found","message":"Chat id not found or expired"}',{status:404}); + return new Response(signature,{status:200}); + }; + const views:string[]=[]; + const noteChain:NoteChain={player:async publicKey=>{views.push(`player:${publicKey}`);return options.player===undefined?account:options.player},confirmedClaims:async id=>{views.push(`journey:${id}`);return options.claims??1}}; + const backend:Backend={accountProvider:"privy",ready:async()=>true,guest:async()=>{throw Error("unreachable")},relay:async()=>{throw Error("unreachable")}}; + const privy:PrivyService={wallet:async(token,create)=>{expect(token).toBe("header.payload.signature");expect(create).toBe(false);return {walletId:"w",implicitAddress:"1".repeat(64),publicKey:"ed25519:synthetic"}}}; + return {forwarded,views,noteFetch,noteChain,backend,privy}; +} +async function serve(environment:TideboundHttpEnvironment,f:ReturnType,work:(url:string)=>Promise){ + const server=createServer(createTideboundHttpHandler({environment,backend:f.backend,privy:f.privy,noteChain:f.noteChain,noteFetch:f.noteFetch})); + await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)}); + try{await work(`http://127.0.0.1:${(server.address() as AddressInfo).port}`)}finally{await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()))} +} +const headers={origin,"content-type":"application/json",authorization:"Bearer header.payload.signature","x-client-pub-key":clientKey,"x-model-pub-key":modelKey}; +const post=(url:string,text:string,extra:Record={})=>fetch(url+"/api/v1/privy/note",{method:"POST",headers:{...headers,...extra},body:text}); + +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(); + 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"], + [{max_tokens:121},"NOTE_MAX_TOKENS"],[{max_tokens:0},"NOTE_MAX_TOKENS"],[{max_tokens:12.5},"NOTE_MAX_TOKENS"],[{max_tokens:"120"},"NOTE_MAX_TOKENS"], + [{messages:[{role:"user",content:cipher}]},"NOTE_MESSAGES"],[{messages:[{role:"system",content:cipher},{role:"user",content:cipher},{role:"user",content:cipher}]},"NOTE_MESSAGES"], + [{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"], + ]; + for(const [patch,code] of cases)expect(checkNoteBody(bytes(body(patch)))?.code).toBe(code); + expect(checkNoteBody(bytes("[]"))?.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"}); +}); + +test("note endpoint is off without NEAR_AI_API_KEY and leaves the other account endpoints unchanged",async()=>{ + const {NEAR_AI_API_KEY:_,...withoutKey}=enabled; + const f=fixture();await serve(withoutKey,f,async url=>{ + const response=await post(url,body());expect(response.status).toBe(503);expect((await response.json()).code).toBe("NOTE_DISABLED"); + expect((await fetch(url+"/api/health")).status).toBe(200); + });expect(f.forwarded).toEqual([]);expect(f.views).toEqual([]); + const g=fixture();await serve({...enabled,TIDEBOUND_HTTP_ENABLED:"false"},g,async url=>{expect((await post(url,body())).status).toBe(503)});expect(g.forwarded).toEqual([]); +}); + +test("note endpoint keeps exact path, method, origin, session and size guards before any chain or NEAR AI call",async()=>{ + const f=fixture();await serve(enabled,f,async url=>{ + for(const path of ["/api/v1/privy/note/","/api/v1/privy/note?model=x","/api/v1/note","/api/v1/privy/notes"])expect((await fetch(url+path,{method:"POST",headers,body:body()})).status).toBe(404); + expect((await fetch(url+"/api/v1/privy/note")).status).toBe(405); + for(const bad of ["","https://wrong.example"])expect((await post(url,body(),{origin:bad})).status).toBe(403); + for(const authorization of ["","Bearer nope","Basic x"])expect((await post(url,body(),{authorization})).status).toBe(401); + expect((await post(url,JSON.stringify({padding:"x".repeat(16_384)}))).status).toBe(413); + expect((await post(url,body({stream:true}))).status).toBe(400); + for(const bad of [{"x-client-pub-key":"A".repeat(64)},{"x-model-pub-key":"b".repeat(63)},{"x-client-pub-key":""}])expect((await post(url,body(),bad)).status).toBe(400); + const preflight=await fetch(url+"/api/v1/privy/note",{method:"OPTIONS",headers:{origin,"access-control-request-method":"POST","access-control-request-headers":"authorization,content-type,x-client-pub-key,x-model-pub-key"}}); + expect(preflight.status).toBe(204);expect(preflight.headers.get("access-control-allow-origin")).toBe(origin); + expect(preflight.headers.get("access-control-allow-headers")?.toLowerCase()).toContain("x-model-pub-key"); + });expect(f.forwarded).toEqual([]);expect(f.views).toEqual([]); +}); + +test("requires a confirmed journey event for the server-derived account",async()=>{ + for(const options of [{claims:0},{player:null}]){ + const f=fixture(options);await serve(enabled,f,async url=>{const response=await post(url,body());expect(response.status).toBe(409);expect((await response.json()).code).toBe("NOTE_NO_EVENT");}); + expect(f.forwarded).toEqual([]); + } +}); + +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`; + await serve(enabled,f,async url=>{ + const response=await post(url,sent);expect(response.status).toBe(200); + const envelope=await response.json(); + 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"); + }); + const [chat,...signatures]=f.forwarded; + 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.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}`]); +}); + +test("a failed upstream call releases the note; repeated attempts hit the per-account rate limit",async()=>{ + const f=fixture({upstreamStatus:500}); + await serve(enabled,f,async url=>{ + for(let i=0;i<3;i++){const response=await post(url,body());expect(response.status).toBe(502);expect(await response.text()).not.toContain(key);} + const limited=await post(url,body());expect(limited.status).toBe(429); + }); + expect(f.forwarded.filter(r=>r.url.endsWith("/chat/completions")).length).toBe(3); +}); diff --git a/services/relayer/src/sealed-note.ts b/services/relayer/src/sealed-note.ts new file mode 100644 index 0000000..9707073 --- /dev/null +++ b/services/relayer/src/sealed-note.ts @@ -0,0 +1,110 @@ +import { JsonRpcProvider } from "near-api-js"; +import { isPlayerAccount } from "../../../web/src/account/names"; +import { Quota } from "./relay"; + +/** Mochi's sealed note. The relay checks plain fields only and forwards the browser's exact encrypted bytes. */ +export const NOTE_MODEL="z-ai/glm-5.3-flash"; +export const NOTE_MAX_TOKENS=120; +export const NOTE_BODY_LIMIT=8_192; +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"]); + +export interface NoteChain { + /** Root `get_player` for the server-verified wallet key. */ + player(publicKey:string):Promise; + /** Number of accepted claims in root `tidebound_journey`. */ + confirmedClaims(accountId:string):Promise; +} +/** Finalized root views only: the verified wallet's registered player, then its accepted claims. */ +export function rpcNoteChain(root:string,rpcUrl:string):NoteChain { + const provider=new JsonRpcProvider({url:rpcUrl}); + return { + async player(publicKey){const account=await provider.callFunction({contractId:root,method:"get_player",args:{public_key:publicKey},blockQuery:{finality:"final"}});return typeof account==="string"&&isPlayerAccount(account,root)?account:null;}, + async confirmedClaims(accountId){const journey=await provider.callFunction<{claims:unknown[]}>({contractId:root,method:"tidebound_journey",args:{account_id:accountId},blockQuery:{finality:"final"}});return Array.isArray(journey?.claims)?journey.claims.length:0;}, + }; +} +export type NoteRefusal={status:400|409|413|429;code:string}; +export type NoteFetch=(url:string,init:RequestInit)=>Promise; + +/** Reads only routing and budget fields. Message contents must already be ciphertext hex and are never decoded. */ +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"};} + 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"}; + 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"}; + const messages=value.messages; + if(!Array.isArray(messages)||messages.length!==2)return {status:400,code:"NOTE_MESSAGES"}; + const roles=["system","user"]; + for(const [index,message] of messages.entries()){ + if(!message||typeof message!=="object"||Array.isArray(message))return {status:400,code:"NOTE_MESSAGES"}; + const keys=Object.keys(message); + if(keys.length!==2||(message as {role?:unknown}).role!==roles[index]||typeof (message as {content?:unknown}).content!=="string"||!ciphertext.test((message as {content:string}).content)) + return {status:400,code:"NOTE_MESSAGES"}; + } + return 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}) { + 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(); + 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))); + if(response.ok&&bytes.byteLength>0&&bytes.byteLength<=8_192){ + try{const value=JSON.parse(new TextDecoder().decode(bytes));if(value&&typeof value==="object"&&typeof value.signature==="string")return bytes;}catch{ /* retry */ } + } + } + return null; + } + return { + async write(input:{walletPublicKey:string;bytes:Uint8Array;clientPublicKey:string|undefined;modelPublicKey:string|undefined}):Promise<{status:number;body:unknown}> { + const refused=checkNoteBody(input.bytes); + if(refused)return {status:refused.status,body:{code:refused.code,error:"Mochi's note could not be sent in that form."}}; + if(!input.clientPublicKey||!hexKey.test(input.clientPublicKey)||!input.modelPublicKey||!hexKey.test(input.modelPublicKey)) + 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); + let completion:Uint8Array; + try{ + const response=await send(`${upstream}/chat/completions`,{method:"POST",redirect:"error",body:input.bytes,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, + }}); + 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."}}; + } + let id:unknown; + try{id=JSON.parse(new TextDecoder().decode(completion)).id;}catch{id=null;} + const signed=typeof id==="string"&&chatId.test(id)?await signature(id):null; + return {status:200,body:{completion:base64(completion),signature:signed?base64(signed):null}}; + }, + }; +} +export type NoteRelay=ReturnType; diff --git a/services/relayer/src/tidebound-http.ts b/services/relayer/src/tidebound-http.ts index ae10c7f..eb2ecfb 100644 --- a/services/relayer/src/tidebound-http.ts +++ b/services/relayer/src/tidebound-http.ts @@ -4,15 +4,16 @@ import type { KeyPairString } from "near-api-js"; import { createApp, type Backend } from "./app"; import { createBackend } from "./chain"; import { createPrivyBridge, type PrivyService } from "./auth/privy"; +import { createNoteRelay, rpcNoteChain, type NoteChain, type NoteFetch } from "./sealed-note"; const origin="https://familiar-two.vercel.app",root="familiar-game.testnet",items=`items.${root}`; const rpc="https://test.rpc.fastnear.com"; export interface TideboundHttpEnvironment { TIDEBOUND_HTTP_ENABLED?:string;ACCOUNT_PROVIDER?:string;NEAR_NETWORK?:string;NEAR_ROOT?:string; - RELAYER_ID?:string;RELAYER_PRIVATE_KEY?:string;PRIVY_APP_ID?:string;PRIVY_APP_SECRET?:string; + RELAYER_ID?:string;RELAYER_PRIVATE_KEY?:string;PRIVY_APP_ID?:string;PRIVY_APP_SECRET?:string;NEAR_AI_API_KEY?:string; } -/** Expose through the three exact .func aliases; request headers and query strings never choose a route. */ -export function createTideboundHttpHandler(options:{environment?:TideboundHttpEnvironment;backend?:Backend;privy?:PrivyService}={}) { +/** Expose through the four exact .func aliases; request headers and query strings never choose a route. */ +export function createTideboundHttpHandler(options:{environment?:TideboundHttpEnvironment;backend?:Backend;privy?:PrivyService;noteChain?:NoteChain;noteFetch?:NoteFetch}={}) { const environment=options.environment??process.env; // Hono's quotas are process-local. Use one configured instance or add durable quotas before scaling. let app:ReturnType|undefined; @@ -21,18 +22,21 @@ export function createTideboundHttpHandler(options:{environment?:TideboundHttpEn const json=(status:number,code:string,error:string)=>{res.statusCode=status;res.setHeader("content-type","application/json; charset=utf-8");res.end(JSON.stringify({code,error}));}; const path=req.url??""; const method=path==="/api/health"?"GET": - path==="/api/v1/privy/wallet"||path==="/api/v1/privy/player"?"POST":null; + path==="/api/v1/privy/wallet"||path==="/api/v1/privy/player"||path==="/api/v1/privy/note"?"POST":null; if(!method){json(404,"NOT_FOUND","This harbor serves only H1 account requests.");return;} if(req.method!==method&&req.method!=="OPTIONS"){res.setHeader("allow",`${method}, OPTIONS`);json(405,"METHOD_NOT_ALLOWED","Use the account request's configured method.");return;} if(environment.TIDEBOUND_HTTP_ENABLED!=="true"||environment.ACCOUNT_PROVIDER!=="privy"||environment.NEAR_NETWORK!=="testnet"|| environment.NEAR_ROOT!==root||environment.RELAYER_ID!==`relayer.${root}`||!environment.RELAYER_PRIVATE_KEY||!environment.PRIVY_APP_ID||!environment.PRIVY_APP_SECRET){ json(503,"TIDEBOUND_DISABLED","H1 account saving is not enabled for this harbor.");return; } + const apiKey=environment.NEAR_AI_API_KEY; + if(path==="/api/v1/privy/note"&&!apiKey){json(503,"NOTE_DISABLED","Mochi's sealed note is not enabled for this harbor.");return;} try { if(!app){ const backend=options.backend??createBackend(root,`relayer.${root}`,environment.RELAYER_PRIVATE_KEY as KeyPairString,rpc,{provider:"privy",items,origins:[origin]}); if(backend.accountProvider!=="privy"||backend.authSign)throw Error("Invalid H1 account provider."); - app=createApp({origins:[origin],root},backend,options.privy??createPrivyBridge({appId:environment.PRIVY_APP_ID,appSecret:environment.PRIVY_APP_SECRET})); + const notes=apiKey?createNoteRelay({apiKey,chain:options.noteChain??rpcNoteChain(root,rpc),fetch:options.noteFetch}):undefined; + app=createApp({origins:[origin],root},backend,options.privy??createPrivyBridge({appId:environment.PRIVY_APP_ID,appSecret:environment.PRIVY_APP_SECRET}),notes); } const headers=new Headers(); for(const [name,value] of Object.entries(req.headers)){ From 597e781b4f62b7bdc3f82e5b1409f3e2acfe648e Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:38:21 +0100 Subject: [PATCH 02/21] build: package the sealed-note path beside the account endpoints --- scripts/package-tidebound-review.test.ts | 4 ++-- scripts/package-tidebound-review.ts | 18 +++++++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/scripts/package-tidebound-review.test.ts b/scripts/package-tidebound-review.test.ts index ff2e590..3aa73aa 100644 --- a/scripts/package-tidebound-review.test.ts +++ b/scripts/package-tidebound-review.test.ts @@ -50,11 +50,11 @@ test("only the existing Familiar project and original-path function routing are for(const path of HTTP_PATHS)expect(()=>validateRouting({...config,routes:[{src:path+"$",dest:"/wallet"},...config.routes]})).toThrow("original request URL"); expect(()=>validateRouting({version:3,routes:[]})).toThrow("filesystem"); }); -test("three fixed URLs share one physical handler using relative aliases without rewrites",async()=>{ +test("four fixed URLs share one physical handler using relative aliases without rewrites",async()=>{ const output=await mkdtemp(join(tmpdir(),"familiar-game-function-test-")),primary=join(output,"functions/api/v1/privy/wallet.func");await mkdir(primary,{recursive:true}); await writeFile(join(primary,"index.mjs"),"export default (req,res)=>res.end(req.url)");await writeFile(join(primary,".vc-config.json"),JSON.stringify({runtime:"nodejs24.x",handler:"index.mjs",shouldAddHelpers:false})); const aliases=await installFunctionAliases(output); - expect(aliases).toEqual([{path:"api/health.func",target:"v1/privy/wallet.func"},{path:"api/v1/privy/player.func",target:"wallet.func"}]); + expect(aliases).toEqual([{path:"api/health.func",target:"v1/privy/wallet.func"},{path:"api/v1/privy/player.func",target:"wallet.func"},{path:"api/v1/privy/note.func",target:"wallet.func"}]); for(const alias of aliases){const path=join(output,"functions",alias.path);expect((await lstat(path)).isSymbolicLink()).toBe(true);expect(await readlink(path)).not.toStartWith("/");expect(await realpath(path)).toBe(await realpath(primary));expect(await readFile(join(path,"index.mjs"),"utf8")).toBe(await readFile(join(primary,"index.mjs"),"utf8"));} const before=await Promise.all(aliases.map(alias=>lstat(join(output,"functions",alias.path)).then(stat=>stat.ino))); await writeFile(join(primary,"index.mjs"),"export default (req,res)=>res.end('patched '+req.url)"); diff --git a/scripts/package-tidebound-review.ts b/scripts/package-tidebound-review.ts index f7cf22f..2d99698 100644 --- a/scripts/package-tidebound-review.ts +++ b/scripts/package-tidebound-review.ts @@ -6,7 +6,9 @@ import { build } from "vite"; import react from "@vitejs/plugin-react"; export const GAME_HTML=["index.html","outing/index.html"] as const; -export const HTTP_PATHS=["/api/health","/api/v1/privy/wallet","/api/v1/privy/player"] as const; +export const HTTP_PATHS=["/api/health","/api/v1/privy/wallet","/api/v1/privy/player","/api/v1/privy/note"] as const; +// A reviewed baseline predates the sealed-note path; its declared scope is checked against these originals. +const BASELINE_HTTP_PATHS=HTTP_PATHS.slice(0,3); export const RUNTIME_WEBPS=[ ...["harbor","arena","wind-gate","mochi","mochi-poses","tidekeeper","lens","moth"].map(name=>`assets/first-light-motion/${name}.webp`), ...["harbor","mochi-poses","tidekeeper","shell","lens","moth","wave","bram","tide-court","stone-island","wooden-bridge"].map(name=>`assets/expedition/runtime/${name}.webp`), @@ -14,8 +16,10 @@ export const RUNTIME_WEBPS=[ export const RUNTIME_METADATA=["assets/first-light-motion/provenance.json","assets/first-light-motion/wind-gate.webp.json","assets/expedition/provenance.json","assets/expedition/runtime/manifest.json"] as const; export const BRAND_ASSETS=["icons/mochi.ico",...[32,180,192,512].map(size=>`icons/mochi-${size}.png`),"social/familiar-harbor.jpg","familiar.webmanifest"]; const primaryFunction="api/v1/privy/wallet.func"; -const aliases=["api/health.func","api/v1/privy/player.func"] as const; -const endpoints=[{path:HTTP_PATHS[0],methods:["GET","OPTIONS"]},...HTTP_PATHS.slice(1).map(path=>({path,methods:["POST","OPTIONS"]}))]; +const aliases=["api/health.func","api/v1/privy/player.func","api/v1/privy/note.func"] as const; +const baselineAliases=aliases.slice(0,2); +const endpointsFor=(paths:readonly string[])=>[{path:paths[0],methods:["GET","OPTIONS"]},...paths.slice(1).map(path=>({path,methods:["POST","OPTIONS"]}))]; +const endpoints=endpointsFor(HTTP_PATHS),baselineEndpoints=endpointsFor(BASELINE_HTTP_PATHS); const gameRoot="familiar-game.testnet",origin="https://familiar-two.vercel.app"; const digest=(bytes:Uint8Array)=>createHash("sha256").update(bytes).digest("hex"); const hash=async(path:string)=>digest(await readFile(path)); @@ -40,7 +44,7 @@ export function validateRouting(config:unknown) { check(!HTTP_PATHS.some(path=>new RegExp(route.src).test(path)),"A baseline rewrite would change an H1 function's original request URL."); } function publicBytes(bytes:Uint8Array,path:string) { - check(!/PRIVY_APP_SECRET|VITE_PRIVY_APP_SECRET|RELAYER_PRIVATE_KEY|ROOT_PRIVATE_KEY|NPC_ADMIN_PRIVATE_KEY|NPC_PRIVATE_KEY|NEAR_PRIVATE_KEY|-----BEGIN (?:EC |RSA |OPENSSH )?PRIVATE KEY-----[\r\n]+[A-Za-z0-9+/=\r\n]{64,}-----END/.test(new TextDecoder().decode(bytes)),`Server configuration or private key material appears in the static overlay: ${path}`); + check(!/NEAR_AI_API_KEY|PRIVY_APP_SECRET|VITE_PRIVY_APP_SECRET|RELAYER_PRIVATE_KEY|ROOT_PRIVATE_KEY|NPC_ADMIN_PRIVATE_KEY|NPC_PRIVATE_KEY|NEAR_PRIVATE_KEY|-----BEGIN (?:EC |RSA |OPENSSH )?PRIVATE KEY-----[\r\n]+[A-Za-z0-9+/=\r\n]{64,}-----END/.test(new TextDecoder().decode(bytes)),`Server configuration or private key material appears in the static overlay: ${path}`); } /** Add only approved art and branding that the baseline lacks; never replace its assets. */ export async function copyRuntimeAssets(sourcePublic:string,destination:string) { @@ -152,9 +156,9 @@ export function baselineFunctionScope(manifest:unknown,actualHash:string,actualA const fn=manifest.privateFunction; check("sha256" in fn && /^[a-f0-9]{64}$/.test(actualHash) && fn.sha256===actualHash,"The baseline manifest does not match the actual private handler hash."); if("mode" in manifest && manifest.mode==="LOCAL_H1_REVIEW_ONLY") { - const expected=[{path:aliases[0],target:"v1/privy/wallet.func"},{path:aliases[1],target:"wallet.func"}]; + const expected=[{path:baselineAliases[0],target:"v1/privy/wallet.func"},{path:baselineAliases[1],target:"wallet.func"}]; const declaredAliases="aliases" in fn?fn.aliases:null; - check("path" in fn && fn.path===primaryFunction && "endpoints" in fn && JSON.stringify(fn.endpoints)===JSON.stringify(endpoints) && + check("path" in fn && fn.path===primaryFunction && "endpoints" in fn && JSON.stringify(fn.endpoints)===JSON.stringify(baselineEndpoints) && Array.isArray(declaredAliases) && declaredAliases.length===expected.length && expected.every(alias=>declaredAliases.some((item:unknown)=>!!item&&typeof item==="object"&&"path" in item&&"target" in item&&item.path===alias.path&&item.target===alias.target)) && JSON.stringify(actualAliases)===JSON.stringify(expected),"The baseline H1 function scope or aliases are unverified."); return "h1"; @@ -190,7 +194,7 @@ async function main() { routing:{baselineConfigSha256:digest(configBytes),currentConfigSha256:await hash(join(output,"config.json")),changed:true,retiredPagesRedirected:true,originalFunctionRequestUrlPreserved:true}, publicBuild:{provider:"privy",tideboundUiEnabled:true,root:gameRoot,relayerUrl:"/api",appIdSha256:digest(new TextEncoder().encode(appId)),environmentFilesLoaded:false}, privateFunction:{path:primaryFunction,scopeBefore,scopeAfter:"h1",scopeChangedFromRecoveryOnly:scopeBefore==="recovery-only",beforeSha256:oldFunctionSha256,sha256:await hash(join(fn,"index.mjs")),bytes:await Bun.file(join(fn,"index.mjs")).size,runtime:"nodejs24.x",shouldAddHelpers:false,aliases:functionAliases,endpoints,enabledByDefault:false}, - requiredRuntimeEnvironmentNames:["TIDEBOUND_HTTP_ENABLED","ACCOUNT_PROVIDER","NEAR_NETWORK","NEAR_ROOT","RELAYER_ID","RELAYER_PRIVATE_KEY","PRIVY_APP_ID","PRIVY_APP_SECRET"], + requiredRuntimeEnvironmentNames:["TIDEBOUND_HTTP_ENABLED","ACCOUNT_PROVIDER","NEAR_NETWORK","NEAR_ROOT","RELAYER_ID","RELAYER_PRIVATE_KEY","PRIVY_APP_ID","PRIVY_APP_SECRET"],optionalRuntimeEnvironmentNames:["NEAR_AI_API_KEY"], requiredNonSecretRuntimeValues:{TIDEBOUND_HTTP_ENABLED:"true",ACCOUNT_PROVIDER:"privy",NEAR_NETWORK:"testnet",NEAR_ROOT:gameRoot,RELAYER_ID:`relayer.${gameRoot}`}, limits:{compatibleContractsVerified:false,liveGameActionsTested:false,hostingAliasUrlBehaviorVerified:false,privateRuntimeConfigured:false},uploaded:false,deployed:false}; await writeFile(join(release,"review-manifest.json"),JSON.stringify(manifest,null,2)+"\n");console.info(JSON.stringify(manifest,null,2)); From 7e3e25ba5408cc7648e7dd33217501794937b0b7 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:41:04 +0100 Subject: [PATCH 03/21] test(relayer): type the sealed-note header cases --- services/relayer/src/sealed-note.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/relayer/src/sealed-note.test.ts b/services/relayer/src/sealed-note.test.ts index 72959fc..70321b9 100644 --- a/services/relayer/src/sealed-note.test.ts +++ b/services/relayer/src/sealed-note.test.ts @@ -74,7 +74,7 @@ test("note endpoint keeps exact path, method, origin, session and size guards be for(const authorization of ["","Bearer nope","Basic x"])expect((await post(url,body(),{authorization})).status).toBe(401); expect((await post(url,JSON.stringify({padding:"x".repeat(16_384)}))).status).toBe(413); expect((await post(url,body({stream:true}))).status).toBe(400); - for(const bad of [{"x-client-pub-key":"A".repeat(64)},{"x-model-pub-key":"b".repeat(63)},{"x-client-pub-key":""}])expect((await post(url,body(),bad)).status).toBe(400); + for(const bad of [{"x-client-pub-key":"A".repeat(64)},{"x-model-pub-key":"b".repeat(63)},{"x-client-pub-key":""}] as Record[])expect((await post(url,body(),bad)).status).toBe(400); const preflight=await fetch(url+"/api/v1/privy/note",{method:"OPTIONS",headers:{origin,"access-control-request-method":"POST","access-control-request-headers":"authorization,content-type,x-client-pub-key,x-model-pub-key"}}); expect(preflight.status).toBe(204);expect(preflight.headers.get("access-control-allow-origin")).toBe(origin); expect(preflight.headers.get("access-control-allow-headers")?.toLowerCase()).toContain("x-model-pub-key"); From ce97d6b8d803cefb4b8dcae061d202147510f7b7 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:41:04 +0100 Subject: [PATCH 04/21] feat(web): verify, encrypt and seal Mochi's note with the NEAR AI SDK --- bun.lock | 168 ++++++++++++++++++++++++++------------ package.json | 3 + web/package.json | 1 + web/src/note/note.test.ts | 143 ++++++++++++++++++++++++++++++++ web/src/note/prompt.ts | 26 ++++++ web/src/note/seal.ts | 32 ++++++++ web/src/note/write.ts | 85 +++++++++++++++++++ 7 files changed, 404 insertions(+), 54 deletions(-) create mode 100644 web/src/note/note.test.ts create mode 100644 web/src/note/prompt.ts create mode 100644 web/src/note/seal.ts create mode 100644 web/src/note/write.ts diff --git a/bun.lock b/bun.lock index c62b5f6..c049975 100644 --- a/bun.lock +++ b/bun.lock @@ -15,6 +15,9 @@ "react-dom": "19.3.1", }, "devDependencies": { + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", "@playwright/test": "1.64.1", "@types/bun": "1.4.4", "@types/node": "26.6.6", @@ -38,6 +41,7 @@ "dependencies": { "@fast-auth-near/browser-sdk": "1.4.2", "@fast-auth-near/javascript-provider": "1.4.1", + "@nearai/inference-sdk": "0.3.0", "@privy-io/react-auth": "3.51.3", "buffer": "6.0.3", "near-api-js-legacy": "npm:near-api-js@5.1.1", @@ -48,6 +52,8 @@ "packages": { "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.1", "", {}, "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ=="], + "@anthropic-ai/sdk": ["@anthropic-ai/sdk@1.3.0", "", { "dependencies": { "@opentelemetry/api": "^1.4.1", "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-k7z9BlLLPxfZH+ov7dS6EnaN/wiZeV8YNT1LZfrpAHIy7oY7pHr4UzirF9f2OlHtFEnRBOX+AZQ91Y5fK+TPTw=="], + "@auth0/auth0-auth-js": ["@auth0/auth0-auth-js@1.18.0", "", { "dependencies": { "jose": "^6.0.8", "openid-client": "^6.8.0" } }, "sha512-3O3fo2IdToP8x1ZlpQy9/hl37E7Xz1/+bFZR/nLwbmb+zXQT1UYFST1/YY0fqHnqHG2zxzJfBhZ/I0ACjKjY5g=="], "@auth0/auth0-spa-js": ["@auth0/auth0-spa-js@2.30.0", "", { "dependencies": { "@auth0/auth0-auth-js": "^1.17.0", "browser-tabs-lock": "^1.3.0", "dpop": "^2.1.1", "es-cookie": "~1.3.2" } }, "sha512-jqsVox2+TiBZf0Zh5h9iITh7W6a/WCGAMLuqniz+PTg2afVggbOBDmieo1zwOp8zQoY3RPguN4l5mvLDmxu7EQ=="], @@ -96,6 +102,8 @@ "@coinbase/wallet-sdk": ["@coinbase/wallet-sdk@4.3.2", "", { "dependencies": { "@noble/hashes": "^1.4.0", "clsx": "^1.2.1", "eventemitter3": "^5.0.1", "preact": "^10.24.2" } }, "sha512-hOLA2YONq8Z9n8f6oVP6N//FEEHOen7nq+adG/cReol6juFTHUelVN5GnA5zTIxiLFMDcrhDwwgCA6Tdb5jubw=="], + "@ecies/ciphers": ["@ecies/ciphers@0.2.6", "", { "peerDependencies": { "@noble/ciphers": "^1.0.0" } }, "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g=="], + "@emotion/is-prop-valid": ["@emotion/is-prop-valid@1.4.0", "", { "dependencies": { "@emotion/memoize": "^0.9.0" } }, "sha512-QgD4fyscGcbbKwJmqNvUMSE02OsHUa+lAWKdEUIJKgqe5IwRSKd7+KhibEWdaKwgjLj0DRSHA9biAIqGBk05lw=="], "@emotion/memoize": ["@emotion/memoize@0.9.0", "", {}, "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ=="], @@ -130,6 +138,12 @@ "@fontsource-variable/fraunces": ["@fontsource-variable/fraunces@5.3.0", "", {}, "sha512-9BYGySn4AHEJdgp9Z28tQ3X+laJMEOITXkQarZXeloWQZDq5oOvXJ3kDA8c7MGIfpogIaZfjrQBqmda8POOCKA=="], + "@freedomofpress/crypto-browser": ["@freedomofpress/crypto-browser@0.1.8", "", { "dependencies": { "@noble/curves": "^1.6.0" } }, "sha512-jvD36HxllT2UCPYzcs4R2UxA8r6dI+4Y62Gm+eVAnC4S3yCrzy2E0Ag1O48FhmMmVo3ZjwchcU8vAJzUSKHzEQ=="], + + "@freedomofpress/sigstore-browser": ["@freedomofpress/sigstore-browser@0.1.15", "", { "dependencies": { "@freedomofpress/crypto-browser": "^0.1.8", "@freedomofpress/tuf-browser": "^0.1.11", "@noble/curves": "^2.0.1" } }, "sha512-INccYE/yJyOc7SUYrQXP69y82w/2u51ZcG3x0RlfjD9qyEl8lUGBmWYAg0WPtv7r4NHf9lSxeDWOZ+Ibo0WaeQ=="], + + "@freedomofpress/tuf-browser": ["@freedomofpress/tuf-browser@0.1.11", "", { "dependencies": { "@freedomofpress/crypto-browser": "^0.1.7" } }, "sha512-d76ohB/AS5+zI+lnbiFMX/BIK3nT18hZ8q3Na6X4vyYaSYjXkeknzhAnbx1da+8ObWLwsaZLue46haEch28qtQ=="], + "@gemini-wallet/core": ["@gemini-wallet/core@0.3.2", "", { "dependencies": { "@metamask/rpc-errors": "7.0.2", "eventemitter3": "5.0.1" }, "peerDependencies": { "viem": ">=2.0.0" } }, "sha512-Z4aHi3ECFf5oWYWM3F1rW83GJfB9OvhBYPTmb5q+VyK3uvzvS48lwo+jwh2eOoCRWEuT/crpb9Vwp2QaS5JqgQ=="], "@hcaptcha/loader": ["@hcaptcha/loader@2.4.2", "", {}, "sha512-+Pf0Vin6iJlJj5u/mq6XMgbJT1mi/Sg5LWHxxqO4YHt2YvdZgecp5V2sbC6vRaNPJUqQGk2HOu1K/i12mqs5vw=="], @@ -232,18 +246,30 @@ "@near-js/wallet-account": ["@near-js/wallet-account@1.3.3", "", { "dependencies": { "@near-js/accounts": "1.4.1", "@near-js/crypto": "1.4.2", "@near-js/keystores": "0.2.2", "@near-js/providers": "1.0.3", "@near-js/signers": "0.2.2", "@near-js/transactions": "1.3.3", "@near-js/types": "0.3.1", "@near-js/utils": "1.1.0", "borsh": "1.0.0" } }, "sha512-GDzg/Kz0GBYF7tQfyQQQZ3vviwV8yD+8F2lYDzsWJiqIln7R1ov0zaXN4Tii86TeS21KPn2hHAsVu3Y4txa8OQ=="], - "@noble/ciphers": ["@noble/ciphers@2.2.0", "", {}, "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA=="], + "@nearai/inference-sdk": ["@nearai/inference-sdk@0.3.0", "", { "dependencies": { "@anthropic-ai/sdk": "1.3.0", "@freedomofpress/sigstore-browser": "0.1.15", "@noble/ciphers": "1.3.0", "@noble/hashes": "1.8.0", "@phala/dcap-qvl": "0.7.0", "buffer": "^6.0.3", "ed2curve": "0.3.0", "ethers": "^6.17.0", "hpke": "1.1.7", "jose": "6.2.13", "ohttp-ts": "0.6.1", "openai": "7.45.1", "tweetnacl": "^1.0.3", "valibot": "1.5.0", "yaml": "2.9.1" } }, "sha512-OzgOMPe50p9BZc9cJqI8YuHq0J+i5SQQM/Po4ZKhKnAOj6ThJ44fip6FcxNuZxV6eBSejI5spjSE0xOFa9YVrg=="], - "@noble/curves": ["@noble/curves@2.2.0", "", { "dependencies": { "@noble/hashes": "2.2.0" } }, "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ=="], + "@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - "@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], + "@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], + + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "@noble/post-quantum": ["@noble/post-quantum@0.6.1", "", { "dependencies": { "@noble/ciphers": "~2.2.0", "@noble/curves": "~2.2.0", "@noble/hashes": "~2.2.0" } }, "sha512-+pormrDZwjRw05U8ADK4JpHejo87+gBd+muRBB/ozztH5yhDLMDF4jHQWN3NQQAsu1zBNPWTG0ZwVI0CR29H0A=="], + "@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="], + "@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="], "@paulmillr/qr": ["@paulmillr/qr@0.2.1", "", {}, "sha512-IHnV6A+zxU7XwmKFinmYjUcwlyK9+xkG3/s9KcQhI9BjQKycrJ1JRO+FbNYPwZiPKW3je/DR0k7w8/gLa5eaxQ=="], + "@peculiar/asn1-schema": ["@peculiar/asn1-schema@2.11.1", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g=="], + + "@peculiar/asn1-x509": ["@peculiar/asn1-x509@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA=="], + + "@peculiar/utils": ["@peculiar/utils@2.0.3", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="], + + "@phala/dcap-qvl": ["@phala/dcap-qvl@0.7.0", "", { "dependencies": { "@peculiar/asn1-schema": "^2.3.13", "@peculiar/asn1-x509": "^2.3.13", "asn1.js": "^5.4.1", "bn.js": "^5.2.2", "buffer": "^6.0.3", "elliptic": "^6.6.1", "hash.js": "^1.1.7", "node-fetch": "^2.7.0" }, "bin": { "test_case": "test_case.js" } }, "sha512-b69KL2nrxGEBB1HhVCtl+vUbjMVEqKxuGzXAOuDrVZM7pi6+PeFfDmiIqqN3pnQkgcvkzZ1IKWOnFrbrXQCK+A=="], + "@phosphor-icons/webcomponents": ["@phosphor-icons/webcomponents@2.1.5", "", { "dependencies": { "lit": "^3" } }, "sha512-JcvQkZxvcX2jK+QCclm8+e8HXqtdFW9xV4/kk2aL9Y3dJA2oQVt+pzbv1orkumz3rfx4K9mn9fDoMr1He1yr7Q=="], "@playwright/test": ["@playwright/test@1.64.1", "", { "dependencies": { "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg=="], @@ -612,6 +638,8 @@ "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + "aes-js": ["aes-js@4.0.0-beta.5", "", {}, "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q=="], + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], "anser": ["anser@1.4.10", "", {}, "sha512-hCv9AqTQ8ycjpSd3upOJd7vFwW1JaoYQ7tpham03GJ1ca8/65rqn0RpaWpItOAd6ylW9wAw6luXYPJIyPFVOww=="], @@ -626,6 +654,10 @@ "asap": ["asap@2.0.6", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="], + "asn1.js": ["asn1.js@5.4.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "safer-buffer": "^2.1.0" } }, "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA=="], + + "asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="], + "async-mutex": ["async-mutex@0.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-Hs4R+4SPgamu6rSGW8C7cV9gaWUKEHykfzCCvIRuaVv636Ju10ZdeUbvb4TBEW0INuq2DHZqXbK4Nd3yG4RaRw=="], "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], @@ -646,6 +678,8 @@ "baseline-browser-mapping": ["baseline-browser-mapping@2.11.35", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ=="], + "bhttp-ts": ["bhttp-ts@0.6.1", "", { "dependencies": { "quicvarint": "^0.2.1" } }, "sha512-8WQNLhUbA9ywMNn/fOPRv+o3kxU+BZHKA1MNGYkm9/MWYQfbCMfS/pjosF3G5T1BcVnwUHhyZdZCYVein7in1A=="], + "big.js": ["big.js@6.2.2", "", {}, "sha512-y/ie+Faknx7sZA5MfGA2xKlu0GDv8RWrXGsmlteyJQ2lvoKv9GBK/fpRMc2qlSoBAgNxrixICFCBefIq8WCQpQ=="], "bip39": ["bip39@3.0.2", "", { "dependencies": { "@types/node": "11.11.6", "create-hash": "^1.1.0", "pbkdf2": "^3.0.9", "randombytes": "^2.0.1" } }, "sha512-J4E1r2N0tUylTKt07ibXvhpT2c5pyAFgvuA5q1H9uDy6dEGpjV8jmymh3MTYJDLCNbIVClSB9FbND49I6N24MQ=="], @@ -790,6 +824,8 @@ "eciesjs": ["eciesjs@0.4.18", "", { "dependencies": { "@ecies/ciphers": "^0.2.5", "@noble/ciphers": "^1.3.0", "@noble/curves": "^1.9.7", "@noble/hashes": "^1.8.0" } }, "sha512-wG99Zcfcys9fZux7Cft8BAX/YrOJLJSZ3jyYPfhZHqN2E+Ffx+QXBDsv3gubEgPtV6dTzJMSQUwk1H98/t/0wQ=="], + "ed2curve": ["ed2curve@0.3.0", "", { "dependencies": { "tweetnacl": "1.x.x" } }, "sha512-8w2fmmq3hv9rCrcI7g9hms2pMunQr1JINfcjwR9tAyZqhtyaMN991lF/ZfHfr5tzZQ8c7y7aBgZbjfbd0fjFwQ=="], + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], "electron-to-chromium": ["electron-to-chromium@1.5.477", "", {}, "sha512-PN++F4zWZoVDGWinxMnSCpVqKhqFOJfLXxdU8bYJKudAEsHL/XKVITOKWVbfMt1r276Mi9RDLU9VHx9uKJ4RMQ=="], @@ -838,6 +874,8 @@ "ethereum-cryptography": ["ethereum-cryptography@2.2.1", "", { "dependencies": { "@noble/curves": "1.4.2", "@noble/hashes": "1.4.0", "@scure/bip32": "1.4.0", "@scure/bip39": "1.3.0" } }, "sha512-r/W8lkHSiTLxUxW8Rf3u4HGB0xQweG2RyETjywylKZSzLWoWAijRz8WCuOtJ6wah+avllXBqZuk29HCCvhEIRg=="], + "ethers": ["ethers@6.17.0", "", { "dependencies": { "@adraffy/ens-normalize": "1.11.1", "@noble/curves": "1.2.0", "@noble/hashes": "1.3.2", "@types/node": "22.7.5", "aes-js": "4.0.0-beta.5", "tslib": "2.7.0", "ws": "8.21.0" } }, "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang=="], + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], "eventemitter2": ["eventemitter2@6.4.9", "", {}, "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg=="], @@ -936,6 +974,8 @@ "hono": ["hono@4.13.16", "", {}, "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A=="], + "hpke": ["hpke@1.1.7", "", {}, "sha512-wQGOBpFBFlP2h7euuLuey8yJGUtJ+c8D/ohPxtTQqpICItFtHDpbXk2B29xfUpIFPn0miS9TJVObFGAeEZzDJA=="], + "http-errors": ["http-errors@1.7.2", "", { "dependencies": { "depd": "~1.1.2", "inherits": "2.0.3", "setprototypeof": "1.1.1", "statuses": ">= 1.5.0 < 2", "toidentifier": "1.0.0" } }, "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg=="], "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], @@ -1008,6 +1048,8 @@ "json-rpc-random-id": ["json-rpc-random-id@1.0.1", "", {}, "sha512-RJ9YYNCkhVDBuP4zN5BBtYAzEl03yq/jIIsyif0JY9qyJuQQZNeDK7anAPKKlyEtLSj2s8h6hNh2F8zO5q7ScA=="], + "json-schema-to-ts": ["json-schema-to-ts@3.1.1", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="], + "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], "jsonpointer": ["jsonpointer@5.0.1", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="], @@ -1168,6 +1210,8 @@ "ofetch": ["ofetch@1.5.1", "", { "dependencies": { "destr": "^2.0.5", "node-fetch-native": "^1.6.7", "ufo": "^1.6.1" } }, "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA=="], + "ohttp-ts": ["ohttp-ts@0.6.1", "", { "dependencies": { "bhttp-ts": "0.6.1", "quicvarint": "0.2.1" }, "peerDependencies": { "hpke": "^1" } }, "sha512-amrwcueJWKMWV2nHLLZM3S4Z88z2pB0RzEqoml0XoI5arFGNHtoxMRDLsrpNbym4xIA06jE5qJMFmLsxIoambA=="], + "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], "on-finished": ["on-finished@2.3.0", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww=="], @@ -1176,6 +1220,8 @@ "open": ["open@8.4.2", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="], + "openai": ["openai@7.45.1", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "google-auth-library": ">=9.15.1 <12", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4", "google-auth-library", "undici", "ws", "zod"] }, "sha512-mutrJXwhJIMZ24Lab2COFtNp44OcpZSnV4O2O7q38wAHUa2m2fQqUO5pj1XS3PqLfOTeODBUS9YoadqDnnGk5A=="], + "openapi-fetch": ["openapi-fetch@0.13.8", "", { "dependencies": { "openapi-typescript-helpers": "^0.0.15" } }, "sha512-yJ4QKRyNxE44baQ9mY5+r/kAzZ8yXMemtNAOFwOzRXJscdjSxxzWSNlyBAr+o5JjkUw9Lc3W7OIoca0cY3PYnQ=="], "openapi-typescript-helpers": ["openapi-typescript-helpers@0.0.15", "", {}, "sha512-opyTPaunsklCBpTK8JGef6mfPhLSnyy5a0IN9vKtx3+4aExf+KxEqYwIy3hqkedXIB97u357uLMJsOnm3GVjsw=="], @@ -1250,6 +1296,10 @@ "punycode": ["punycode@1.4.1", "", {}, "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ=="], + "pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="], + + "pvutils": ["pvutils@1.2.0", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="], + "qrcode": ["qrcode@1.5.3", "", { "dependencies": { "dijkstrajs": "^1.0.1", "encode-utf8": "^1.0.3", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-puyri6ApkEHYiVl4CFzo1tDkAZ+ATcnbJrJ6RiBM1Fhctdn/ix9MTE3hRph33omisEbC/2fcfemsseiKgBPKZg=="], "qs": ["qs@6.17.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA=="], @@ -1258,6 +1308,8 @@ "quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="], + "quicvarint": ["quicvarint@0.2.1", "", {}, "sha512-h45spZya+YkPl9qyrMnV4hjd3HvrlUTqxBwqdWN/Nr+MwXjb91B7tHHd1lFy/upSm4KiApLRSc6HnsmZNjdR+w=="], + "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], "randombytes": ["randombytes@2.1.0", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="], @@ -1308,6 +1360,8 @@ "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], "secp256k1": ["secp256k1@5.0.1", "", { "dependencies": { "elliptic": "^6.5.7", "node-addon-api": "^5.0.0", "node-gyp-build": "^4.2.0" }, "hasInstallScript": true }, "sha512-lDFs9AAIaWP9UCdtWrotXWWF9t8PWgQDcxqgAnpM9rMqxb3Oaq2J0thzPVSxBwdJgyQtkU/sYtFtbM1RSt/iYA=="], @@ -1414,7 +1468,9 @@ "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], - "tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + "ts-algebra": ["ts-algebra@2.0.0", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="], + + "tslib": ["tslib@2.7.0", "", {}, "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="], "tweetnacl": ["tweetnacl@1.0.3", "", {}, "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="], @@ -1454,6 +1510,8 @@ "uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + "valibot": ["valibot@1.5.0", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ=="], + "valtio": ["valtio@2.1.7", "", { "dependencies": { "proxy-compare": "^3.0.1" }, "peerDependencies": { "@types/react": ">=18.0.0", "react": ">=18.0.0" }, "optionalPeers": ["@types/react", "react"] }, "sha512-DwJhCDpujuQuKdJ2H84VbTjEJJteaSmqsuUltsfbfdbotVfNeTE4K/qc/Wi57I9x8/2ed4JNdjEna7O6PfavRg=="], "viem": ["viem@2.57.8", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.14.56", "ws": "8.21.0" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-WYxDGltqjnHxM7sMZ/IBYpesbrEDDhLcmsbUE5zIPjVYOtP8gztcOhiL7OHZHJbI6vfuWNW4NCR5Gdddw+/Ovw=="], @@ -1494,6 +1552,8 @@ "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + "yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="], "yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="], @@ -1532,6 +1592,8 @@ "@fast-auth-near/javascript-provider/near-api-js": ["near-api-js@5.1.1", "", { "dependencies": { "@near-js/accounts": "1.4.1", "@near-js/crypto": "1.4.2", "@near-js/keystores": "0.2.2", "@near-js/keystores-browser": "0.2.2", "@near-js/keystores-node": "0.1.2", "@near-js/providers": "1.0.3", "@near-js/signers": "0.2.2", "@near-js/transactions": "1.3.3", "@near-js/types": "0.3.1", "@near-js/utils": "1.1.0", "@near-js/wallet-account": "1.3.3", "@noble/curves": "1.8.1", "borsh": "1.0.0", "depd": "2.0.0", "http-errors": "1.7.2", "near-abi": "0.2.0", "node-fetch": "2.6.7" } }, "sha512-h23BGSKxNv8ph+zU6snicstsVK1/CTXsQz4LuGGwoRE24Hj424nSe4+/1tzoiC285Ljf60kPAqRCmsfv9etF2g=="], + "@freedomofpress/sigstore-browser/@noble/curves": ["@noble/curves@2.2.0", "", { "dependencies": { "@noble/hashes": "2.2.0" } }, "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ=="], + "@gemini-wallet/core/eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], "@jest/types/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], @@ -1620,16 +1682,30 @@ "@near-js/wallet-account/borsh": ["borsh@1.0.0", "", {}, "sha512-fSVWzzemnyfF89EPwlUNsrS5swF5CrtiN4e+h0/lLf4dz2he4L3ndM20PS9wj7ICSkXJe/TQUHdaPTq15b1mNQ=="], + "@nearai/inference-sdk/jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="], + + "@noble/post-quantum/@noble/ciphers": ["@noble/ciphers@2.2.0", "", {}, "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA=="], + + "@noble/post-quantum/@noble/curves": ["@noble/curves@2.2.0", "", { "dependencies": { "@noble/hashes": "2.2.0" } }, "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ=="], + + "@noble/post-quantum/@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], + + "@peculiar/asn1-schema/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "@peculiar/asn1-x509/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "@peculiar/utils/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "@phala/dcap-qvl/bn.js": ["bn.js@5.2.5", "", {}, "sha512-Vq886eXykuP5E6HcKSSStP3bJgrE6In5WKxVUvJ8XGpWWYs2xZHWqUwzCtGgEtBcxyd57KBFDPFoUfNzdaHCNg=="], + + "@phala/dcap-qvl/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], + "@privy-io/encoding/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@privy-io/js-sdk-core/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@privy-io/js-sdk-core/jose": ["jose@4.15.9", "", {}, "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA=="], - "@privy-io/node/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@privy-io/node/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@privy-io/node/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@privy-io/react-auth/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], @@ -1658,14 +1734,8 @@ "@reown/appkit-wallet/zod": ["zod@3.22.4", "", {}, "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg=="], - "@scure/bip32/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@scure/bip32/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@scure/bip32/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], - "@scure/bip39/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@scure/bip39/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@solana/errors/commander": ["commander@14.0.2", "", {}, "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ=="], @@ -1738,17 +1808,21 @@ "@wagmi/core/zustand": ["zustand@5.0.0", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-LE+VcmbartOPM+auOjCCLQOsQ05zUTp8RkgwRzefUk+2jISdMMFnxvyTjA4YNWr5ZGXYbVsEMZosttuxUBkojQ=="], + "@walletconnect/environment/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + + "@walletconnect/events/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + + "@walletconnect/jsonrpc-utils/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + "@walletconnect/jsonrpc-ws-connection/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], "@walletconnect/relay-auth/@noble/curves": ["@noble/curves@1.8.0", "", { "dependencies": { "@noble/hashes": "1.7.0" } }, "sha512-j84kjAbzEnQHaSIhRPUmB3/eVXu2k3dKPl2LOrR8fSOIL+89U+7lV117EWHtq/GHM3ReGHM46iRBdZfpc4HRUQ=="], "@walletconnect/relay-auth/@noble/hashes": ["@noble/hashes@1.7.0", "", {}, "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w=="], - "@walletconnect/utils/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], + "@walletconnect/safe-json/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], - "@walletconnect/utils/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@walletconnect/utils/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], + "@walletconnect/time/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], "@walletconnect/utils/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], @@ -1756,10 +1830,16 @@ "@walletconnect/utils/ox": ["ox@0.9.3", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.0.9", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg=="], + "@walletconnect/window-getters/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + + "@walletconnect/window-metadata/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], "aria-hidden/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "asn1js/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "async-mutex/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], "axios/https-proxy-agent": ["https-proxy-agent@5.0.1", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="], @@ -1778,14 +1858,6 @@ "duplexify/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], - "eciesjs/@ecies/ciphers": ["@ecies/ciphers@0.2.6", "", { "peerDependencies": { "@noble/ciphers": "^1.0.0" } }, "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g=="], - - "eciesjs/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - - "eciesjs/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "eciesjs/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "eth-block-tracker/@metamask/utils": ["@metamask/utils@5.0.2", "", { "dependencies": { "@ethereumjs/tx": "^4.1.2", "@types/debug": "^4.1.7", "debug": "^4.3.4", "semver": "^7.3.8", "superstruct": "^1.0.3" } }, "sha512-yfmE79bRQtnMzarnKfX7AEJBwFTxvTyw3nBQlu/5rmGXrjAeAMltoGxO62TFurxrQAFMNa/fEjIHNvungZp0+g=="], "eth-json-rpc-filters/pify": ["pify@5.0.0", "", {}, "sha512-eW/gHNMlxdSP6dmG6uJip6FXN0EQBwm2clYYd8Wul42Cwu/DK8HEftzsapcNdYe2MfLiIwZqsDk2RDEsTE79hA=="], @@ -1798,6 +1870,12 @@ "ethereum-cryptography/@scure/bip39": ["@scure/bip39@1.3.0", "", { "dependencies": { "@noble/hashes": "~1.4.0", "@scure/base": "~1.1.6" } }, "sha512-disdg7gHuTDZtY+ZdkmLpPCk7fxZSu3gBiEGuoC1XYxv9cGx3Z6cpTggCgW6odSOOIXCiDjuGejW+aJKCY/pIQ=="], + "ethers/@noble/curves": ["@noble/curves@1.2.0", "", { "dependencies": { "@noble/hashes": "1.3.2" } }, "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw=="], + + "ethers/@noble/hashes": ["@noble/hashes@1.3.2", "", {}, "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ=="], + + "ethers/@types/node": ["@types/node@22.7.5", "", { "dependencies": { "undici-types": "~6.19.2" } }, "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ=="], + "finalhandler/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "finalhandler/encodeurl": ["encodeurl@1.0.2", "", {}, "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w=="], @@ -1838,6 +1916,10 @@ "metro-symbolicate/source-map": ["source-map@0.5.7", "", {}, "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ=="], + "near-api-js/@noble/curves": ["@noble/curves@2.2.0", "", { "dependencies": { "@noble/hashes": "2.2.0" } }, "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ=="], + + "near-api-js/@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], + "near-api-js-legacy/@near-js/accounts": ["@near-js/accounts@1.4.1", "", { "dependencies": { "@near-js/crypto": "1.4.2", "@near-js/providers": "1.0.3", "@near-js/signers": "0.2.2", "@near-js/transactions": "1.3.3", "@near-js/types": "0.3.1", "@near-js/utils": "1.1.0", "@noble/hashes": "1.7.1", "borsh": "1.0.0", "depd": "2.0.0", "is-my-json-valid": "^2.20.6", "lru_map": "0.4.1", "near-abi": "0.2.0" } }, "sha512-ni3QT9H3NdrbVVKyx56yvz93r89Dvpc/vgVtiIK2OdXjkK6jcj+UKMDRQ6F7rd9qJOInLkHZbVBtcR6j1CXLjw=="], "near-api-js-legacy/@near-js/transactions": ["@near-js/transactions@1.3.3", "", { "dependencies": { "@near-js/crypto": "1.4.2", "@near-js/signers": "0.2.2", "@near-js/types": "0.3.1", "@near-js/utils": "1.1.0", "@noble/hashes": "1.7.1", "borsh": "1.0.0" } }, "sha512-1AXD+HuxlxYQmRTLQlkVmH+RAmV3HwkAT8dyZDu+I2fK/Ec9BQHXakOJUnOBws3ihF+akQhamIBS5T0EXX/Ylw=="], @@ -1848,12 +1930,8 @@ "obj-multiplex/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], - "ox/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - "ox/@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], - "ox/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "ox/eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], "pino/pino-abstract-transport": ["pino-abstract-transport@2.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw=="], @@ -1864,6 +1942,8 @@ "porto/zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + "pvtsutils/tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "react-aria/clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], @@ -1884,8 +1964,6 @@ "viem/@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], - "viem/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "wagmi/use-sync-external-store": ["use-sync-external-store@1.4.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-9WXSPC5fMv61vaupRkCKCxsPxBocVnwakBEkMIHHpkTTg6icbJtg6jzgtLDm4bl3cSHAca52rYWih0k4K3PfHw=="], "wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], @@ -1964,6 +2042,8 @@ "@fast-auth-near/javascript-provider/near-api-js/borsh": ["borsh@1.0.0", "", {}, "sha512-fSVWzzemnyfF89EPwlUNsrS5swF5CrtiN4e+h0/lLf4dz2he4L3ndM20PS9wj7ICSkXJe/TQUHdaPTq15b1mNQ=="], + "@freedomofpress/sigstore-browser/@noble/curves/@noble/hashes": ["@noble/hashes@2.2.0", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="], + "@jest/types/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "@jest/types/chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], @@ -2268,6 +2348,8 @@ "ethereum-cryptography/@scure/bip39/@scure/base": ["@scure/base@1.1.9", "", {}, "sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg=="], + "ethers/@types/node/undici-types": ["undici-types@6.19.8", "", {}, "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="], + "finalhandler/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "form-data/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], @@ -2310,12 +2392,8 @@ "obj-multiplex/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], - "porto/ox/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - "porto/ox/@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], - "porto/ox/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "porto/ox/eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], "react-native/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], @@ -2486,12 +2564,6 @@ "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/sign-client/@walletconnect/core": ["@walletconnect/core@2.21.9", "", { "dependencies": { "@walletconnect/heartbeat": "1.2.2", "@walletconnect/jsonrpc-provider": "1.0.14", "@walletconnect/jsonrpc-types": "1.0.4", "@walletconnect/jsonrpc-utils": "1.0.8", "@walletconnect/jsonrpc-ws-connection": "1.0.16", "@walletconnect/keyvaluestorage": "1.1.1", "@walletconnect/logger": "2.1.2", "@walletconnect/relay-api": "1.0.11", "@walletconnect/relay-auth": "1.1.0", "@walletconnect/safe-json": "1.0.2", "@walletconnect/time": "1.0.2", "@walletconnect/types": "2.21.9", "@walletconnect/utils": "2.21.9", "@walletconnect/window-getters": "1.0.1", "es-toolkit": "1.39.3", "events": "3.3.0", "uint8arrays": "3.1.1" } }, "sha512-SlSknLvbO4i9Y4y8zU0zeCuJv1klQIUX3HRSBs1BaYvQKVVkrdiWPgRj4jcrL2wEOINa9NXw6HXp6x5XCXOolA=="], - "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/utils/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - - "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/utils/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/utils/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/utils/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@reown/appkit-controllers/@walletconnect/universal-provider/@walletconnect/utils/bs58": ["bs58@6.0.0", "", { "dependencies": { "base-x": "^5.0.0" } }, "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw=="], @@ -2514,12 +2586,6 @@ "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/sign-client/@walletconnect/core": ["@walletconnect/core@2.21.9", "", { "dependencies": { "@walletconnect/heartbeat": "1.2.2", "@walletconnect/jsonrpc-provider": "1.0.14", "@walletconnect/jsonrpc-types": "1.0.4", "@walletconnect/jsonrpc-utils": "1.0.8", "@walletconnect/jsonrpc-ws-connection": "1.0.16", "@walletconnect/keyvaluestorage": "1.1.1", "@walletconnect/logger": "2.1.2", "@walletconnect/relay-api": "1.0.11", "@walletconnect/relay-auth": "1.1.0", "@walletconnect/safe-json": "1.0.2", "@walletconnect/time": "1.0.2", "@walletconnect/types": "2.21.9", "@walletconnect/utils": "2.21.9", "@walletconnect/window-getters": "1.0.1", "es-toolkit": "1.39.3", "events": "3.3.0", "uint8arrays": "3.1.1" } }, "sha512-SlSknLvbO4i9Y4y8zU0zeCuJv1klQIUX3HRSBs1BaYvQKVVkrdiWPgRj4jcrL2wEOINa9NXw6HXp6x5XCXOolA=="], - "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/utils/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - - "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/utils/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/utils/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/utils/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@reown/appkit-utils/@walletconnect/universal-provider/@walletconnect/utils/bs58": ["bs58@6.0.0", "", { "dependencies": { "base-x": "^5.0.0" } }, "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw=="], @@ -2544,12 +2610,6 @@ "@reown/appkit/@walletconnect/universal-provider/@walletconnect/sign-client/@walletconnect/core": ["@walletconnect/core@2.21.9", "", { "dependencies": { "@walletconnect/heartbeat": "1.2.2", "@walletconnect/jsonrpc-provider": "1.0.14", "@walletconnect/jsonrpc-types": "1.0.4", "@walletconnect/jsonrpc-utils": "1.0.8", "@walletconnect/jsonrpc-ws-connection": "1.0.16", "@walletconnect/keyvaluestorage": "1.1.1", "@walletconnect/logger": "2.1.2", "@walletconnect/relay-api": "1.0.11", "@walletconnect/relay-auth": "1.1.0", "@walletconnect/safe-json": "1.0.2", "@walletconnect/time": "1.0.2", "@walletconnect/types": "2.21.9", "@walletconnect/utils": "2.21.9", "@walletconnect/window-getters": "1.0.1", "es-toolkit": "1.39.3", "events": "3.3.0", "uint8arrays": "3.1.1" } }, "sha512-SlSknLvbO4i9Y4y8zU0zeCuJv1klQIUX3HRSBs1BaYvQKVVkrdiWPgRj4jcrL2wEOINa9NXw6HXp6x5XCXOolA=="], - "@reown/appkit/@walletconnect/universal-provider/@walletconnect/utils/@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - - "@reown/appkit/@walletconnect/universal-provider/@walletconnect/utils/@noble/curves": ["@noble/curves@1.9.7", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="], - - "@reown/appkit/@walletconnect/universal-provider/@walletconnect/utils/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@reown/appkit/@walletconnect/universal-provider/@walletconnect/utils/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], "@reown/appkit/@walletconnect/universal-provider/@walletconnect/utils/viem": ["viem@2.36.0", "", { "dependencies": { "@noble/curves": "1.9.6", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.9.1", "ws": "8.18.3" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-Xz7AkGtR43K+NY74X2lBevwfRrsXuifGUzt8QiULO47NXIcT7g3jcA4nIvl5m2OTE5v8SlzishwXmg64xOIVmQ=="], diff --git a/package.json b/package.json index 9c4d8f8..668c8bd 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,9 @@ "react-dom": "19.3.1" }, "devDependencies": { + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", "@playwright/test": "1.64.1", "@types/bun": "1.4.4", "@types/node": "26.6.6", diff --git a/web/package.json b/web/package.json index 6683eea..a9cfe23 100644 --- a/web/package.json +++ b/web/package.json @@ -12,6 +12,7 @@ "dependencies": { "@fast-auth-near/browser-sdk": "1.4.2", "@fast-auth-near/javascript-provider": "1.4.1", + "@nearai/inference-sdk": "0.3.0", "@privy-io/react-auth": "3.51.3", "buffer": "6.0.3", "near-api-js-legacy": "npm:near-api-js@5.1.1", diff --git a/web/src/note/note.test.ts b/web/src/note/note.test.ts new file mode 100644 index 0000000..5d95a9e --- /dev/null +++ b/web/src/note/note.test.ts @@ -0,0 +1,143 @@ +import {expect,test} from "bun:test"; +import {ed25519,edwardsToMontgomeryPriv,edwardsToMontgomeryPub,x25519} from "@noble/curves/ed25519"; +import {hkdf} from "@noble/hashes/hkdf"; +import {sha256} from "@noble/hashes/sha256"; +import {xchacha20poly1305} from "@noble/ciphers/chacha"; +import * as sdk from "@nearai/inference-sdk"; +import {decideSeal,NOTE_MODEL,sha256Hex} from "./seal"; +import {HARBOR_NAME,NOTE_INSTRUCTIONS,noteFacts,noteMessages} from "./prompt"; +import {readNote,writeSealedNote} from "./write"; +import type {ReturnRecord} from "../expedition/return-record"; + +const hex=(b:Uint8Array)=>Buffer.from(b).toString("hex"),unhex=(s:string)=>new Uint8Array(Buffer.from(s,"hex")); +const utf8=(s:string)=>new TextEncoder().encode(s); +const concat=(...parts:Uint8Array[])=>{const out=new Uint8Array(parts.reduce((n,p)=>n+p.length,0));let i=0;for(const p of parts){out.set(p,i);i+=p.length;}return out;}; +const kdf=(shared:Uint8Array)=>hkdf(sha256,shared,undefined,utf8("ed25519_encryption"),32); +const requestAad=(replyEd25519:Uint8Array,field:string)=>concat(utf8("nearai-e2ee-request-v3"),new Uint8Array([2]),replyEd25519,new Uint8Array([0]),utf8(field)); +function open(envelope:string,modelSeed:Uint8Array,aad:Uint8Array) { + const bytes=unhex(envelope),shared=x25519.getSharedSecret(edwardsToMontgomeryPriv(modelSeed),bytes.slice(0,32)); + return new TextDecoder().decode(xchacha20poly1305(kdf(shared),bytes.slice(32,56),aad).decrypt(bytes.slice(56))); +} +function sealTo(plaintext:string,recipientEd25519:Uint8Array,aad=new Uint8Array(),ephemeral=x25519.utils.randomPrivateKey(),nonce=crypto.getRandomValues(new Uint8Array(24))) { + const shared=x25519.getSharedSecret(ephemeral,edwardsToMontgomeryPub(recipientEd25519)); + return hex(concat(x25519.getPublicKey(ephemeral),nonce,xchacha20poly1305(kdf(shared),nonce,aad).encrypt(utf8(plaintext)))); +} + +// Public Ed25519 vector from nearai/inference-proxy tests/fixtures/e2ee-v3.json (commit 724cf65, 2026-11-13). +const vector={ + model_secret:"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",model_public:"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + reply_public:"66be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a",ephemeral_secret:"0303030303030303030303030303030303030303030303030303030303030303", + nonce:"000102030405060708090a0b0c0d0e0f1011121314151617", + aad:"6e65617261692d653265652d726571756573742d76330266be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a006d657373616765735b5d2e636f6e74656e74", + plaintext:"E2EE v3: private prompt", + ciphertext:"5dfedd3b6bd47f6fa28ee15d969d5bb0ea53774d488bdaf9df1c6e0124b3ef22000102030405060708090a0b0c0d0e0f1011121314151617952f1029d9facf0669005cd32fc9f3682f65e17b55d57abc02aeccf35eaabf4b8efe9979121175", +}; +test("the test TEE reproduces NEAR AI's official E2EE v3 Ed25519 vector",()=>{ + expect(hex(ed25519.getPublicKey(unhex(vector.model_secret)))).toBe(vector.model_public); + const aad=requestAad(unhex(vector.reply_public),"messages[].content"); + expect(hex(aad)).toBe(vector.aad); + expect(open(vector.ciphertext,unhex(vector.model_secret),aad)).toBe(vector.plaintext); + expect(sealTo(vector.plaintext,unhex(vector.model_public),aad,unhex(vector.ephemeral_secret),unhex(vector.nonce))).toBe(vector.ciphertext); + expect(()=>open(vector.ciphertext,unhex(vector.model_secret),requestAad(unhex(vector.reply_public),"messages[].name"))).toThrow(); +}); + +const record=(patch:Partial):ReturnRecord=>({schemaVersion:1,id:"r",operationId:"return:r",contentVersion:"first_light_v1",context:{authority:"local-preview",banked:[],lit:false,signaled:false},area:"beacon",tool:"rope",banked:[],commands:[],outcome:"returned",cargo:["lens"],disposition:"accepted",acceptedClaimId:"a".repeat(64),...patch} as ReturnRecord); +test("the model sees only the fixed harbor name and accepted return facts",()=>{ + const facts=noteFacts([record({id:"staged",disposition:"staged",cargo:["moth"]}),record({area:"wind",tool:"lantern",cargo:["vane"]}),record({}),record({outcome:"rescued",cargo:[]})]); + expect(facts).toBe(`Harbor: ${HARBOR_NAME}.\nRecent accepted returns, newest first:\n- Beacon Court, carrying the rope. Bram brought me home safely.\n- Beacon Court, carrying the rope. I brought home the Beacon Lens.\n- Wind Gate, carrying the lantern. I brought home the Signal Vane.`); + expect(facts).not.toContain("wind-moth"); + expect(noteMessages([record({})]).map(m=>m.role)).toEqual(["system","user"]); + expect(NOTE_INSTRUCTIONS).toContain("she and her"); +}); + +function teeKeys(){const seed=ed25519.utils.randomPrivateKey();return {seed,publicKey:ed25519.getPublicKey(seed),hex:hex(ed25519.getPublicKey(seed))};} +/** A local stand-in for the model TEE: decrypts v3 request fields, encrypts the reply to the client and signs both hashes. */ +async function mockTee(model:ReturnType,requestBytes:Uint8Array,clientKeyHex:string,reply="The lens is home and the light is steady.",kind="provider_tee") { + const body=JSON.parse(new TextDecoder().decode(requestBytes));const client=unhex(clientKeyHex); + const plaintexts=body.messages.map((m:{content:string})=>open(m.content,model.seed,requestAad(client,"messages[].content"))); + const completion=utf8(JSON.stringify({id:"chatcmpl-local_1",object:"chat.completion",model:NOTE_MODEL,choices:[{index:0,message:{role:"assistant",content:sealTo(reply,client)},finish_reason:"stop"}]})); + const text=`${NOTE_MODEL}:${await sha256Hex(requestBytes)}:${await sha256Hex(completion)}`; + const signature=utf8(JSON.stringify({text,signature:hex(ed25519.sign(utf8(text),model.seed)),signing_address:model.hex,signing_algo:"ed25519",signature_kind:kind})); + return {plaintexts,completion,signature,text}; +} +test("SDK v3 encryption round-trips through a locally generated model key pair",async()=>{ + const model=teeKeys(),messages=noteMessages([record({})]); + const prepared=await sdk.prepareE2eeChatRequest({request:new Request("https://note.invalid/v1/chat/completions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:NOTE_MODEL,messages,stream:false,max_tokens:120})}),modelKey:{signingAlgo:"ed25519",publicKey:model.hex}}); + const headers=prepared.request.headers,bytes=new Uint8Array(await prepared.request.clone().arrayBuffer()); + expect(headers.get("x-encryption-version")).toBe("3");expect(headers.get("x-signing-algo")).toBe("ed25519");expect(headers.get("x-model-pub-key")).toBe(model.hex); + 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"]); + 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(); + expect(decrypted.choices[0].message.content).toBe("The lens is home and the light is steady."); + // A second preparation uses a different one-use reply key. + const again=await sdk.prepareE2eeChatRequest({request:new Request("https://note.invalid/v1/chat/completions",{method:"POST",body:JSON.stringify({model:NOTE_MODEL,messages})}),modelKey:{signingAlgo:"ed25519",publicKey:model.hex}}); + expect(again.request.headers.get("x-client-pub-key")).not.toBe(headers.get("x-client-pub-key")); +}); + +test("seal decision: sealed only for a provider_tee signature over the exact bytes by the attested key",async()=>{ + const model=teeKeys(),requestBytes=utf8('{"model":"z-ai/glm-5.3-flash"}'),client=hex(ed25519.getPublicKey(ed25519.utils.randomPrivateKey())); + const request=utf8(JSON.stringify({model:NOTE_MODEL,messages:[{role:"user",content:sealTo("hi",model.publicKey,requestAad(unhex(client),"messages[].content"))}]})); + const tee=await mockTee(model,request,client); + const decide=(signatureBytes:Uint8Array|null,patch:Partial[0]>={})=>decideSeal({modelId:NOTE_MODEL,requestBytes:request,responseBytes:tee.completion,signatureBytes,modelKey:model.hex,...patch}); + expect(await decide(tee.signature)).toEqual({state:"sealed"}); + const edit=(patch:Record)=>utf8(JSON.stringify({...JSON.parse(new TextDecoder().decode(tee.signature)),...patch})); + const original=JSON.parse(new TextDecoder().decode(tee.signature)).signature as string; + const flipped=(original[0]==="0"?"1":"0")+original.slice(1); + for(const [label,decision] of [ + ["tampered signature",await decide(edit({signature:flipped}))], + ["wrong signed text",await decide(edit({text:`${NOTE_MODEL}:${"0".repeat(64)}:${"0".repeat(64)}`}))], + ["gateway signature",await decide(edit({signature_kind:"gateway"}))], + ["legacy unlabeled signature",await decide(edit({signature_kind:undefined}))], + ["ecdsa signature",await decide(edit({signing_algo:"ecdsa"}))], + ["other signer",await decide(tee.signature,{modelKey:teeKeys().hex})], + ["changed request",await decide(tee.signature,{requestBytes:utf8(new TextDecoder().decode(request)+" ")})], + ["changed response",await decide(tee.signature,{responseBytes:utf8(new TextDecoder().decode(tee.completion)+" ")})], + ["no signature",await decide(null)],["unreadable signature",await decide(utf8("{"))], + ] as const)expect({label,state:decision.state}).toEqual({label,state:"plain"}); + const wrongText=await decide(edit({text:"z-ai/glm-5.3:aa:bb"}));expect(wrongText.state==="plain"&&wrongText.reason).toContain("signed text"); +}); + +/** Stubs only attestation fetch/verification; encryption, decryption and the seal decision are real. */ +function flow(options:{model:ReturnType;relay:(bytes:Uint8Array,headers:Headers)=>Promise;keys?:string[]}) { + const fake={ + ...sdk, + AttestationClient:class{fetchModelMetadata=async()=>({providerType:"vllm",attestationSupported:true});fetchModelAttestations=async()=>({attestations:(options.keys??[options.model.hex,options.model.hex]).map(()=>({})),clientBinding:{nonce:"0".repeat(64)}});}, + verifyModelAttestation:(()=>{let i=0;return async()=>{const k=(options.keys??[options.model.hex,options.model.hex])[i++]!;return {signer:{signingAlgo:"ed25519",signingAddress:k},signingPublicKey:k,tcbStatus:"UpToDate"};};})(), + } as unknown as typeof sdk; + const calls:{url:string;headers:Headers;bytes:Uint8Array}[]=[]; + const send=(async(url:string,init:RequestInit)=>{const bytes=new Uint8Array(init.body as Uint8Array),headers=new Headers(init.headers);calls.push({url,headers,bytes});return options.relay(bytes,headers);}) as typeof fetch; + return {calls,run:()=>writeSealedNote({returns:[record({})],token:"header.payload.signature",relayUrl:"/api",fetch:send,sdk:fake})}; +} +const envelope=(completion:Uint8Array,signature:Uint8Array|null)=>Response.json({completion:Buffer.from(completion).toString("base64"),signature:signature?Buffer.from(signature).toString("base64"):null}); +test("the browser flow returns sealed, plain and broken notes",async()=>{ + const model=teeKeys(); + const sealed=flow({model,relay:async(bytes,headers)=>{const tee=await mockTee(model,bytes,headers.get("x-client-pub-key")!);return envelope(tee.completion,tee.signature);}}); + const note=await sealed.run(); + expect(note).toMatchObject({state:"sealed",text:"The lens is home and the light is steady.",back:{model:NOTE_MODEL,modelKey:model.hex,instances:2,chatId:"chatcmpl-local_1"}}); + const [call]=sealed.calls;expect(call!.url).toBe("/api/v1/privy/note");expect(call!.headers.get("authorization")).toBe("Bearer header.payload.signature"); + expect(call!.headers.get("x-model-pub-key")).toBe(model.hex);expect(new TextDecoder().decode(call!.bytes)).not.toContain("Pocket Harbor"); + + const tampered=flow({model,relay:async(bytes,headers)=>{const tee=await mockTee(model,bytes,headers.get("x-client-pub-key")!);return envelope(tee.completion,utf8(new TextDecoder().decode(tee.signature).replace(/"signature":"(.)/,(_,c)=>`"signature":"${c==="0"?"1":"0"}`)));}}); + expect(await tampered.run()).toMatchObject({state:"plain",text:"The lens is home and the light is steady.",back:{reason:"The signature does not verify against the attested model key."}}); + const gateway=flow({model,relay:async(bytes,headers)=>{const tee=await mockTee(model,bytes,headers.get("x-client-pub-key")!,undefined,"gateway");return envelope(tee.completion,tee.signature);}}); + expect((await gateway.run()).state).toBe("plain"); + const unsigned=flow({model,relay:async(bytes,headers)=>envelope((await mockTee(model,bytes,headers.get("x-client-pub-key")!)).completion,null)}); + 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."}}); + 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");}}); + expect((await split.run()).state).toBe("broken");expect(split.calls).toEqual([]); +}); + +test("stored notes are read only in their known shapes",()=>{ + const store=(value:string|null)=>({getItem:()=>value}); + expect(readNote(store(null),"k")).toBeNull();expect(readNote(store("{"),"k")).toBeNull(); + expect(readNote(store(JSON.stringify({state:"broken",back:{model:NOTE_MODEL}})),"k")).toBeNull(); + expect(readNote(store(JSON.stringify({state:"sealed",text:"hi",back:{model:NOTE_MODEL}})),"k")?.state).toBe("sealed"); +}); diff --git a/web/src/note/prompt.ts b/web/src/note/prompt.ts new file mode 100644 index 0000000..bb6c17a --- /dev/null +++ b/web/src/note/prompt.ts @@ -0,0 +1,26 @@ +import type {ReturnRecord} from "../expedition/return-record"; + +export const HARBOR_NAME="Pocket Harbor"; +const places={beacon:"Beacon Court",wind:"Wind Gate"} as const; +const finds={lens:"the Beacon Lens",moth:"a wind-moth",vane:"the Signal Vane",chart:"a chart",salvage:"some salvage"} as const; + +export const NOTE_INSTRUCTIONS=[ + "You are Mochi, the small companion who lives in a picture-book harbor town.", + "Write one short note to the person who guides you, in first person, two or three sentences, under 60 words.", + "Warm, plain and slightly wry. Mention only the outings listed. If you refer to Mochi in the third person, use she and her.", + "No questions, lists, emoji or sign-off. Never mention AI, models, computers, money, tokens or blockchains.", +].join(" "); + +/** Only facts the game recorded: the fixed harbor name and accepted returns. No player-written text is included. */ +export function noteFacts(returns:readonly ReturnRecord[]) { + const accepted=returns.filter(r=>r.disposition==="accepted").slice(-3).reverse(); + const lines=accepted.map(r=>{ + const cargo=r.cargo.map(item=>finds[item]); + const brought=r.outcome==="rescued"?"Bram brought me home safely":cargo.length?`I brought home ${cargo.join(" and ")}`:"I came home with an empty satchel"; + return `- ${places[r.area]}, carrying the ${r.tool}. ${brought}.`; + }); + return `Harbor: ${HARBOR_NAME}.\nRecent accepted returns, newest first:\n${lines.join("\n")}`; +} +export function noteMessages(returns:readonly ReturnRecord[]) { + return [{role:"system" as const,content:NOTE_INSTRUCTIONS},{role:"user" as const,content:noteFacts(returns)}]; +} diff --git a/web/src/note/seal.ts b/web/src/note/seal.ts new file mode 100644 index 0000000..096afd9 --- /dev/null +++ b/web/src/note/seal.ts @@ -0,0 +1,32 @@ +export const NOTE_MODEL="z-ai/glm-5.3-flash"; +export type SealDecision={state:"sealed"}|{state:"plain";reason:string}; + +const hex=(bytes:Uint8Array)=>[...bytes].map(n=>n.toString(16).padStart(2,"0")).join(""); +const bytesOf=(value:string)=>new Uint8Array(value.match(/../g)!.map(n=>Number.parseInt(n,16))); +const strip=(value:unknown)=>typeof value==="string"?value.replace(/^0x/,"").toLowerCase():""; +export async function sha256Hex(bytes:Uint8Array){return hex(new Uint8Array(await crypto.subtle.digest("SHA-256",bytes as Uint8Array)));} + +/** + * Seal only a model-TEE signature over `:sha256(request):sha256(response)` by the attested key. + * Every other outcome is a readable note that is labelled not sealed. + */ +export async function decideSeal(input:{modelId:string;requestBytes:Uint8Array;responseBytes:Uint8Array;signatureBytes:Uint8Array|null;modelKey:string}):Promise { + if(!input.signatureBytes)return {state:"plain",reason:"NEAR AI had not recorded a signature for this note."}; + let signature:Record; + try{const value:unknown=JSON.parse(new TextDecoder().decode(input.signatureBytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();signature=value as Record;} + catch{return {state:"plain",reason:"The signature record could not be read."};} + if(signature.signature_kind!=="provider_tee")return {state:"plain",reason:"The signature came from the gateway, not the model's sealed room."}; + if(signature.signing_algo!=="ed25519")return {state:"plain",reason:"The signature used an unexpected algorithm."}; + const key=strip(input.modelKey); + if(!/^[0-9a-f]{64}$/.test(key)||strip(signature.signing_address)!==key)return {state:"plain",reason:"The signature is not from the attested model key."}; + const expected=`${input.modelId}:${await sha256Hex(input.requestBytes)}:${await sha256Hex(input.responseBytes)}`; + if(signature.text!==expected)return {state:"plain",reason:"The signed text does not match this exact request and reply."}; + const signed=strip(signature.signature); + if(!/^[0-9a-f]{128}$/.test(signed))return {state:"plain",reason:"The signature is malformed."}; + let valid=false; + try{ + const publicKey=await crypto.subtle.importKey("raw",bytesOf(key),{name:"Ed25519"},false,["verify"]); + valid=await crypto.subtle.verify({name:"Ed25519"},publicKey,bytesOf(signed),new TextEncoder().encode(expected)); + }catch{valid=false;} + return valid?{state:"sealed"}:{state:"plain",reason:"The signature does not verify against the attested model key."}; +} diff --git a/web/src/note/write.ts b/web/src/note/write.ts new file mode 100644 index 0000000..2d90839 --- /dev/null +++ b/web/src/note/write.ts @@ -0,0 +1,85 @@ +import type {ReturnRecord} from "../expedition/return-record"; +import {decideSeal,NOTE_MODEL} from "./seal"; +import {noteMessages} from "./prompt"; + +type Sdk=typeof import("@nearai/inference-sdk"); +type ModelVerifiers=NonNullable[0]["verifiers"]>; +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; +} +export type SealedNote= + |{state:"sealed";text:string;back:NoteBack} + |{state:"plain";text:string;back:NoteBack} + |{state:"broken";back:NoteBack}; + +const base=(model=NOTE_MODEL):NoteBack=>({model,attestation:"Fetched directly from NEAR AI, without a key, using a fresh one-time nonce.",verifiedIn:"Verified in this browser with NEAR AI's inference SDK."}); +const fromBase64=(value:string)=>Uint8Array.from(atob(value),c=>c.charCodeAt(0)); +function check(value:unknown,message:string):asserts value {if(!value)throw Error(message);} + +/** + * One note: verify every attested instance, encrypt both messages to the shared model key with a + * one-use reply key, send the exact bytes through the relay, decrypt, then decide the seal. + */ +export async function writeSealedNote(options:{ + returns:readonly ReturnRecord[];token:string;relayUrl:string; + fetch?:typeof globalThis.fetch;sdk?:Sdk;verifiers?:ModelVerifiers; +}):Promise { + const back=base(),send=options.fetch??globalThis.fetch.bind(globalThis); + let key:string,prepared:Awaited>,requestBytes:Uint8Array; + try{ + const sdk=options.sdk??await import("@nearai/inference-sdk"); + const client=new sdk.AttestationClient({fetch:send}); + const metadata=await client.fetchModelMetadata(NOTE_MODEL); + check(metadata.providerType==="vllm"&&metadata.attestationSupported,"This model does not offer NEAR model attestation."); + const fetched=await client.fetchModelAttestations({model:NOTE_MODEL,signingAlgo:"ed25519"}); + check(fetched.attestations.length>0,"NEAR AI returned no attested model instance."); + const verified=await Promise.all(fetched.attestations.map(attestation=>sdk.verifyModelAttestation({attestation,clientBinding:fetched.clientBinding,policy:{gpuEvidence:"required"},verifiers:options.verifiers}))); + const keys=new Set(verified.map(v=>v.signingPublicKey?.toLowerCase())); + 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}}); + // 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()); + }catch(error){ + return {state:"broken",back:{...back,reason:error instanceof Error&&error.message?`The seal could not be prepared: ${error.message}`:"The seal could not be prepared."}}; + } + let completion:Uint8Array,signature:Uint8Array|null,text:string; + try{ + const response=await send(`${options.relayUrl.replace(/\/$/,"")}/v1/privy/note`,{method:"POST",body:requestBytes,headers:{ + authorization:`Bearer ${options.token}`,"content-type":"application/json", + "x-client-pub-key":prepared.request.headers.get("x-client-pub-key")??"","x-model-pub-key":key, + }}); + 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}}; + } + check(envelope&&typeof envelope==="object"&&"completion" in envelope&&typeof envelope.completion==="string","The harbor's reply was malformed."); + completion=fromBase64(envelope.completion); + signature="signature" in envelope&&typeof envelope.signature==="string"?fromBase64(envelope.signature):null; + const decrypted=await prepared.decryptResponse(new Response(completion,{status:200,headers:{"content-type":"application/json"}})); + const reply=await decrypted.json() as {id?:unknown;choices?:{message?:{content?:unknown}}[]}; + if(typeof reply.id==="string")back.chatId=reply.id; + const content=reply.choices?.[0]?.message?.content; + check(typeof content==="string"&&content.trim(),"The note came back empty."); + text=content.trim().slice(0,600); + }catch(error){ + return {state:"broken",back:{...back,reason:error instanceof Error&&error.message?error.message:"The note could not be opened."}}; + } + const decision=await decideSeal({modelId:NOTE_MODEL,requestBytes,responseBytes:completion,signatureBytes:signature,modelKey:key}); + return decision.state==="sealed"?{state:"sealed",text,back}:{state:"plain",text,back:{...back,reason:decision.reason}}; +} + +export function noteKey(root:string,accountId:string,claimId:string){return `familiar.sealed-note.v1:testnet:${root}:${accountId}:${claimId}`;} +export function readNote(store:Pick,key:string):SealedNote|null { + try{ + const value=JSON.parse(store.getItem(key)??"null") as SealedNote|null; + return value&&["sealed","plain"].includes(value.state)&&"text" in value&&typeof value.text==="string"&&value.back&&typeof value.back.model==="string"?value:null; + }catch{return null;} +} From caf92569ea347e37a0396b48044c62b23d6f8ae1 Mon Sep 17 00:00:00 2001 From: David Dada Date: Fri, 13 Nov 2026 23:43:59 +0100 Subject: [PATCH 05/21] feat(web): show Mochi's note on the latest accepted return behind VITE_SEALED_NOTE_ENABLED --- web/src/account/privy-adapter.ts | 2 + web/src/expedition/Game.tsx | 3 +- web/src/expedition/harbor-controller.ts | 1 + web/src/expedition/harbor-port.ts | 2 + web/src/note/SealedNote.tsx | 68 +++++++++++++++++++++++++ web/src/note/sealed-note.css | 25 +++++++++ 6 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 web/src/note/SealedNote.tsx create mode 100644 web/src/note/sealed-note.css diff --git a/web/src/account/privy-adapter.ts b/web/src/account/privy-adapter.ts index 80ebebd..8c59853 100644 --- a/web/src/account/privy-adapter.ts +++ b/web/src/account/privy-adapter.ts @@ -74,6 +74,8 @@ export class PrivyAccountAdapter implements RecoverableAccountAdapter { const token=await this.options.session.accessToken();this.sameIdentity(identity.id,generation); check(token,"Sign in again before requesting your canonical wallet.");return token; } + /** The current app-scoped session token, for the server to verify identity; never stored. */ + async accessToken(){const identity=await this.identity();return identity?this.token(identity):null;} /** Independent of root deployment, for explicit wallet setup and the sign-only recovery spike. */ async canonicalWallet(create=false):Promise { const generation=this.generation,expectedIdentity=this.options.session.identity()?.id; diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index a0e3f1c..b42578d 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -3,6 +3,7 @@ import "@fontsource-variable/fraunces"; import "@fontsource-variable/figtree"; import World from "./World"; import PassageGame from "./PassageGame"; +import {SealedNote,sealedNoteEnabled} from "../note/SealedNote"; import { passageDelivered, startPassage, type PassageState } from "./passage"; import { dockPassage, emptyPassageHome, readPassageHome, writePassageHome, type Landing, type PassageHome } from "./passage-save"; import HarborChart from "./HarborChart"; @@ -337,7 +338,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in

{passageError||"These crossings and their harbor changes are saved on this device."}

- :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{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.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{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."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

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.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

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.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

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.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} + :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{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.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{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."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.

{record.id}

)}{sealedNoteEnabled()&&savedMode&&session?.noteToken&&session.noteToken!()}/>}{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.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

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.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

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.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} {session?.state.message&&

{session.state.message}

} } } diff --git a/web/src/expedition/harbor-controller.ts b/web/src/expedition/harbor-controller.ts index d23dc0b..027ba27 100644 --- a/web/src/expedition/harbor-controller.ts +++ b/web/src/expedition/harbor-controller.ts @@ -73,6 +73,7 @@ export class HarborController implements HarborSession { async authenticate(){check(this.connection,"Recoverable sign-in is not configured at this address.");return this.enter(()=>this.connection!.adapter.authenticate());} async checkUsername(username:string){this.guard(this.epoch);check(this.connection&&!this.value.busy,"Recoverable sign-in is unavailable or busy.");const epoch=this.epoch,result=await this.connection.adapter.checkUsername(username);this.guard(epoch);return result;} async provisionPlayer(username:string){check(this.connection,"Recoverable sign-in is unavailable.");return this.enter(()=>this.connection!.adapter.provisionAccount(username));} + async noteToken(){const adapter=this.connection?.adapter as {accessToken?():Promise}|undefined;return this.value.mode==="saved"&&this.value.binding&&adapter?.accessToken?adapter.accessToken():null;} async signOut(){this.guard(this.epoch);const epoch=++this.epoch;this.prepared=null;this.update({binding:null,snapshot:null,mode:"preview",review:null,busy:true,message:"Your device previews and original requests are preserved."});try{await this.connection?.adapter.endSession();}finally{if(this.live&&epoch===this.epoch)this.update({busy:false});}} async refresh(){const binding=this.value.binding;check(binding&&this.connection,"Sign in to check the saved harbor.");return this.work(()=>this.load(binding,this.epoch));} private async work(task:()=>Promise) { diff --git a/web/src/expedition/harbor-port.ts b/web/src/expedition/harbor-port.ts index 811bdad..bbde6de 100644 --- a/web/src/expedition/harbor-port.ts +++ b/web/src/expedition/harbor-port.ts @@ -35,4 +35,6 @@ export interface HarborSession { selectSaved():Promise;selectPreview():void; review(intent:WorldIntent):Promise;confirm(reviewId:string):Promise;cancelReview():void; refresh():Promise;resumeOriginal():Promise;checkOriginal():Promise;resolveExpired():Promise; + /** Short-lived session proof for the sealed-note relay; absent when the account provider cannot supply one. */ + noteToken?():Promise; } diff --git a/web/src/note/SealedNote.tsx b/web/src/note/SealedNote.tsx new file mode 100644 index 0000000..9a3bb4c --- /dev/null +++ b/web/src/note/SealedNote.tsx @@ -0,0 +1,68 @@ +import {useEffect,useRef,useState} from "react"; +import type {ReturnRecord} from "../expedition/return-record"; +import {noteKey,readNote,writeSealedNote,type SealedNote as Note} from "./write"; +import "./sealed-note.css"; + +export const SEALED_LINE="Written where nobody could read over her shoulder."; +export const sealedNoteEnabled=()=>import.meta.env.VITE_SEALED_NOTE_ENABLED==="true"; + +type Store=Pick; +const browserStore=():Store|null=>{try{return globalThis.localStorage;}catch{return null;}}; + +/** Mochi's one note, attached to the newest accepted return. Only game-recorded facts are sent. */ +export function SealedNote({returns,token,relayUrl=import.meta.env.VITE_RELAYER_URL??"/api",write=writeSealedNote,store=browserStore()}:{ + 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); + 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; + async function ask(){ + setBusy(true); + let result:Note; + try{ + const bearer=await token(); + result=bearer?await write({returns,token:bearer,relayUrl}):{state:"broken",back:{model:"",attestation:"",verifiedIn:"",reason:"Sign in again so the harbor knows who is asking."}}; + }catch{result={state:"broken",back:{model:"",attestation:"",verifiedIn:"",reason:"The note could not be opened."}};} + if(result.state!=="broken")try{store?.setItem(key!,JSON.stringify(result));}catch{ /* The note still shows for this visit. */ } + if(alive.current){setNote(result);setBusy(false);} + } + if(!note)return
+

Mochi has been chewing a pencil since the last return.

+ +

One note per harbor. Only the harbor's name and your recent accepted returns are sent.

+
; + const facts=note.back; + return
+
+ {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.text}

+
+ {note.state==="sealed"?<> + + Sealed. {SEALED_LINE} + :Not sealed. Mochi wrote this, but the seal could not be checked: {facts.reason}} +
+ } +
+ {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.code!=="NOTE_WRITTEN"&&facts.code!=="NOTE_NO_EVENT"&&} :<>

{note.text}

{note.state==="sealed"?<> Sealed. {SEALED_LINE} - :Not sealed. Mochi wrote this, but the seal could not be checked: {facts.reason}} + :Not sealed. Where this note came from could not be confirmed. {facts.reason}}
} {facts.model&&
Turn the note over
-
Written by
{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.

- {facts.code!=="NOTE_WRITTEN"&&facts.code!=="NOTE_NO_EVENT"&&} + {facts.code!=="QUOTA"&&facts.code!=="NOTE_NO_EVENT"&&} :<>

{note.text}