A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): host sign-in, and the half the engine refuses to fake
yhha37f85818fa7
diff --git a/docs/astro/src/content/docs/guides/services.mdx b/docs/astro/src/content/docs/guides/services.mdxindex de3bf5047..4f2467db9 100644--- a/docs/astro/src/content/docs/guides/services.mdx+++ b/docs/astro/src/content/docs/guides/services.mdx@@ -154,3 +154,35 @@ friends. So the panel can be laid out and styled without packaging anything.What it cannot rehearse is the part that is genuinely the host's — real friendsand the sandbox they live in. Check that on a device before you ship.++## Signing in++A mini-game host signs the player in and hands back a **one-time code**. That+code is not an identity: turning it into one takes your app secret, and an app+secret in a client is an app secret anyone can read. So the exchange belongs to+your own server, and the engine's job ends at the code.++```typescript+import { defineSystem, Res, Identity } from 'esengine';++if (!identity.available) return; // web, native, the editor++// Skip the round trip when the session your server holds is still good.+if (await identity.sessionValid()) return;++const { code } = await identity.login(); // a CODE, not a session+const session = await postToYourServer('/session', { code });+```++`login()` rejects — with the host's own words — when the sign-in fails, and+rejects immediately where the platform has none, so a caller that skipped+`available` hears about it instead of awaiting a promise that never settles.+The code is short-lived and single-use: cache the session your server returns,+never the code.++There is deliberately **no local stand-in** for this in play mode, unlike ads+and the leaderboard. A pretend ad is still a real pause and a pretend board is+still the real renderer, so rehearsing them tells you something. A pretend code+is a string no server can exchange — rehearsing with it would only rehearse a+request that is going to fail. Off-platform, `available` is `false`, and a game+takes whatever path it takes when there is no account.diff --git a/docs/astro/src/content/docs/zh-cn/guides/services.mdx b/docs/astro/src/content/docs/zh-cn/guides/services.mdxindex 81321879a..e1998f038 100644--- a/docs/astro/src/content/docs/zh-cn/guides/services.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/services.mdx@@ -141,3 +141,31 @@ Play 模式会装一块本地榜:跑的是**引擎自己的渲染器**,和它替代不了的是真正属于宿主的那部分——真实好友,以及它们所在的沙箱。发版前请在真机上过一眼。++## 登录++小游戏宿主把玩家登录后交给你一个**一次性 code**。这个 code 不是身份:要把它换成+身份需要你的 app secret,而放在客户端里的 app secret 等于人人可读。所以**这一步+交换属于你自己的服务器**,引擎的职责到 code 为止。++```typescript+import { defineSystem, Res, Identity } from 'esengine';++if (!identity.available) return; // 网页、原生、编辑器都没有++// 你服务器手上的会话还有效时,跳过这趟往返。+if (await identity.sessionValid()) return;++const { code } = await identity.login(); // 是 code,不是会话+const session = await postToYourServer('/session', { code });+```++登录失败时 `login()` 会 **reject**,并带上宿主自己的说法;平台压根没有登录时也会+立刻 reject——这样跳过了 `available` 的调用方会听到消息,而不是 await 一个永远不+settle 的 promise。code 短期有效且只能用一次:**缓存你服务器返回的会话,不要缓存+code**。++这里**刻意没有本地替身**,和广告、排行榜不同。假广告仍然是真的暂停、假排行榜仍然+是真的渲染器,排练它们有意义;而假 code 是任何服务器都换不了的字符串——拿它排练,+排练的只是一个注定失败的请求。在没有该能力的平台上 `available` 是 `false`,游戏走+它在「没有账号」时本来该走的那条路。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 26cd9bfe0..d3acc7a11 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1399 stable · 17 beta · 1 deprecated+Symbols: 1402 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -3291,6 +3291,20 @@ numbernumber```+## Identity — const+```+ResourceDef<IdentityAPI>+```++## IdentityAPI — class+```+available: boolean+login: () => Promise<LoginResult>+sessionValid: () => Promise<boolean>+static new (): IdentityAPI+static prototype: IdentityAPI+```+## ImageSegment — interface```height: number@@ -3932,6 +3946,11 @@ static new (): Loggerstatic prototype: Logger```+## LoginResult — interface+```+code: string+```+## LoopMode — type```(typeof LoopMode)[keyof typeof LoopMode]@@ -4801,6 +4820,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canSignIn: (() => boolean) | undefined+checkSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -4819,6 +4840,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: (() => string) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefined+login: (() => Promise<string>) | undefinedname: PlatformNamenow: () => numberonAppHide: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 2925c0b6e..dbe5b5830 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1418 stable · 22 beta · 1 deprecated+Symbols: 1421 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -3299,6 +3299,20 @@ numbernumber```+## Identity — const+```+ResourceDef<IdentityAPI>+```++## IdentityAPI — class+```+available: boolean+login: () => Promise<LoginResult>+sessionValid: () => Promise<boolean>+static new (): IdentityAPI+static prototype: IdentityAPI+```+## ImageSegment — interface```height: number@@ -3940,6 +3954,11 @@ static new (): Loggerstatic prototype: Logger```+## LoginResult — interface+```+code: string+```+## LoopMode — type```(typeof LoopMode)[keyof typeof LoopMode]@@ -4957,6 +4976,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canSignIn: (() => boolean) | undefined+checkSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -4975,6 +4996,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: (() => string) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefined+login: (() => Promise<string>) | undefinedname: PlatformNamenow: () => numberonAppHide: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7395d2525..511bb8dad 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1398 stable · 19 beta · 1 deprecated+Symbols: 1401 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3286,6 +3286,20 @@ numbernumber```+## Identity — const+```+ResourceDef<IdentityAPI>+```++## IdentityAPI — class+```+available: boolean+login: () => Promise<LoginResult>+sessionValid: () => Promise<boolean>+static new (): IdentityAPI+static prototype: IdentityAPI+```+## ImageSegment — interface```height: number@@ -3927,6 +3941,11 @@ static new (): Loggerstatic prototype: Logger```+## LoginResult — interface+```+code: string+```+## LoopMode — type```(typeof LoopMode)[keyof typeof LoopMode]@@ -4796,6 +4815,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canSignIn: (() => boolean) | undefined+checkSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -4814,6 +4835,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: (() => string) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefined+login: (() => Promise<string>) | undefinedname: PlatformNamenow: () => numberonAppHide: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 305f136cc..087c74d37 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1419 stable · 17 beta · 1 deprecated+Symbols: 1422 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3286,6 +3286,20 @@ numbernumber```+## Identity — const+```+ResourceDef<IdentityAPI>+```++## IdentityAPI — class+```+available: boolean+login: () => Promise<LoginResult>+sessionValid: () => Promise<boolean>+static new (): IdentityAPI+static prototype: IdentityAPI+```+## ImageSegment — interface```height: number@@ -3927,6 +3941,11 @@ static new (): Loggerstatic prototype: Logger```+## LoginResult — interface+```+code: string+```+## LoopMode — type```(typeof LoopMode)[keyof typeof LoopMode]@@ -4187,6 +4206,7 @@ writeFile: (opts: { filePath: string; data: string | ArrayBuffer; encoding?: str## MiniGameGlobal — interface```+checkSession: ((opts: { success?: () => void; fail?: (err: unknown) => void; }) => void) | undefinedconnectSocket: (opts: { url: string; protocols?: string[]; }) => MiniGameSocketTaskcreateCanvas: () => MiniGameCanvascreateImage: () => MiniGameImage@@ -4199,6 +4219,7 @@ getStorageInfoSync: () => MiniGameStorageInfogetStorageSync: (key: string) => unknowngetSystemInfoSync: () => MiniGameSystemInfoloadSubpackage: ((opts: { name: string; success?: () => void; fail?: (err: unknown) => void; complete?: () => void; }) => void) | undefined+login: ((opts: { success?: (res: { code: string; }) => void; fail?: (err: unknown) => void; timeout?: number; }) => void) | undefinedoffKeyDown: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefinedoffKeyUp: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefinedoffMemoryWarning: ((cb: () => void) => void) | undefined@@ -4259,6 +4280,8 @@ code: string## MiniGamePlatformAdapter — class```bindInputEvents: (callbacks: InputEventCallbacks, _target?: unknown) => void+canSignIn: () => boolean+checkSession: () => Promise<boolean>clearStorage: (prefix: string) => voidcreateAudioBackend: () => PlatformAudioBackendcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -4277,6 +4300,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: () => stringloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: (name: string) => Promise<void>+login: () => Promise<string>name: PlatformNamenow: () => numberonMemoryWarning: (callback: () => void) => () => void@@ -5024,6 +5048,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canSignIn: (() => boolean) | undefined+checkSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -5042,6 +5068,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: (() => string) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefined+login: (() => Promise<string>) | undefinedname: PlatformNamenow: () => numberonAppHide: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex dec2aa81f..4950a7d7b 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1409 stable · 17 beta · 1 deprecated+Symbols: 1412 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3286,6 +3286,20 @@ numbernumber```+## Identity — const+```+ResourceDef<IdentityAPI>+```++## IdentityAPI — class+```+available: boolean+login: () => Promise<LoginResult>+sessionValid: () => Promise<boolean>+static new (): IdentityAPI+static prototype: IdentityAPI+```+## ImageLoadResult — interface```height: number@@ -3934,6 +3948,11 @@ static new (): Loggerstatic prototype: Logger```+## LoginResult — interface+```+code: string+```+## LoopMode — type```(typeof LoopMode)[keyof typeof LoopMode]@@ -4803,6 +4822,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canSignIn: (() => boolean) | undefined+checkSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvas@@ -4821,6 +4842,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imporlanguage: (() => string) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefined+login: (() => Promise<string>) | undefinedname: PlatformNamenow: () => numberonAppHide: ((callback: () => void) => () => void) | undefineddiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex a212137b3..74bf2a14c 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -406,10 +406,11 @@ export {Ads, AdsAPI, createMockAdProvider,Share, ShareAPI,Leaderboard, LeaderboardAPI, createLocalLeaderboard,+ Identity, IdentityAPI,ServicesPlugin, servicesPlugin,type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,- type LeaderboardStyle, type LocalLeaderboardOptions,+ type LeaderboardStyle, type LocalLeaderboardOptions, type LoginResult,} from './services';// =============================================================================diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 08f53afb3..a0d57f47d 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -299,6 +299,31 @@ export function platformOnShareRequest(provide: () => import('./types').Platformreturn true;}+/** Whether this platform can sign a player in at all — what a menu reads to+ * hide its sign-in button honestly (web, native and the editor cannot). */+export function platformCanSignIn(): boolean {+ if (!isPlatformInitialized()) return false;+ const p = getPlatform();+ // Declared, and — where the adapter can be more precise than its own method+ // list — actually backed by a host that signs people in.+ return p.login !== undefined && (p.canSignIn?.() ?? true);+}++/** Begin a sign-in; rejects where the platform has none, so a caller that+ * skipped {@link platformCanSignIn} still hears about it rather than awaiting+ * a promise that never settles. */+export function platformLogin(): Promise<string> {+ if (!platformCanSignIn()) return Promise.reject(new Error('this platform has no sign-in'));+ return getPlatform().login!();+}++/** Whether the host still regards the last sign-in as current. False where+ * there is no sign-in at all — there is nothing current about nothing. */+export function platformCheckSession(): Promise<boolean> {+ if (!isPlatformInitialized()) return Promise.resolve(false);+ return getPlatform().checkSession?.() ?? Promise.resolve(false);+}+/*** Whether this platform has a USABLE open data context — what a leaderboard* reads to hide itself honestly (web, native and the editor have none).diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 96f5ca2eb..8982c60e9 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -60,6 +60,9 @@ export {platformCanShare,platformShare,platformOnShareRequest,+ platformCanSignIn,+ platformLogin,+ platformCheckSession,platformCanOpenData,platformOpenDataPostMessage,platformOpenDataCanvas,diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex b4cb37df4..7281c8d72 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -186,6 +186,40 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {this.g_.onShareAppMessage?.call(this.g_, provide);}+ /** This one class serves every vendor, so it defines `login` regardless —+ * the honest answer is whether the host behind it has one. */+ canSignIn(): boolean {+ return this.g_.login !== undefined;+ }++ /** Begin a sign-in, as a promise. Rejects with the host's own words: this+ * is a network round trip and "it failed" without why is unactionable. */+ login(): Promise<string> {+ const begin = this.g_.login;+ if (!begin) return Promise.reject(new Error('this host has no sign-in'));+ return new Promise<string>((resolve, reject) => {+ begin.call(this.g_, {+ success: (res) => {+ // A host that answers success with no code has not signed+ // anyone in, whatever it says.+ if (res?.code) resolve(res.code);+ else reject(new Error('sign-in returned no code'));+ },+ fail: (err) => reject(new Error(`sign-in failed: ${JSON.stringify(err)}`)),+ });+ });+ }++ /** Whether the last sign-in is still current. The hosts answer by which+ * callback they call, so this is where that becomes a boolean. */+ checkSession(): Promise<boolean> {+ const check = this.g_.checkSession;+ if (!check) return Promise.resolve(false);+ return new Promise<boolean>((resolve) => {+ check.call(this.g_, { success: () => resolve(true), fail: () => resolve(false) });+ });+ }+/*** The open data context, resolved once and kept.*diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 9e2f6648d..b3c9f1b45 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -245,6 +245,17 @@ export interface MiniGameGlobal {* own menu. The host calls `cb` at share time, not at registration. */onShareAppMessage?(cb: () => MiniGameShareOptions): void;+ /** Begin a sign-in. The result is a one-time code the game's own server+ * exchanges — see the note on `PlatformAdapter.login`. */+ login?(opts: {+ success?: (res: { code: string }) => void;+ fail?: (err: unknown) => void;+ timeout?: number;+ }): void;+ /** Whether the host still regards the last sign-in as current. Reports the+ * answer by WHICH callback it calls, not by a value. */+ checkSession?(opts: { success?: () => void; fail?: (err: unknown) => void }): void;+/** The open data context, if this host has one. Absent on a host without* friend data, and on a game whose package declares no context directory. */getOpenDataContext?(): MiniGameOpenDataContext;diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 2a2a750af..6449fee8b 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -515,6 +515,25 @@ export interface PlatformAdapter {* as a texture. Null when the host has the capability but this game's* package declares no context to draw with. */openDataCanvas?(): PlatformCanvas | null;+ /**+ * Begin a host sign-in. Resolves with the one-time CODE, never a session:+ * turning a code into an identity needs the app secret, which must not be+ * in anything a player can open, so the exchange is the game's own server's+ * to make. A platform with no sign-in omits this.+ */+ login?(): Promise<string>;+ /**+ * Whether {@link login} would reach a real sign-in.+ *+ * Method presence is not a capability probe for a FAMILY adapter — one+ * class serves every mini-game vendor, so it defines `login` whether or not+ * the host behind it has one. An adapter that is one platform can omit this+ * and presence stands; a family answers for the host it actually wraps.+ */+ canSignIn?(): boolean;+ /** Whether the host still regards the last sign-in as current, so a game+ * can skip re-exchanging a code it does not need. */+ checkSession?(): Promise<boolean>;/** Write this player's own rows to the host's per-player cloud store — the* writable half of a leaderboard. Reading is the open data context's* alone, which is the whole reason that context exists. Returns whetherdiff --git a/sdk/src/services/identity.ts b/sdk/src/services/identity.tsnew file mode 100644index 000000000..9301339ff--- /dev/null+++ b/sdk/src/services/identity.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file identity.ts+ * @brief Host sign-in as an engine service — and the half the engine cannot do.+ *+ * A mini-game host signs a player in and hands back a one-time CODE. Turning+ * that code into an identity takes the app secret, and the app secret must+ * never be in anything a player can open, so the exchange belongs to the game's+ * own server. The engine's job ends at the code, and this API is shaped so that+ * is impossible to miss:+ *+ * `login()` resolves with `{ code }`, not a string and not a user. Destructuring+ * it makes the call site say the word `code`, which is the one thing that stops+ * `if (await Identity.login())` from reading like "I am now logged in".+ *+ * There is deliberately NO local provider here, unlike ads and the leaderboard.+ * A pretend ad is still a real pause and a pretend board is still the real+ * renderer, so rehearsing them is worth something. A pretend code is a string no+ * server can exchange — rehearsing with it means rehearsing a request that is+ * going to fail. Off-platform, `available` is false and a game takes whatever+ * path it takes when there is no account.+ */+import { defineResource } from '../ecs/resource';+import { platformCanSignIn, platformCheckSession, platformLogin } from '../platform';++/** What a sign-in yields: the code, and nothing that resembles a session. */+export interface LoginResult {+ /**+ * The host's one-time code. Send it to YOUR server, which exchanges it for+ * a session using the app secret. Short-lived and single-use: cache the+ * session your server returns, never this.+ */+ code: string;+}++export class IdentityAPI {+ /** Whether this platform can sign a player in at all — what a menu reads to+ * hide its sign-in button rather than offer one that cannot work. */+ get available(): boolean {+ return platformCanSignIn();+ }++ /**+ * Begin a sign-in.+ *+ * Rejects with the host's own words when it fails — this is a network round+ * trip, and "it failed" without a reason is not something a game can act on.+ * Rejects immediately where the platform has no sign-in, so a caller that+ * skipped {@link available} hears about it rather than hanging.+ */+ async login(): Promise<LoginResult> {+ return { code: await platformLogin() };+ }++ /**+ * Whether the host still regards the last sign-in as current.+ *+ * The reason to ask is to SKIP a login: if the session your server holds is+ * still good, exchanging a fresh code buys nothing. False where there is no+ * sign-in at all — there is nothing current about nothing.+ */+ sessionValid(): Promise<boolean> {+ return platformCheckSession();+ }+}++export const Identity = defineResource<IdentityAPI>(null!, 'Identity');diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsindex 77ecdbcec..6d7bfcc5b 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -10,4 +10,5 @@ export {type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,type LeaderboardStyle, type LocalLeaderboardOptions,} from './leaderboard';+export { Identity, IdentityAPI, type LoginResult } from './identity';export { ServicesPlugin, servicesPlugin } from './servicesPlugin';diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.tsindex 65ea35b7c..2be539239 100644--- a/sdk/src/services/servicesPlugin.ts+++ b/sdk/src/services/servicesPlugin.ts@@ -21,6 +21,7 @@ import { Schedule, defineSystem } from '../ecs/system';import { Ads, AdsAPI } from './ads';import { Share, ShareAPI } from './share';import { Leaderboard, LeaderboardAPI } from './leaderboard';+import { Identity, IdentityAPI } from './identity';export class ServicesPlugin implements Plugin {name = 'Services';@@ -36,6 +37,7 @@ export class ServicesPlugin implements Plugin {resumeAudio: () => app.getResource(Audio)?.resume(),}));app.insertResource(Share, new ShareAPI());+ app.insertResource(Identity, new IdentityAPI());// Resolved per call rather than captured: the module is attached by// connectCpp, which can run after the plugins have built.app.insertResource(Leaderboard, new LeaderboardAPI(() => app.wasmModule));diff --git a/sdk/tests/identity.test.ts b/sdk/tests/identity.test.tsnew file mode 100644index 000000000..4b7de10f0--- /dev/null+++ b/sdk/tests/identity.test.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Host sign-in, and the half the engine deliberately does not do.+ *+ * The code is not a session and the engine cannot make it one — the exchange+ * needs the app secret, which must never reach a client. So what is worth+ * pinning is that failure is loud and specific, that a platform without+ * sign-in says so instead of hanging, and that the result is shaped to be+ * called `code` at the call site.+ */+import { describe, it, expect } from 'vitest';+import { IdentityAPI } from '../src/services/identity';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import { setPlatform } from '../src/platform/base';+import type { MiniGameGlobal, MiniGameProfile } from '../src/platform/minigame/api';+import type { PlatformAdapter } from '../src/platform/types';++function miniGame(patch: Partial<MiniGameGlobal>): IdentityAPI {+ const profile: MiniGameProfile = {+ id: 'wechat',+ hostLabel: 'Test',+ global: {+ getSystemInfoSync: () => ({ pixelRatio: 1, screenWidth: 1, screenHeight: 1, platform: 'devtools', language: 'zh_CN' }),+ ...patch,+ } as unknown as MiniGameGlobal,+ };+ setPlatform(new MiniGamePlatformAdapter(profile));+ return new IdentityAPI();+}++/** A platform with no mini-game host behind it at all — web, native, tests. */+function bare(): IdentityAPI {+ setPlatform({ name: 'web', devicePixelRatio: () => 1 } as unknown as PlatformAdapter);+ return new IdentityAPI();+}++describe('available', () => {+ it('is true on a host that can sign in', () => {+ expect(miniGame({ login: (o) => o.success?.({ code: 'c' }) }).available).toBe(true);+ });++ it('is false on a mini-game host without the call', () => {+ expect(miniGame({}).available).toBe(false);+ });++ it('is false off-platform', () => {+ expect(bare().available).toBe(false);+ });+});++describe('login', () => {+ it('resolves with the code, named as one', async () => {+ const id = miniGame({ login: (o) => o.success?.({ code: 'oc-123' }) });+ const { code } = await id.login();+ expect(code).toBe('oc-123');+ });++ it('rejects with the host\'s own words, because a round trip that failed for an unknown reason is unactionable', async () => {+ const id = miniGame({ login: (o) => o.fail?.({ errMsg: 'login:fail no network' }) });+ await expect(id.login()).rejects.toThrow(/no network/);+ });++ it('treats a success with no code as a failure — nobody was signed in', async () => {+ const id = miniGame({ login: (o) => (o.success as (r: { code: string }) => void)?.({} as { code: string }) });+ await expect(id.login()).rejects.toThrow(/no code/);+ });++ it('rejects rather than hanging where there is no sign-in', async () => {+ // A caller that skipped `available` has to hear about it: a promise that+ // never settles is a game stuck on its own loading screen.+ await expect(bare().login()).rejects.toThrow(/no sign-in/);+ await expect(miniGame({}).login()).rejects.toThrow(/no sign-in/);+ });+});++describe('sessionValid', () => {+ // The hosts answer by WHICH callback they call, not with a value — this is+ // the layer that turns that into a boolean.+ it('is true when the host calls success', async () => {+ const id = miniGame({ checkSession: (o) => o.success?.() });+ await expect(id.sessionValid()).resolves.toBe(true);+ });++ it('is false when the host calls fail', async () => {+ const id = miniGame({ checkSession: (o) => o.fail?.({}) });+ await expect(id.sessionValid()).resolves.toBe(false);+ });++ it('is false where there is no session to be current', async () => {+ await expect(miniGame({}).sessionValid()).resolves.toBe(false);+ await expect(bare().sessionValid()).resolves.toBe(false);+ });+});