feat(web): phone registration + fix login/register response handling

- Add RegisterPage (phone + SMS code) and lib/api/auth.ts verification-code
  endpoints, wired into App.tsx routing.
- Fix registerAccountByPhone(): the injected acc.phone extra field must be
  bare 11-digit, not E.164 -- server checks digit length before normalizing.
- Fix LoginCtrl shape: SDK's login/loginBasic/createAccountBasic promises
  resolve with the ctrl fields flat, not wrapped in {ctrl: {...}}.
- Fix tinode-sdk.d.ts: the real method is getCurrentUserID(), there is no
  getAuthenticatedUserID().

All three bugs found and fixed via live testing against the real backend
(api.118im.com, tenant "default"), confirming registration and login both
work end-to-end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Your Name
2026-09-08 00:51:06 +08:00
co-authored by Claude Sonnet 5
parent 8cdd84152d
commit 63c1b84b41
6 changed files with 268 additions and 12 deletions
+67 -7
View File
@@ -7,7 +7,7 @@
// silently stomp on each other. This module claims all the SDK's callback slots exactly once and
// fans them out to any number of subscribers via its own Set, which is what hooks.ts's
// useSyncExternalStore-based hooks actually subscribe to.
import { Tinode } from 'tinode-sdk';
import { Tinode, type LoginCtrl } from 'tinode-sdk';
import { API_KEY, APP_NAME, LOGGING_ENABLED } from '@/lib/config';
import { useSessionStore } from '@/stores/session';
@@ -25,18 +25,32 @@ function setStatus(next: ConnectionStatus) {
}
/**
* The server extends the stock {hi} packet with a `tenant` field (server/datamodel.go) that the
* vendored JS SDK has no API for. `#initPacket`/the connection's packet builder is private, so the
* only usable hook is wrapping the connection's raw sendText and injecting the field into the
* already-serialized JSON. Ported as-is from the old app's tnSetup/installTenantHiPatch -- this is
* a real backend protocol extension, not an old-codebase-specific workaround.
* Registration-only extra fields (username/phone/invite_code) queued by registerAccount() below,
* consumed the next time an {acc} packet actually goes out. A module-level slot, not a per-call
* argument, because the SDK's own createAccountBasic() has no parameter for them at all -- same
* one-shot-queue shape as the old app's `tinode.__pendingAccExtra`.
*/
let pendingAccExtra: Record<string, unknown> | null = null;
export function queueAccExtra(extra: Record<string, unknown>) {
pendingAccExtra = extra;
}
/**
* The server extends two stock packets with fields the vendored JS SDK has no API for
* (server/datamodel.go): {hi}'s `tenant` (resolved via POST /v1/im/tenants/resolve) and {acc}'s
* `username`/`phone`/`invite_code` (used by server/user.go's replyCreateUser during registration).
* The packet builder is private, so the only usable hook is wrapping the connection's raw sendText
* and injecting fields into the already-serialized JSON. Ported as-is from the old app's
* tnSetup/installTenantHiPatch -- this is a real backend protocol extension, not an old-codebase-
* specific workaround.
*/
function installTenantHiPatch(t: Tinode) {
const conn = t._connection;
if (!conn || conn.__tenantPatched) return;
const original = conn.sendText.bind(conn);
conn.sendText = (msg: unknown) => {
if (typeof msg === 'string' && msg.indexOf('"hi":') >= 0) {
if (typeof msg === 'string' && (msg.indexOf('"hi":') >= 0 || msg.indexOf('"acc":') >= 0)) {
try {
const parsed = JSON.parse(msg);
if (parsed.hi) {
@@ -45,6 +59,10 @@ function installTenantHiPatch(t: Tinode) {
parsed.hi.tenant = tenant.code;
msg = JSON.stringify(parsed);
}
} else if (parsed.acc && pendingAccExtra) {
Object.assign(parsed.acc, pendingAccExtra);
pendingAccExtra = null;
msg = JSON.stringify(parsed);
}
} catch {
// Not valid JSON -- send as is.
@@ -105,3 +123,45 @@ export function subscribeConnectionStatus(callback: () => void): () => void {
listeners.add(callback);
return () => listeners.delete(callback);
}
export interface RegisterPhoneParams {
phoneE164: string;
password: string;
displayName?: string;
verificationToken: string;
challengeId: string;
}
/**
* Phone-based registration (product Ch.1.4's phone path). Two DIFFERENT phone representations are
* required and mixing them up throws a 422 "policy violation" with no further detail (confirmed
* live against the real backend, then traced to server/user.go's resolveRegistrationAccount):
* - `login_` (this function's first createAccountBasic arg, becomes the secret's account half)
* must equal what resolveRegistrationAccount computes as secretAccount -- for phone
* registration that's the E.164-normalized phone, e.g. "+8613900005232".
* - the injected `acc.phone` extra field is checked *before* any E.164 normalization happens
* (`len(phone) != 11 || !asciiRegistrationDigits(phone)`) -- it must be the bare 11-digit
* number with no "+86" prefix, e.g. "13900005232". Sending the E.164 form here fails that
* length check immediately, which is exactly the bug this comment is warning future edits away
* from reintroducing.
*/
export async function registerAccountByPhone({
phoneE164,
password,
displayName,
verificationToken,
challengeId,
}: RegisterPhoneParams): Promise<LoginCtrl> {
const t = getTinode();
if (!t.isConnected()) {
await connect();
}
const phoneBare = phoneE164.replace(/^\+86/, '');
queueAccExtra({ phone: phoneBare });
const cred = Tinode.credential({ meth: 'tel', val: phoneE164, resp: verificationToken, params: { challenge_id: challengeId } });
const trimmedName = displayName?.trim();
return t.createAccountBasic(phoneE164, password, {
public: trimmedName ? { fn: trimmedName } : undefined,
cred: cred ?? undefined,
});
}
+33 -2
View File
@@ -19,8 +19,31 @@ declare module 'tinode-sdk' {
export type AuthLevel = 'anon' | 'auth' | 'root';
/**
* login()/loginBasic()/loginToken()/createAccountBasic() all resolve with this shape directly --
* NOT wrapped in an outer `{ctrl: ...}` key, confirmed against the SDK's own source (the resolved
* value is literally the promise executor's `ctrl` parameter, one level flatter than the *wire*
* message's `{"ctrl": {...}}` envelope). Getting this wrong throws "Cannot read properties of
* undefined" on the very first successful (non-throwing) call, since `.ctrl` doesn't exist -- hit
* live registering a real account before this type was corrected.
*/
export interface LoginCtrl {
ctrl: { code: number; text?: string; params?: Record<string, unknown> };
code: number;
text?: string;
params?: Record<string, unknown>;
}
export interface CredentialParam {
meth: string;
val?: string;
resp?: string;
params?: Record<string, unknown>;
}
export interface CredentialInput {
meth: string;
val?: string;
resp?: string;
params?: Record<string, unknown>;
}
export class AccessMode {
@@ -103,7 +126,7 @@ declare module 'tinode-sdk' {
disconnect(): void;
isConnected(): boolean;
isAuthenticated(): boolean;
getAuthenticatedUserID(): string | undefined;
getCurrentUserID(): string;
login(scheme: string, secret: string, cred?: unknown): Promise<LoginCtrl>;
loginBasic(username: string, password: string, cred?: unknown): Promise<LoginCtrl>;
@@ -114,6 +137,14 @@ declare module 'tinode-sdk' {
getTopic(topicName: string): Topic;
account(userId: string, scheme: string, secret: string, login: boolean, desc?: unknown): Promise<unknown>;
createAccountBasic(
username: string,
password: string,
params: { public?: TopicDescPublic; tags?: string[]; cred?: CredentialParam[]; attachments?: string[] },
): Promise<LoginCtrl>;
/** Wraps a single {meth,val,resp,params} credential into the array shape {acc}/createAccountBasic expects. */
static credential(cred: CredentialInput): CredentialParam[] | null;
onConnect?: () => void;
onDisconnect?: (err?: Error) => void;