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
25 changes: 18 additions & 7 deletions docs/AI-driver/02-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,24 @@ route does this; copy that pattern, do not let a parse throw reach the outer cat

## Private keys on the client

- Client signing goes through `useSessionSigning` (the unified entry — the callers migrated in
A6-T2/T3a/T3b: transfer, the eight active-class wallet operations, and the four remaining
wallet-domain callers: claim rewards, communities, change password, recovery warning) or
directly through `SteemSigner` (`client.ts`) for the T4 callers (market/proposals/witnesses),
the login challenge, the recovery pages, and the two no-session-key remnants (the claim
banner's remembered-posting-key branch and the communities hivemind setup ops — see
09-vault.md's "who still signs directly" inventory).
- Client signing goes through `useSessionSigning` (the unified entry — every business
caller is migrated: A6-T2 transfer; A6-T3a the eight active-class wallet operations;
A6-T3b claim rewards, communities, change password, recovery warning; A6-T4 market limit
orders, proposals vote/create/remove and witness vote/proxy — all at the ACTIVE floor
except the documented posting/owner floors in 09-vault.md). `SteemSigner` (`client.ts`)
remains ONLY for the login challenge + key derivation, the recovery pages' dual-sign
flow, the non-signing derive/validate helpers, and the two no-session-key remnants (the
claim banner's remembered-posting-key branch and the communities hivemind setup ops —
see 09-vault.md's final "who still signs directly" inventory).
AUTHORITY NOTE (T4): update_proposal_votes is an ACTIVE-class Steem operation — the
legacy postingOps whitelist never listed it and the chain's active authority covers it —
so proposals votes sign at the active floor exactly like the pre-T4 active-or-owner key
resolution; do NOT "downgrade" it to posting.
LOGIN-DIALOG CONTRACT (T4): the market / proposals / witnesses embedded sign-in dialogs
pass `requiredAuthTypes: ['active']` with NO fixedUsername (session-account pages:
unauthenticated visitors may log in as any account), so a privateKey login is fit for
purpose the first time; the account-pinned classic re-auth dialogs (every caller's
`needsClassicReauth` surface) keep `fixedUsername` + `requiredAuthTypes`.
CHANGE-PASSWORD KEY SOURCE (T3b): the account_update signs with the SESSION
owner key, not the owner WIF the form's account password used to derive —
a privateKey session without an owner key gets the `ownerKeySessionRequired`
Expand Down
12 changes: 8 additions & 4 deletions docs/AI-driver/06-frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,15 @@ canonical lowercase.
`useSessionSigning` (09-vault.md module map): it applies this lowest-at-or-above-the-floor
rule for privateKey sessions itself (posting → active → owner for a posting floor, active →
owner for an active floor) and routes vault identity sessions through the per-key password
dialog. After A6-T3b every wallet-domain caller is on it (transfer pilot + the eight
active-class ops + claim / communities / change-password / recovery-warning); the remaining
direct signers are the T4 market/proposals/witnesses callers, the two no-session-key
dialog. After A6-T4 EVERY business signing caller is on it (transfer pilot + the eight
active-class ops + claim / communities / change-password / recovery-warning + the five
T4 callers — market limit orders, proposals vote/create/remove, witness vote/proxy —
EACH of the five T4 callers at the ACTIVE floor; the earlier callers' posting/owner
floors are the documented exceptions in 09-vault.md's A6 progress note); the only
remaining direct signers are the two no-session-key
remnants (claim remembered-key branch, communities hivemind setup ops) and the permanent
login-challenge/recovery paths — see 09-vault.md's "who still signs directly" inventory.
login-challenge/recovery paths — see 09-vault.md's final "who still signs directly"
inventory.

## Legacy-parity watchlist (verified drifts from `wallet-legacy`)

Expand Down
179 changes: 114 additions & 65 deletions docs/AI-driver/09-vault.md

Large diffs are not rendered by default.

39 changes: 24 additions & 15 deletions src/components/auth/login-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,20 @@
* Mode dispatcher (R3) — decides WHICH login surface the persisted signing
* mode (settings row, default `'privateKey'`) gets:
*
* - `'vault'` + plain usage -> VaultLoginForm (identity selection);
* - `'vault'` + embedded caller that pins an account or requires specific
* authorities (`fixedUsername` / `requiredAuthTypes` — the re-auth
* dialogs) -> an explicit "not available in Vault Mode yet" notice with a
* shortcut to the Work Mode modal. Identity selection cannot satisfy a
* per-key authority requirement; the real path is the per-key password +
* signing flow that A6 wires. Deliberately LOUD, never a silent swap.
* - `'vault'` + plain usage, including embedded dialogs that only declare
* `requiredAuthTypes` (the market / proposals / witnesses "sign in to
* trade / vote" dialogs since A6-T4) -> VaultLoginForm (identity
* selection). The declared authority is NOT checked at identity-selection
* time: after login the caller's action goes through `useSessionSigning`,
* whose per-key password dialog offers exactly the keys at-or-above the
* action's role floor — identity selection IS fit for purpose for vault
* mode now.
* - `'vault'` + embedded caller that PINS an account (`fixedUsername` — the
* account-locked re-auth dialogs) -> an explicit "not available in Vault
* Mode yet" notice with a shortcut to the Work Mode modal. An account-
* pinned re-auth means a privateKey session needs ITS account's key back;
* identity selection would switch accounts and cannot serve that.
* Deliberately LOUD, never a silent swap.
* - everything else -> PrivateKeyLoginForm below.
*
* The PrivateKey branch must stay byte-identical in behavior: when the mode
Expand All @@ -82,28 +89,30 @@
* surface storage errors with Retry instead of quietly showing this form.
*/
export function LoginForm(props: LoginFormProps = {}) {
const { embedded = false, fixedUsername, requiredAuthTypes } = props;
const { embedded = false, fixedUsername } = props;
const runtime = useVaultRuntime();
const { mode } = useSigningMode(runtime.state === 'ready' ? runtime.facade : null);

if (mode !== 'vault') {
return <PrivateKeyLoginForm {...props} />;
}

// Embedded re-auth consumers pin an account and/or require key authorities
// that identity selection cannot provide (A6 wires the real path).
if (embedded && (fixedUsername !== undefined || (requiredAuthTypes?.length ?? 0) > 0)) {
// Embedded account-pinned re-auth cannot be satisfied by identity
// selection (it would switch accounts); `requiredAuthTypes` alone CAN —
// the per-action password dialog enforces the floor after login (A6-T4).
if (embedded && fixedUsername !== undefined) {
return <VaultModeUnsupportedNotice />;
}

return <VaultLoginForm embedded={embedded} onLoginSuccess={props.onLoginSuccess} />;
}

/**
* Explicit dead-end for embedded re-auth dialogs while the device is in Vault
* Mode: states that this flow needs a specific key authority, which identity
* selection cannot satisfy yet, and offers the Work Mode modal to switch back
* to PrivateKey Mode. Never renders a silently-degraded form.
* Explicit dead-end for embedded ACCOUNT-PINNED re-auth dialogs while the
* device is in Vault Mode: states that this flow needs this account's key
* back, which identity selection (a different login model that would switch
* accounts) cannot satisfy, and offers the Work Mode modal to switch back to
* PrivateKey Mode. Never renders a silently-degraded form.
*/
function VaultModeUnsupportedNotice() {
const t = useTranslations('auth');
Expand Down Expand Up @@ -175,7 +184,7 @@
return msg === 'passwordupdated'
? t('passwordUpdateSuccess', { username: displayName })
: t('accountRecoverySuccess', { username: displayName });
}, [accountFromQuery, formData.username, t]);

Check warning on line 187 in src/components/auth/login-form.tsx

View workflow job for this annotation

GitHub Actions / lint-and-test

React Hook useMemo has a missing dependency: 'searchParams'. Either include it or remove the dependency array

useEffect(() => {
if (!showRememberUser || fixedUsername || accountFromQuery) return;
Expand Down
147 changes: 127 additions & 20 deletions src/components/market/market-page-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Suspense, useCallback, useState } from 'react';
import { useTranslations } from 'next-intl';
import { LoginForm } from '@/components/auth/login-form';
import { toast } from 'sonner';
import { useAuth, useActiveSigningKey } from '@/hooks/use-auth';
import { useAuth } from '@/hooks/use-auth';
import { useSessionSigning } from '@/hooks/use-session-signing';
import { useMarketData } from '@/hooks/use-market-data';
import { useSteemAccount } from '@/hooks/use-steem-account';
import { MarketDepthChart } from '@/components/market/market-depth-chart';
Expand All @@ -28,22 +29,31 @@ import {
} from '@/lib/market/constants';
import { formatAssetAmount } from '@/lib/market/utils';
import { nextMarketOrderId } from '@/lib/market/order-id';
import { unixSecToSteemIsoTimestamp } from '@/lib/steem/chain-time';
import { invalidateWalletCache } from '@/lib/cache/client-invalidate';
import { apiClient, SteemSigner } from '@/lib/steem/client';
import { apiClient } from '@/lib/steem/client';
import type { Operation } from '@/lib/steem/types';

export function MarketPageClient() {
const t = useTranslations('wallet.marketPage');
const tAuth = useTranslations('auth');
const tWallet = useTranslations('wallet');
const { username, isAuthenticated } = useAuth();
const activeKey = useActiveSigningKey();
// Unified signing entry (A6-T4): privateKey sessions sign through the
// facade's legacy backend exactly as before (active key, owner fallback);
// vault identity sessions get the per-key password dialog. `signing.dialog`
// mounts it.
const signing = useSessionSigning();
const { data: account } = useSteemAccount(username ?? '');
const { orderbook, ticker, history, openOrders, loading, error, refresh } =
useMarketData(username);
const [cancellingId, setCancellingId] = useState<number | null>(null);
const [selectedPrice, setSelectedPrice] = useState<number | null>(null);
const [loginOpen, setLoginOpen] = useState(false);
/** Classic re-auth for a privateKey session that lacks an active/owner key. */
const [reauthOpen, setReauthOpen] = useState(false);

const canTrade = isAuthenticated && !!username && !!activeKey;
const canTrade = isAuthenticated && !!username;

const placeOrder = useCallback(
async (
Expand All @@ -56,7 +66,7 @@ export function MarketPageClient() {
marketRefPrice: number;
}
) => {
if (!username || !activeKey) {
if (!username) {
toast.error(t('signInToTrade'));
setLoginOpen(true);
return;
Expand Down Expand Up @@ -93,16 +103,50 @@ export function MarketPageClient() {
const expiration = Math.floor(Date.now() / 1000) + DEFAULT_LIMIT_ORDER_EXPIRATION_SEC;

try {
const signedTx = await SteemSigner.signLimitOrderCreate(
username,
amountToSell,
minToReceive,
orderid,
expiration,
activeKey
);
// The exact operation tuple SteemSigner.signLimitOrderCreate built
// internally — field order, fill_or_kill default and the ISO
// expiration conversion (condenser_api expects a time_point_sec
// string, not unix seconds) are byte-identical.
const operations: Operation[] = [
[
'limit_order_create',
{
owner: username,
amount_to_sell: amountToSell,
min_to_receive: minToReceive,
fill_or_kill: false,
expiration: unixSecToSteemIsoTimestamp(expiration),
orderid,
},
],
];

// limit_order_create is an active-class operation.
const outcome = await signing.sign({
operations,
accountName: username,
role: 'active',
});

if (outcome.status === 'cancelled') {
// User aborted the vault dialog — back to the form, no error.
return;
}
if (outcome.status === 'needsClassicReauth') {
// privateKey session without an active/owner key: the classic
// re-auth dialog locked to this account.
setReauthOpen(true);
return;
}
if (outcome.status === 'error') {
toast.error(t('orderFailed'));
return;
}

const res = await apiClient.broadcastLimitOrderCreate(signedTx, username);
const res = await apiClient.broadcastLimitOrderCreate(
outcome.result.signedTx,
username
);
if (!res.success) {
toast.error(res.error ?? t('orderFailed'));
return;
Expand All @@ -120,17 +164,44 @@ export function MarketPageClient() {
toast.error(t('orderFailed'));
}
},
[username, activeKey, t, refresh]
[username, t, refresh, signing]
);

const cancelOrder = useCallback(
async (orderid: number) => {
if (!username || !activeKey) return;
if (!username) return;
if (!window.confirm(t('cancelConfirm', { orderId: orderid, user: username }))) return;
setCancellingId(orderid);
try {
const signedTx = await SteemSigner.signLimitOrderCancel(username, orderid, activeKey);
const res = await apiClient.broadcastLimitOrderCancel(signedTx, username);
// The exact operation tuple SteemSigner.signLimitOrderCancel built.
const operations: Operation[] = [
['limit_order_cancel', { owner: username, orderid }],
];

// limit_order_cancel is an active-class operation.
const outcome = await signing.sign({
operations,
accountName: username,
role: 'active',
});

if (outcome.status === 'cancelled') {
// User aborted the vault dialog — release the spinner, no error.
return;
}
if (outcome.status === 'needsClassicReauth') {
setReauthOpen(true);
return;
}
if (outcome.status === 'error') {
toast.error(t('orderFailed'));
return;
}

const res = await apiClient.broadcastLimitOrderCancel(
outcome.result.signedTx,
username
);
if (!res.success) {
toast.error(res.error ?? t('orderFailed'));
return;
Expand All @@ -147,7 +218,7 @@ export function MarketPageClient() {
setCancellingId(null);
}
},
[username, activeKey, t, refresh]
[username, t, refresh, signing]
);

return (
Expand Down Expand Up @@ -182,11 +253,47 @@ export function MarketPageClient() {
</div>
}
>
<LoginForm embedded onLoginSuccess={() => setLoginOpen(false)} />
{/* Unauthenticated visitors may log in as any account; the
active-authority requirement keeps a privateKey login fit for
trading the first time (limit orders are active-class). In
Vault Mode this dialog still offers identity selection — the
per-action password dialog enforces the floor after login. */}
<LoginForm
embedded
requiredAuthTypes={['active']}
onLoginSuccess={() => setLoginOpen(false)}
/>
</Suspense>
</DialogContent>
</Dialog>

<Dialog open={reauthOpen} onOpenChange={setReauthOpen}>
<DialogContent className="z-[60] max-h-[90vh] overflow-x-hidden overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{tWallet('reauthTitle')}</DialogTitle>
<DialogDescription>{tWallet('reauthDescription')}</DialogDescription>
</DialogHeader>
<Suspense
fallback={
<div className="space-y-4 py-2">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-11 w-full" />
</div>
}
>
<LoginForm
embedded
fixedUsername={username ?? ''}
requiredAuthTypes={['active']}
onLoginSuccess={() => setReauthOpen(false)}
/>
</Suspense>
</DialogContent>
</Dialog>

{signing.dialog}

{error && (
<p className="text-destructive text-sm" role="alert">
{error}
Expand Down
Loading
Loading