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
29 changes: 29 additions & 0 deletions app/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,34 @@ export default [
ignores: ['src/lib/i18n/**', '**/*.spec.js'],
plugins: { belege },
rules: { 'belege/no-german': 'error' }
},
{
// Headless logic (#1074): what a page, an agent or a test can call alike.
// Its dependencies – fetch, a signer, a clock, storage – are handed in.
files: ['src/lib/**/core/**/*.js'],
ignores: ['**/*.spec.js'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['svelte', 'svelte/*', '$app/*', '*.svelte', '*.svelte.js'],
message: 'core/ is headless: no Svelte, no runes, no SvelteKit.'
},
{
group: ['$lib/session*', '**/session.svelte.js', '$lib/i18n*', '**/i18n/**'],
message: 'core/ takes what it needs as arguments and answers with codes, not words.'
}
]
}
],
'no-restricted-globals': [
'error',
...['window', 'document', 'localStorage', 'sessionStorage', 'indexedDB', 'navigator'].map(
(name) => ({ name, message: 'core/ runs without a browser.' })
)
]
}
}
];
4 changes: 2 additions & 2 deletions app/src/lib/backup/BackupCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
creditsPerDay,
createBackupUploader,
ensureBackupKey,
FILE_NOT_FOUND,
findBackups,
forgetChain,
isAddress,
Expand All @@ -52,6 +51,7 @@
saveOwner,
storeAnswer
} from './keeper.js';
import { refusalOfRecord } from './core/refusal.js';
// The run itself is the app's (run.svelte.js): it goes on when this card is
// left, and the header shows it.

