Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"dependencies": {
"@fontsource-variable/bricolage-grotesque": "^5.3.0",
"@fontsource/lato": "^5.3.0",
"@onlyworlds/sdk": "4.219.1",
"@onlyworlds/sdk": "4.227.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "1.5.3",
"qrcode-generator": "1.4.4"
Expand Down
35 changes: 35 additions & 0 deletions src/kinds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// A value OnlyWorlds would store as another, found before Put it online sends anything.
//
// keel takes a wrong kind with a 200 and changes it: an integer field stores int(value) (2.5 as 2,
// "7" as 7, true as 1), a text field the text of any other value (12 as "12"). The SDK refuses such a
// value before sending, with a TypeError that stops a whole /bulk. A world file written by another
// tool can hold one, and Put it online sends a file's elements as it holds them, so the phone asks the
// SDK's own rule (`kindFaults`, since 4.222.0) first and says which element, field and value.
import { kindFaults } from '@onlyworlds/sdk';
import { fieldLabel } from './schema';

export interface KindFault {
field: string;
kind: 'integer' | 'text';
/** As a person reads it: 2.5, "7", yes, a list. */
shown: string;
}

function shownValue(v: unknown): string {
if (typeof v === 'string') return `"${v.length > 40 ? `${v.slice(0, 40)}…` : v}"`;
if (typeof v === 'number') return String(v);
if (typeof v === 'boolean') return v ? 'yes' : 'no';
if (Array.isArray(v)) return 'a list';
return 'a group of fields';
}

/** The first field, in the element's own order, whose value OnlyWorlds would store as another; or null. */
export function kindFault(type: string, element: Record<string, unknown>): KindFault | null {
const first = kindFaults(type, element)[0];
return first ? { field: first.field, kind: first.kind, shown: shownValue(first.value) } : null;
}

/** The fault in words, after the element's name: 'height holds "7", and that field takes a whole number: ...'. */
export function kindFaultWords(fault: KindFault): string {
return `${fieldLabel(fault.field)} holds ${fault.shown}, and that field takes ${fault.kind === 'integer' ? 'a whole number' : 'text'}: OnlyWorlds would store it as another value.`;
}
22 changes: 21 additions & 1 deletion src/online.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
// so a retry sends the very same body. Then a key for this phone, the pictures the phone holds and
// one atomic /bulk that sets them, the description and the now, a read back, and only when every
// element, picture and own key came back as sent does the phone-only copy go.
import { OwApiError, OwV2Client } from '@onlyworlds/sdk';
import { OwApiError, OwV2Client, typeWord, type ElementType } from '@onlyworlds/sdk';
import { kindFault, kindFaultWords } from './kinds';
import * as db from './db';
import { KEPT, accountName, accountToken, deviceName, whoAmI } from './account';
import { API_BASE, LANTERN_CLIENT_NAME, openWorld, forgetSession, pictureRefusalText } from './world';
Expand Down Expand Up @@ -119,6 +120,21 @@ export function notSendable(rec: db.WorldRecord, ownKeys: Record<string, unknown
return null;
}

/**
* The first element holding a value OnlyWorlds would store as another (`kinds.ts`), said with its name,
* field and value before anything is made: the SDK refuses one, and that refusal stops the whole hand-over.
*/
export function wrongKindLine(elements: Record<string, unknown>[]): string | null {
for (const el of elements) {
const type = typeof el.type === 'string' ? el.type : '';
const fault = kindFault(type, bodyOf(el));
if (!fault) continue;
const who = typeof el.name === 'string' && el.name.trim() ? el.name.trim() : `A ${typeWord(null, type as ElementType)}`;
return `${who}'s ${kindFaultWords(fault)} Change it on its page, then try again. Nothing was sent.`;
}
return null;
}

export class PinNeeded extends Error {
constructor() {
super('Choose a four-digit PIN for your account first.');
Expand Down Expand Up @@ -275,6 +291,8 @@ export async function putOnline(localId: string, pin: string, onStep: (text: str
const ownKeys = worldOwnKeys(rec);
const refused = notSendable(rec, ownKeys);
if (refused) throw new OnlineSaid(refused);
const wrongKind = wrongKindLine(elements as unknown as Record<string, unknown>[]);
if (wrongKind) throw new OnlineSaid(wrongKind);
const held = elements.filter((el) => isHeld(el as Record<string, unknown>)) as Record<string, unknown>[];
// Every element goes in the hand-over without a picture the phone holds: a picture needs the world's key.
const items = elements.map((el) => {
Expand Down Expand Up @@ -649,6 +667,8 @@ async function finishOld(
): Promise<string> {
const localId = rec.id;
const ownKeys = worldOwnKeys(rec);
const wrongKind = wrongKindLine(elements as unknown as Record<string, unknown>[]);
if (wrongKind) throw new OnlineSaid(wrongKind);
const client = new OwV2Client({ apiKey: pending.key, apiPin: pin, baseUrl: API_BASE, client: LANTERN_CLIENT_NAME, fetch: fetchThatHolds(putScope(localId)) });
const held = elements.filter((el) => isHeld(el as Record<string, unknown>));
for (const [i, el] of held.entries()) {
Expand Down
10 changes: 10 additions & 0 deletions src/world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as db from './db';
import type { OutboxRow, WorldRecord } from './db';
import { uuid7 } from './uuid7';
import { isEmptyValue, withoutLinksTo } from './schema';
import { kindFault, kindFaultWords } from './kinds';
import { pinFor, setPin } from './pin';
import { keyRefusalOf, keyRefusalText, type KeyRefusal } from './keyrefusal';
import { hostRefusalText, isHostRefusal } from './hostrefusal';
Expand Down Expand Up @@ -1366,6 +1367,15 @@ export class WorldSession {
await db.putOutboxRow(this.id, { ...row, state: 'waiting' });
}
}
// A value of the wrong kind: the SDK refuses it before sending (4.220) with a TypeError the catch
// below would read as no network, so the row is refused here, in words, and every other element goes on.
const fault = kindFault(row.type, row.values);
if (fault) {
row.state = 'refused';
row.error = `Its ${kindFaultWords(fault)} Change it on its page.`;
await db.putOutboxRow(this.id, row);
return false;
}
let el: OwElement;
if (row.op === 'create') {
el = await c.create(row.type, { ...row.values, id: row.id }, { idempotencyKey: row.idempotencyKey });
Expand Down
17 changes: 17 additions & 0 deletions test/knownof.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,23 @@ describe('a stub is never changed, deleted or sent from here (rules 3 and 5)', (
expect(again.status).not.toBe('offline');
expect(keel.calls.filter((c) => !c.startsWith('GET'))).toEqual([]);
});

it('a row holding a value of the wrong kind is refused in words, never left waiting for signal (SDK 4.220)', async () => {
const s = await playerWorld({ apiKey: 'ow_w_' + 'w'.repeat(40), keyKind: 'write', memberRole: undefined, role: 'owner', characterId: null });
setPin(s.rec, '1234');
await s.pull();
// Hand-built, as an older outbox or a world file's element could hold one: the SDK refuses the body before it is sent.
await db.putOutboxRow(s.id, { op: 'patch', type: 'character', id: ANA, values: { height: '7' }, state: 'waiting', createdAt: '' });
await db.putOutboxRow(s.id, { op: 'create', type: 'character', id: '01a15929-0000-7000-8000-00000000000b', values: { name: 'Bo', description: 12 }, idempotencyKey: 'k2', state: 'waiting', createdAt: '' });
forgetSession(s.id);
const again = await openWorld(s.id);
await again.flush();
expect(again.outbox.map((r) => r.state)).toEqual(['refused', 'refused']);
expect(again.outbox[0].error).toBe('Its Height holds "7", and that field takes a whole number: OnlyWorlds would store it as another value. Change it on its page.');
expect(again.outbox[1].error).toMatch(/^Its Description holds 12, and that field takes text:/);
expect(again.status).not.toBe('offline');
expect(keel.calls.filter((c) => !c.startsWith('GET'))).toEqual([]);
});
});

describe('the stub gate', () => {
Expand Down
24 changes: 24 additions & 0 deletions test/online.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,30 @@ describe('put it online', () => {
expect((await db.allElements(local)).length).toBe(2);
});

it('a world file holding "7" or 2.5 in a whole-number field, or 12 in a text field: said by element, field and value, nothing made, the copy stays', async () => {
keel.accountPin = '4321';
for (const [extra, said] of [
[{ height: '7' }, `Vera's Height holds "7", and that field takes a whole number: OnlyWorlds would store it as another value. Change it on its page, then try again. Nothing was sent.`],
[{ weight: 72.5 }, `Vera's Weight holds 72.5, and that field takes a whole number:`],
[{ supertype: 12 }, `Vera's Supertype holds 12, and that field takes text:`],
] as const) {
const local = await localWorld([...ELS, { id: 'e1000000-0000-7000-8000-000000000016', type: 'character', name: 'Vera', ...extra }]);
const err = await putOnline(local, '4321').then(() => null, (e: Error) => e);
expect(err?.message.startsWith(said), err?.message).toBe(true);
expect(keel.worlds.size).toBe(0);
expect(keel.bulks).toBe(0);
expect((await db.allElements(local)).length).toBe(3);
expect((await db.getWorldRecord(local))?.pendingOnline).toBeUndefined();
}
});

it('a whole number, an unset field and a custom field of any kind go up as before', async () => {
keel.accountPin = '4321';
const local = await localWorld([...ELS, { id: 'e1000000-0000-7000-8000-000000000017', type: 'character', name: 'Vera', height: 180, weight: null, x_mood: 2.5 }]);
await putOnline(local, '4321');
expect(keel.worlds.size).toBe(1);
});

it('a hidden element goes up hidden, as the boolean keel takes; a false or null mark is never sent (folder spec §4.8)', async () => {
keel.accountPin = '4321';
const ids = ['e1000000-0000-7000-8000-000000000011', 'e1000000-0000-7000-8000-000000000012', 'e1000000-0000-7000-8000-000000000013', 'e1000000-0000-7000-8000-000000000014'];
Expand Down
34 changes: 33 additions & 1 deletion walk/live-online.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
// Then a second world file holding an id the first world now holds is put online: nothing may be made
// (keel's hand-over, one write). a331c51 is that control: it makes the world, the bulk is refused, an
// empty world stays (recorded from the account's list by this run's name, and torn down).
// A third holds "7" in a Character's height: said by element, field and value, nothing made; 5702584 is that
// control (it makes the world, recorded and torn down).
// Secrets are never printed.
// Run from tools/lantern:
// CREW_FILE=<crew-walk-accounts.txt> [SERVE_DIST=dist] node walk/live-online.mjs [url] [chromium|webkit|firefox] [tag]
Expand Down Expand Up @@ -79,6 +81,15 @@ const refusedFile = writeWorldFile([
el('character', 'bram', { id: id(5), name: 'Bram' }),
], `online-refused-${run}`);

// Since 2026-11-28: a third world file whose Character holds "7" in an integer field (keel would store 7, and
// the SDK from 4.220 refuses it before sending). Put it online must say the element, field and value with
// nothing made. The build before (5702584) sends it: keel makes the world (recorded, torn down).
const WRONG_NAME = `${WORLD_NAME} wrong kind`;
const wrongFile = writeWorldFile([
{ path: 'world.json', data: enc.encode(JSON.stringify({ id: id(97), name: WRONG_NAME })) },
el('character', 'vera', { id: id(6), name: 'Vera', height: '7' }),
], `online-wrong-${run}`);

// The record: what this run minted, by id. Only these are revoked or deleted.
const tokens = []; // { id, token, by }
const worlds = []; // { id, name, key }
Expand All @@ -95,7 +106,7 @@ function teardown(why) {
try {
const page = await b.newPage({ viewport: { width: 1280, height: 900 } });
for (const w of worlds) {
if (w.name !== WORLD_NAME && w.name !== REFUSED_NAME) { check(false, `teardown: world ${w.id} is named ${JSON.stringify(w.name)}, not this run's: left alone`); continue; }
if (w.name !== WORLD_NAME && w.name !== REFUSED_NAME && w.name !== WRONG_NAME) { check(false, `teardown: world ${w.id} is named ${JSON.stringify(w.name)}, not this run's: left alone`); continue; }
const del = `https://www.onlyworlds.com/account/worlds/${w.id}/delete`;
await page.goto(del);
await page.waitForLoadState('networkidle');
Expand Down Expand Up @@ -275,6 +286,27 @@ try {
check(listed2.filter((x) => x.name === REFUSED_NAME).length === 0 && worlds.filter((x) => x.name === REFUSED_NAME).length === 0,
`the refused put leaves no world on the account (listed ${listed2.filter((x) => x.name === REFUSED_NAME).length}, recorded ${worlds.filter((x) => x.name === REFUSED_NAME).length})`);
await p.screenshot({ path: `${OUT}/live-online-${engine}-${tag}-2-refused.png` });

// ---- 6. A world file holding "7" in an integer field: said, no world made ----
await p.goto(new URL('/#/worlds', url).href);
await p.locator('input[aria-label="A world file"]').waitFor({ state: 'attached', timeout: 15000 });
await p.locator('input[aria-label="A world file"]').setInputFiles({ name: 'wrong.owworld', mimeType: 'application/zip', buffer: Buffer.from(wrongFile) });
need(await p.waitForSelector('[data-screen="home"]', { timeout: 15000 }).then(() => true, () => false), 'the third world file opens on the phone');
await p.goto(new URL('/#/worlds', url).href);
const g3 = p.locator('.local-group', { hasText: WRONG_NAME });
await g3.waitFor({ timeout: 15000 });
await g3.getByRole('button', { name: 'Put it online' }).tap();
await p.locator('.sheet input[aria-label="PIN"]').fill(pin);
await p.locator('.sheet button[type="submit"]').tap();
const wrongKindSaid = await p.locator('.sheet .error').filter({ hasText: /\S/ }).first().innerText({ timeout: 30000 }).catch(() => '');
await p.waitForTimeout(1500);
await Promise.allSettled(pending);
const listed3 = ((await (await fetch(`${API}/account/worlds`, { headers: { Authorization: `Bearer ${own.token}` }, ...limit() })).json().catch(() => ({}))).data ?? []);
for (const w of listed3.filter((x) => x.name === WRONG_NAME)) if (!worlds.some((x) => x.id === w.id)) worlds.push({ id: w.id, name: w.name });
check(/Vera's .*holds "7".*whole number.*Nothing was sent\./.test(wrongKindSaid), `"7" in an integer field is said by element, field and value (${JSON.stringify(wrongKindSaid.trim())})`);
check(listed3.filter((x) => x.name === WRONG_NAME).length === 0 && worlds.filter((x) => x.name === WRONG_NAME).length === 0,
`the wrong kind leaves no world on the account (listed ${listed3.filter((x) => x.name === WRONG_NAME).length}, recorded ${worlds.filter((x) => x.name === WRONG_NAME).length})`);
await p.screenshot({ path: `${OUT}/live-online-${engine}-${tag}-3-wrong-kind.png` });
check(errors.length === 0, `no page errors${errors.length ? ': ' + errors.join(' | ') : ''}`);
} catch (e) {
if (!String(e.message).startsWith('stopped:')) { console.log(`${T} FAIL threw: ${String(e).slice(0, 200)}`); failures++; }
Expand Down
Loading