Expand Down Expand Up @@ -818,7 +818,7 @@
: ''}"
>
{#if b.status === 'unknown'}{t('backup.unknownHint')}{/if}
{#if b.status === 'rejected' && b.errorCode === FILE_NOT_FOUND}
{#if refusalOfRecord(b)?.code === 'file-unavailable'}
<!-- Aleph never got the file: a new order for it would be refused again. -->
<span class="w-full" data-testid="backup-file-gone">{t('backup.fileGone')}</span>
{:else}
Expand Down
116 changes: 116 additions & 0 deletions app/src/lib/backup/core/refusal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Why Aleph refused to keep a backup, as data (#1074, BK1): a code a page, an
// agent or a test can read, the amounts when Aleph named them, and whether
// asking again can work. No words here – the page picks them (i18n).
//
// Headless: nothing in `backup/core/` imports Svelte, the session, the
// catalogue or browser storage (eslint.config.js).
//
// A refusal reaches the app three ways:
// - thrown while the run waits for Aleph's word: keeper.js
// `BackupRefusedError`, kind `credits` with the two amounts, or kind
// `rejected` with Aleph's error code;
// - thrown by the bridge, when it signs: an error with the code
// `ALEPH_BACKUP_REJECTED` (bridge/client.js) – why is only in its text;
// - found later, on a row Aleph had answered `pending` for: the row's
// `status: 'rejected'` and `errorCode` (recheck.js).

/**
* Aleph's error codes for a message it refused, as its node software names
* them (pyaleph `ErrorCode`, read 2026-12-01). Only those a STORE can get.
*/
export const ALEPH_ERROR = Object.freeze({
INVALID_FORMAT: 0,
INVALID_SIGNATURE: 1,
PERMISSION_DENIED: 2,
FILE_UNAVAILABLE: 4,
BALANCE_INSUFFICIENT: 5,
CREDIT_INSUFFICIENT: 6,
STORE_REF_NOT_FOUND: 200,
STORE_UPDATE_UPDATE: 201,
INVALID_PAYMENT_METHOD: 202
});

/**
* @typedef {'credits' | 'file-unavailable' | 'not-allowed' | 'invalid' | 'unknown'} RefusalCode
* `credits`: the paying account has too few; `file-unavailable`: Aleph could
* not fetch the file; `not-allowed`: the key that signed may not act for the
* account; `invalid`: the message itself is wrong; `unknown`: Aleph gave no
* code, or one not listed here
* @typedef {'no' | 'after-credits' | 'after-grant' | 'maybe'} RefusalRetry
* whether a new STORE for the same file can be kept: never, once credits
* were added, once the key was granted, or nobody can tell
* @typedef {object} Refusal
* @property {RefusalCode} code
* @property {RefusalRetry} retry
* @property {number} [alephCode] Aleph's own code, when it gave one
* @property {number} [credits] what the account has, when Aleph said
* @property {number} [required] what a day of this file needs, when Aleph said
*/

/** @type {Record<number, [RefusalCode, RefusalRetry]>} */
const BY_ALEPH_CODE = {
[ALEPH_ERROR.INVALID_FORMAT]: ['invalid', 'no'],
[ALEPH_ERROR.INVALID_SIGNATURE]: ['invalid', 'no'],
[ALEPH_ERROR.PERMISSION_DENIED]: ['not-allowed', 'after-grant'],
[ALEPH_ERROR.FILE_UNAVAILABLE]: ['file-unavailable', 'no'],
[ALEPH_ERROR.BALANCE_INSUFFICIENT]: ['credits', 'after-credits'],
[ALEPH_ERROR.CREDIT_INSUFFICIENT]: ['credits', 'after-credits'],
[ALEPH_ERROR.STORE_REF_NOT_FOUND]: ['invalid', 'no'],
[ALEPH_ERROR.STORE_UPDATE_UPDATE]: ['invalid', 'no'],
[ALEPH_ERROR.INVALID_PAYMENT_METHOD]: ['invalid', 'no']
};

/**
* The refusal Aleph's error code stands for; without a code, or with one not
* listed, `unknown` – asking again may or may not work.
*
* @param {unknown} alephCode
* @returns {Refusal}
*/
export function refusalOfCode(alephCode) {
if (!Number.isInteger(alephCode)) return { code: 'unknown', retry: 'maybe' };
const n = Number(alephCode);
const [code, retry] = BY_ALEPH_CODE[n] ?? ['unknown', 'maybe'];
return { code, retry, alephCode: n };
}

/** @param {unknown} n */
const amount = (n) => (Number.isFinite(Number(n)) && n !== null && n !== '' ? Number(n) : null);

/**
* What a thrown error says about a refusal, or null when it is no refusal
* (the network, a timeout, a limit of the upload).
*
* @param {unknown} error
* @returns {Refusal | null}
*/
export function refusalOfError(error) {
const e = /** @type {any} */ (error);
if (!e || typeof e !== 'object') return null;
if (e.name === 'BackupRefusedError') {
if (e.kind === 'credits') {
const credits = amount(e.reason?.credits);
const required = amount(e.reason?.required);
return {
code: 'credits',
retry: 'after-credits',
...(credits !== null ? { credits } : {}),
...(required !== null ? { required } : {})
};
}
return refusalOfCode(e.reason?.errorCode);
}
// The bridge signed, and Aleph refused it: the reason stayed in its words.
if (e.code === 'ALEPH_BACKUP_REJECTED') return { code: 'unknown', retry: 'maybe' };
return null;
}

/**
* Why Aleph refused a backup of the history, or null for one it did not refuse.
*
* @param {{ status?: string, errorCode?: number } | null | undefined} record
* @returns {Refusal | null}
*/
export function refusalOfRecord(record) {
return record?.status === 'rejected' ? refusalOfCode(record.errorCode) : null;
}
105 changes: 105 additions & 0 deletions app/src/lib/backup/core/refusal.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// A refusal as data: one case per way it reaches the app. Made-up amounts.
import { describe, expect, it } from 'vitest';

import { BackupRefusedError } from '../keeper.js';
import { ALEPH_ERROR, refusalOfCode, refusalOfError, refusalOfRecord } from './refusal.js';

describe('refusalOfCode', () => {
it('names what each of Aleph’s codes means, and whether asking again can work', () => {
expect(refusalOfCode(ALEPH_ERROR.FILE_UNAVAILABLE)).toEqual({
code: 'file-unavailable',
retry: 'no',
alephCode: 4
});
expect(refusalOfCode(ALEPH_ERROR.CREDIT_INSUFFICIENT)).toEqual({
code: 'credits',
retry: 'after-credits',
alephCode: 6
});
expect(refusalOfCode(ALEPH_ERROR.BALANCE_INSUFFICIENT).code).toBe('credits');
expect(refusalOfCode(ALEPH_ERROR.PERMISSION_DENIED)).toEqual({
code: 'not-allowed',
retry: 'after-grant',
alephCode: 2
});
for (const n of [0, 1, 200, 201, 202]) {
expect(refusalOfCode(n)).toEqual({ code: 'invalid', retry: 'no', alephCode: n });
}
});

it('keeps a code it does not know, and does not guess', () => {
expect(refusalOfCode(-1)).toEqual({ code: 'unknown', retry: 'maybe', alephCode: -1 });
expect(refusalOfCode(3)).toEqual({ code: 'unknown', retry: 'maybe', alephCode: 3 });
});

it('is unknown without a code', () => {
for (const none of [undefined, null, '4', 4.5, NaN]) {
expect(refusalOfCode(none)).toEqual({ code: 'unknown', retry: 'maybe' });
}
});
});

describe('refusalOfError', () => {
it('reads the amounts of a refusal for credits thrown while the run waits', () => {
const e = new BackupRefusedError('credits', { credits: 12, required: 345 });
expect(refusalOfError(e)).toEqual({
code: 'credits',
retry: 'after-credits',
credits: 12,
required: 345
});
});

it('leaves out an amount Aleph did not name', () => {
const e = new BackupRefusedError('credits', { credits: NaN, required: 345 });
expect(refusalOfError(e)).toEqual({ code: 'credits', retry: 'after-credits', required: 345 });
});

it('reads Aleph’s code of any other refusal thrown while the run waits', () => {
expect(refusalOfError(new BackupRefusedError('rejected', { errorCode: 4 }))).toEqual({
code: 'file-unavailable',
retry: 'no',
alephCode: 4
});
expect(refusalOfError(new BackupRefusedError('rejected', { errorCode: null }))).toEqual({
code: 'unknown',
retry: 'maybe'
});
});

it('knows a refusal the bridge reports, without its reason', () => {
const e = Object.assign(new Error('said in words'), {
status: 402,
code: 'ALEPH_BACKUP_REJECTED'
});
expect(refusalOfError(e)).toEqual({ code: 'unknown', retry: 'maybe' });
});

it('is null for what is no refusal', () => {
expect(refusalOfError(new TypeError('Failed to fetch'))).toBeNull();
expect(refusalOfError(Object.assign(new Error('x'), { reason: 'signed-limit' }))).toBeNull();
expect(
refusalOfError(Object.assign(new Error('x'), { name: 'UploadTimeoutError' }))
).toBeNull();
expect(refusalOfError(null)).toBeNull();
expect(refusalOfError('rejected')).toBeNull();
});
});

describe('refusalOfRecord', () => {
it('reads the code a row was given when Aleph refused it later', () => {
expect(refusalOfRecord({ status: 'rejected', errorCode: 4 })?.code).toBe('file-unavailable');
expect(refusalOfRecord({ status: 'rejected', errorCode: 6 })?.retry).toBe('after-credits');
});

it('is unknown for a refused row without a code', () => {
expect(refusalOfRecord({ status: 'rejected' })).toEqual({ code: 'unknown', retry: 'maybe' });
});

it('is null for a row Aleph did not refuse, whatever code it still carries', () => {
for (const status of ['processed', 'pending', 'unknown', 'forgotten']) {
expect(refusalOfRecord({ status, errorCode: 4 })).toBeNull();
}
expect(refusalOfRecord(null)).toBeNull();
});
});
5 changes: 1 addition & 4 deletions app/src/lib/backup/keeper.js
Original file line number Diff line number Diff line change
Expand Up @@ -572,11 +572,8 @@ export async function storeStatus({ itemHash, endpoints = alephEndpoints(), fetc
return (await storeAnswer({ itemHash, endpoints, ...(f ? { fetch: f } : {}) })).status;
}

/** Aleph's error code for a STORE whose file it could not fetch ("File not found"). */
export const FILE_NOT_FOUND = 4;

/**
* The same, with why Aleph refused it (its error code), when it did.
* The same, with why Aleph refused it (its error code, core/refusal.js), when it did.
*
* @param {{ itemHash: string, endpoints?: AlephEndpoints, fetch?: typeof fetch }} params
* @returns {Promise<{ status: string, errorCode?: number }>}
Expand Down
39 changes: 27 additions & 12 deletions app/src/lib/backup/run.svelte.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import { backupName, loadBackups, rememberBackup, updateBackup } from './history
import { chainAfter, chainFromBase, loadChain, saveChain } from './chain.js';
import { keepAwake } from '$lib/wake-lock.js';
import { holdAlive } from '$lib/keep-alive.js';
import { BackupRefusedError, storeAnswer } from './keeper.js';
import { storeAnswer } from './keeper.js';
import { refusalOfError } from './core/refusal.js';

/**
* @typedef {'' | 'packing' | 'asking' | 'uploading' | 'keeping'} BackupStep
Expand Down Expand Up @@ -128,8 +129,15 @@ const holdTheTab = (e) => {
};

/** Aleph refused to keep it – by this browser's key, or by the bridge. @param {unknown} e */
const alephRefused = (e) =>
e instanceof BackupRefusedError || /** @type {any} */ (e)?.code === 'ALEPH_BACKUP_REJECTED';
const alephRefused = (e) => refusalOfError(e) !== null;

/**
* Aleph's refusal by this browser's key (keeper.js `BackupRefusedError`): the
* bridge's comes in words already.
* @param {unknown} e
*/
const refusedByKey = (e) =>
/** @type {any} */ (e)?.name === 'BackupRefusedError' ? refusalOfError(e) : null;

/** Aleph's refusal in words. @param {unknown} e */
export const refused = (e) =>
Expand All @@ -148,17 +156,24 @@ export const refused = (e) =>
size: sizeText(/** @type {any} */ (e).size),
limit: sizeText(/** @type {any} */ (e).limit)
})
: e instanceof BackupRefusedError
? e.kind === 'credits'
? t('messages.bridge.alephNotKept', {
credits: Number(e.reason.credits).toLocaleString(intlLocale()),
required: Number(e.reason.required).toLocaleString(intlLocale())
})
: t('messages.bridge.alephRejected', { error: String(e.reason.errorCode ?? '') })
: refusedByKey(e)
? refusedText(/** @type {import('./core/refusal.js').Refusal} */ (refusedByKey(e)))
: e instanceof Error
? e.message
: String(e);

/**
* A refusal in words: with the amounts when Aleph named them, else with its code.
* @param {import('./core/refusal.js').Refusal} why
*/
const refusedText = (why) =>
why.credits !== undefined && why.required !== undefined
? t('messages.bridge.alephNotKept', {
credits: why.credits.toLocaleString(intlLocale()),
required: why.required.toLocaleString(intlLocale())
})
: t('messages.bridge.alephRejected', { error: String(why.alephCode ?? '') });

/**
* Per database, as the app names them.
*
Expand Down Expand Up @@ -304,8 +319,8 @@ export async function runBackup({ continuing, uploader, askFor, unattended = fal
store.settings,
recordOf({
status: alephRefused(e) ? 'rejected' : 'unknown',
...(Number.isInteger(/** @type {any} */ (e)?.reason?.errorCode)
? { errorCode: Number(/** @type {any} */ (e).reason.errorCode) }
...(refusalOfError(e)?.alephCode !== undefined
? { errorCode: refusalOfError(e)?.alephCode }
: {}),
...(handle?.itemHash ? { itemHash: String(handle.itemHash) } : {})
})
Expand Down