@totop/platform-sdk 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI-INTEGRATION.md +17 -0
- package/README.md +45 -0
- package/bin/totop-auth.mjs +57 -0
- package/dist/core.d.ts +99 -0
- package/dist/index.d.ts +22 -0
- package/dist/totop-platform.esm.js +432 -0
- package/dist/totop-platform.global.js +457 -0
- package/package.json +12 -0
- package/schema/totop.auth.schema.json +19 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# ToTop Platform SDK AI integration contract
|
|
2
|
+
|
|
3
|
+
Follow these instructions exactly when integrating ToTop authentication with Cursor, Codex, or another coding agent.
|
|
4
|
+
|
|
5
|
+
1. Install the exact reviewed version of `@totop/platform-sdk` supplied by ToTop.
|
|
6
|
+
2. Copy the supplied `totop.auth.json` to the application's public root. Do not edit its `clientId`, URLs, type, scopes, or minimum SDK version.
|
|
7
|
+
3. Import `ToTop` and call `await ToTop.init('/totop.auth.json')` once during application startup. This call also completes an OAuth callback when `code` and `state` are present.
|
|
8
|
+
4. Call `await ToTop.login()` when the user chooses to sign in. Do not implement OAuth, PKCE, token exchange, refresh, or callback parsing yourself.
|
|
9
|
+
5. Read the display profile with `ToTop.getUser()`.
|
|
10
|
+
6. Call `ToTop.authorizedFetch()` for ToTop protected APIs. Never manually add a bearer token unless implementing a reviewed server integration.
|
|
11
|
+
7. For a game, use `ToTop.cloudSave.save/load/list/restore`; do not call the save API or implement revision handling manually. Handle `ToTopCloudSaveConflictError` without silently overwriting its `currentSave`.
|
|
12
|
+
8. Call `await ToTop.logout()` for normal sign-out. Only call `logout({ global: true })` from a separate, explicit “Sign out everywhere” action.
|
|
13
|
+
9. Never place access tokens, refresh tokens, authorization codes, client secrets, private keys, or save payloads in URLs, logs, analytics, or error reports. Do not place auth tokens in `localStorage`.
|
|
14
|
+
10. Do not add a client secret to browser code. Browser apps and games are public PKCE clients.
|
|
15
|
+
11. Run `npx totop-platform verify` and resolve every failure before delivery.
|
|
16
|
+
|
|
17
|
+
The application must not silently authorize after local sign-out. A signed-in ToTop browser session may skip credential entry only after the user chooses the application’s sign-in action.
|
package/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @totop/platform-sdk
|
|
2
|
+
|
|
3
|
+
Browser SDK for reviewed ToTop applications and games. It provides unified identity, protected API access, cloud saves, token rotation, and local/global logout separation.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @totop/platform-sdk@1.1.0
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { ToTop } from '@totop/platform-sdk'
|
|
11
|
+
|
|
12
|
+
await ToTop.init('/totop.auth.json')
|
|
13
|
+
await ToTop.login()
|
|
14
|
+
|
|
15
|
+
const user = ToTop.getUser()
|
|
16
|
+
|
|
17
|
+
// Games get cloud save without implementing HTTP, tokens or revision handling.
|
|
18
|
+
const save = await ToTop.cloudSave.save({ level: 4, score: 1200 })
|
|
19
|
+
await ToTop.cloudSave.restore((payload) => game.restore(payload))
|
|
20
|
+
|
|
21
|
+
// Use authorizedFetch only for other reviewed ToTop APIs.
|
|
22
|
+
const response = await ToTop.authorizedFetch('https://api.totop.ai/game-api/games/ID/custom-resource')
|
|
23
|
+
await ToTop.logout()
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The reviewed `totop.auth.json` is public configuration and contains no secret. Access tokens stay in memory; rotating refresh tokens are limited to the current browser tab's `sessionStorage` for at most eight hours.
|
|
27
|
+
|
|
28
|
+
## Cloud save (game clients)
|
|
29
|
+
|
|
30
|
+
`ToTop.cloudSave` is available only when `totop.auth.json` has `type: "game"` and a reviewed `game:<uuid>` client.
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
const saved = await ToTop.cloudSave.save(state, {
|
|
34
|
+
slot: 0, // 0-9; default 0
|
|
35
|
+
schemaVersion: 1, // default 1
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
const cloud = await ToTop.cloudSave.load(0) // null when the slot is empty
|
|
39
|
+
const all = await ToTop.cloudSave.list()
|
|
40
|
+
await ToTop.cloudSave.restore((payload, save) => game.restore(payload), 0)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The SDK remembers each loaded revision and sends the correct optimistic-concurrency value automatically. A concurrent write throws `ToTopCloudSaveConflictError`, whose `currentSave` is the authoritative cloud copy. A save payload must be a JSON object and is limited to 1 MiB per slot.
|
|
44
|
+
|
|
45
|
+
Run `npx totop-platform verify` in the integrating project before publishing.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, readdir } from 'node:fs/promises'
|
|
3
|
+
import { resolve, relative, extname } from 'node:path'
|
|
4
|
+
|
|
5
|
+
const args = process.argv.slice(2)
|
|
6
|
+
if (args[0] !== 'verify') {
|
|
7
|
+
console.error('Usage: totop-platform verify [--config public/totop.auth.json] [--root .] [--json]')
|
|
8
|
+
process.exit(2)
|
|
9
|
+
}
|
|
10
|
+
function option(name, fallback) { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : fallback }
|
|
11
|
+
const root = resolve(option('--root', '.'))
|
|
12
|
+
const configPath = resolve(root, option('--config', 'public/totop.auth.json'))
|
|
13
|
+
const jsonOutput = args.includes('--json')
|
|
14
|
+
const results = []
|
|
15
|
+
function result(name, ok, detail = '') { results.push({ name, ok, detail }) }
|
|
16
|
+
function exactHttps(value, originOnly = false) { try { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password && !url.hash && (!originOnly || url.href === `${url.origin}/`) } catch { return false } }
|
|
17
|
+
|
|
18
|
+
let config
|
|
19
|
+
try { config = JSON.parse(await readFile(configPath, 'utf8')); result('config_file', true, relative(root, configPath)) } catch (error) { result('config_file', false, error instanceof Error ? error.message : String(error)) }
|
|
20
|
+
if (config) {
|
|
21
|
+
const game = /^game:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(config.clientId)
|
|
22
|
+
const app = /^app:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(config.clientId)
|
|
23
|
+
result('client_id', config.type === 'game' ? game : config.type === 'app' && app, String(config.clientId ?? 'missing'))
|
|
24
|
+
result('https_urls', exactHttps(config.issuer, true) && exactHttps(config.redirectUri) && exactHttps(config.apiOrigin, true), 'issuer, redirectUri and apiOrigin must be exact HTTPS values')
|
|
25
|
+
const scopes = config.type === 'game' ? 'openid profile game:save' : 'openid profile'
|
|
26
|
+
result('scopes', Array.isArray(config.scopes) && config.scopes.join(' ') === scopes, scopes)
|
|
27
|
+
result('sdk_version', /^\d+\.\d+\.\d+$/.test(config.minimumSdkVersion), String(config.minimumSdkVersion ?? 'missing'))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const pkg = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'))
|
|
32
|
+
const dependencies = { ...pkg.dependencies, ...pkg.devDependencies }
|
|
33
|
+
result('sdk_dependency', typeof dependencies['@totop/platform-sdk'] === 'string', '@totop/platform-sdk')
|
|
34
|
+
} catch { result('sdk_dependency', false, 'package.json not found') }
|
|
35
|
+
|
|
36
|
+
const sourceFiles = []
|
|
37
|
+
async function walk(directory) {
|
|
38
|
+
let entries
|
|
39
|
+
try { entries = await readdir(directory, { withFileTypes: true }) } catch { return }
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
if (['node_modules', 'dist', 'build', '.git', '.next', 'coverage'].includes(entry.name)) continue
|
|
42
|
+
const path = resolve(directory, entry.name)
|
|
43
|
+
if (entry.isDirectory()) await walk(path)
|
|
44
|
+
else if (['.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html'].includes(extname(entry.name))) sourceFiles.push(path)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
for (const name of ['src', 'app', 'pages']) await walk(resolve(root, name))
|
|
48
|
+
const sources = (await Promise.all(sourceFiles.map(async path => ({ path, text: await readFile(path, 'utf8') })))).filter(item => item.text)
|
|
49
|
+
const joined = sources.map(item => item.text).join('\n')
|
|
50
|
+
result('sdk_initialization', /ToTop\s*\.\s*init\s*\(/.test(joined), 'call ToTop.init() during application startup')
|
|
51
|
+
result('authorized_fetch', /authorizedFetch\s*\(|cloudSave\s*\./.test(joined), 'use authorizedFetch() or cloudSave for ToTop protected APIs')
|
|
52
|
+
const unsafe = sources.filter(item => /localStorage[^\n]*(?:access|refresh|token)|(?:access_token|refresh_token)[^\n]*(?:searchParams|location\.(?:href|search))|console\.(?:log|info|warn|error)[^\n]*(?:accessToken|refreshToken|token)/i.test(item.text))
|
|
53
|
+
result('token_safety', unsafe.length === 0, unsafe.map(item => relative(root, item.path)).join(', '))
|
|
54
|
+
|
|
55
|
+
if (jsonOutput) console.log(JSON.stringify({ ok: results.every(item => item.ok), results }, null, 2))
|
|
56
|
+
else for (const item of results) console.log(`${item.ok ? 'PASS' : 'FAIL'} ${item.name}${item.detail ? `: ${item.detail}` : ''}`)
|
|
57
|
+
process.exit(results.every(item => item.ok) ? 0 : 1)
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export declare const PLATFORM_SDK_VERSION = "1.1.0";
|
|
2
|
+
export type ToTopPlatformConfig = {
|
|
3
|
+
version: 1;
|
|
4
|
+
clientId: string;
|
|
5
|
+
type: 'app' | 'game';
|
|
6
|
+
issuer: string;
|
|
7
|
+
redirectUri: string;
|
|
8
|
+
apiOrigin: string;
|
|
9
|
+
scopes: string[];
|
|
10
|
+
minimumSdkVersion: string;
|
|
11
|
+
};
|
|
12
|
+
export type ToTopUser = {
|
|
13
|
+
id: string;
|
|
14
|
+
nickname: string;
|
|
15
|
+
avatarUrl: string;
|
|
16
|
+
};
|
|
17
|
+
export type ToTopCloudSave<T extends Record<string, unknown> = Record<string, unknown>> = {
|
|
18
|
+
id: string;
|
|
19
|
+
gameId: string;
|
|
20
|
+
slot: number;
|
|
21
|
+
payload: T;
|
|
22
|
+
schemaVersion: number;
|
|
23
|
+
revision: number;
|
|
24
|
+
createdAt: string;
|
|
25
|
+
updatedAt: string;
|
|
26
|
+
};
|
|
27
|
+
export type ToTopCloudSaveOptions = {
|
|
28
|
+
slot?: number;
|
|
29
|
+
schemaVersion?: number;
|
|
30
|
+
baseRevision?: number;
|
|
31
|
+
};
|
|
32
|
+
export declare class ToTopCloudSaveConflictError<T extends Record<string, unknown> = Record<string, unknown>> extends Error {
|
|
33
|
+
readonly currentSave: ToTopCloudSave<T> | null;
|
|
34
|
+
readonly code = "revision_conflict";
|
|
35
|
+
constructor(currentSave: ToTopCloudSave<T> | null);
|
|
36
|
+
}
|
|
37
|
+
export interface TabStorage {
|
|
38
|
+
getItem(key: string): string | null;
|
|
39
|
+
setItem(key: string, value: string): void;
|
|
40
|
+
removeItem(key: string): void;
|
|
41
|
+
}
|
|
42
|
+
export declare class MemoryTabStorage implements TabStorage {
|
|
43
|
+
private readonly map;
|
|
44
|
+
getItem(key: string): string | null;
|
|
45
|
+
setItem(key: string, value: string): void;
|
|
46
|
+
removeItem(key: string): void;
|
|
47
|
+
keys(): string[];
|
|
48
|
+
values(): string[];
|
|
49
|
+
}
|
|
50
|
+
type Dependencies = {
|
|
51
|
+
storage: TabStorage;
|
|
52
|
+
fetch?: typeof fetch;
|
|
53
|
+
navigate?: (url: string) => void;
|
|
54
|
+
replaceUrl?: (url: string) => void;
|
|
55
|
+
currentUrl?: () => string;
|
|
56
|
+
randomBytes?: (length: number) => Uint8Array;
|
|
57
|
+
digest?: (input: Uint8Array) => Promise<Uint8Array>;
|
|
58
|
+
now?: () => number;
|
|
59
|
+
};
|
|
60
|
+
export declare function validateConfig(value: unknown): ToTopPlatformConfig;
|
|
61
|
+
export declare class ToTopPlatformClient {
|
|
62
|
+
private readonly deps;
|
|
63
|
+
private config?;
|
|
64
|
+
private accessToken?;
|
|
65
|
+
private accessExpiresAt;
|
|
66
|
+
private user?;
|
|
67
|
+
private refreshFlight?;
|
|
68
|
+
private readonly cloudSaveRevisions;
|
|
69
|
+
private generation;
|
|
70
|
+
private readonly controllers;
|
|
71
|
+
private readonly fetcher;
|
|
72
|
+
constructor(deps: Dependencies);
|
|
73
|
+
private key;
|
|
74
|
+
private now;
|
|
75
|
+
private current;
|
|
76
|
+
private abortAll;
|
|
77
|
+
private clearState;
|
|
78
|
+
private resource;
|
|
79
|
+
private requireConfig;
|
|
80
|
+
private requireGame;
|
|
81
|
+
private parseCloudSave;
|
|
82
|
+
init(input?: ToTopPlatformConfig | string): Promise<this>;
|
|
83
|
+
handleCallback(): Promise<boolean>;
|
|
84
|
+
login(): Promise<void>;
|
|
85
|
+
requireLogin(): Promise<void>;
|
|
86
|
+
getUser(): ToTopUser | null;
|
|
87
|
+
getAccessToken(): Promise<string>;
|
|
88
|
+
authorizedFetch(input: string | URL, init?: RequestInit): Promise<Response>;
|
|
89
|
+
listCloudSaves<T extends Record<string, unknown> = Record<string, unknown>>(): Promise<ToTopCloudSave<T>[]>;
|
|
90
|
+
loadCloudSave<T extends Record<string, unknown> = Record<string, unknown>>(slot?: number): Promise<ToTopCloudSave<T> | null>;
|
|
91
|
+
saveCloudSave<T extends Record<string, unknown>>(payload: T, options?: ToTopCloudSaveOptions): Promise<ToTopCloudSave<T>>;
|
|
92
|
+
restoreCloudSave<T extends Record<string, unknown> = Record<string, unknown>>(apply: (payload: T, save: ToTopCloudSave<T>) => void | Promise<void>, slot?: number): Promise<ToTopCloudSave<T> | null>;
|
|
93
|
+
logout(input?: {
|
|
94
|
+
global?: boolean;
|
|
95
|
+
}): Promise<void>;
|
|
96
|
+
private refresh;
|
|
97
|
+
private exchange;
|
|
98
|
+
}
|
|
99
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type ToTopPlatformConfig } from './core.js';
|
|
2
|
+
export declare const ToTop: {
|
|
3
|
+
version: string;
|
|
4
|
+
init: (input?: ToTopPlatformConfig | string) => Promise</*elided*/ any>;
|
|
5
|
+
handleCallback: () => Promise<boolean>;
|
|
6
|
+
login: () => Promise<void>;
|
|
7
|
+
requireLogin: () => Promise<void>;
|
|
8
|
+
getUser: () => import("./core.js").ToTopUser | null;
|
|
9
|
+
getAccessToken: () => Promise<string>;
|
|
10
|
+
authorizedFetch: (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
11
|
+
cloudSave: {
|
|
12
|
+
list: <T extends Record<string, unknown> = Record<string, unknown>>() => Promise<import("./core.js").ToTopCloudSave<T>[]>;
|
|
13
|
+
load: <T extends Record<string, unknown> = Record<string, unknown>>(slot?: number) => Promise<import("./core.js").ToTopCloudSave<T> | null>;
|
|
14
|
+
save: <T extends Record<string, unknown>>(payload: T, options?: import("./core.js").ToTopCloudSaveOptions) => Promise<import("./core.js").ToTopCloudSave<T>>;
|
|
15
|
+
restore: <T extends Record<string, unknown> = Record<string, unknown>>(apply: (payload: T, save: import("./core.js").ToTopCloudSave<T>) => void | Promise<void>, slot?: number) => Promise<import("./core.js").ToTopCloudSave<T> | null>;
|
|
16
|
+
};
|
|
17
|
+
logout: (input?: {
|
|
18
|
+
global?: boolean;
|
|
19
|
+
}) => Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
export { ToTopPlatformClient, PLATFORM_SDK_VERSION, MemoryTabStorage, ToTopCloudSaveConflictError, validateConfig } from './core.js';
|
|
22
|
+
export type { ToTopPlatformConfig, ToTopCloudSave, ToTopCloudSaveOptions, ToTopUser, TabStorage } from './core.js';
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// packages/auth-sdk/src/core.ts
|
|
2
|
+
var PLATFORM_SDK_VERSION = "1.1.0";
|
|
3
|
+
var CONFIG_VERSION = 1;
|
|
4
|
+
var MAX_CLOUD_SAVE_BYTES = 1024 * 1024;
|
|
5
|
+
var SESSION_PREFIX = "totop:auth-sdk:";
|
|
6
|
+
var GAME_ID = /^game:([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i;
|
|
7
|
+
var APP_ID = /^app:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
8
|
+
var ToTopCloudSaveConflictError = class extends Error {
|
|
9
|
+
constructor(currentSave) {
|
|
10
|
+
super("Cloud save revision conflict");
|
|
11
|
+
this.currentSave = currentSave;
|
|
12
|
+
this.name = "ToTopCloudSaveConflictError";
|
|
13
|
+
}
|
|
14
|
+
currentSave;
|
|
15
|
+
code = "revision_conflict";
|
|
16
|
+
};
|
|
17
|
+
var MemoryTabStorage = class {
|
|
18
|
+
map = /* @__PURE__ */ new Map();
|
|
19
|
+
getItem(key) {
|
|
20
|
+
return this.map.get(key) ?? null;
|
|
21
|
+
}
|
|
22
|
+
setItem(key, value) {
|
|
23
|
+
this.map.set(key, value);
|
|
24
|
+
}
|
|
25
|
+
removeItem(key) {
|
|
26
|
+
this.map.delete(key);
|
|
27
|
+
}
|
|
28
|
+
keys() {
|
|
29
|
+
return [...this.map.keys()];
|
|
30
|
+
}
|
|
31
|
+
values() {
|
|
32
|
+
return [...this.map.values()];
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
function b64url(bytes) {
|
|
36
|
+
const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
|
|
37
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
38
|
+
}
|
|
39
|
+
function random(length) {
|
|
40
|
+
const bytes = new Uint8Array(length);
|
|
41
|
+
crypto.getRandomValues(bytes);
|
|
42
|
+
return bytes;
|
|
43
|
+
}
|
|
44
|
+
function semver(value) {
|
|
45
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(value);
|
|
46
|
+
return match?.slice(1).map(Number);
|
|
47
|
+
}
|
|
48
|
+
function atLeast(actual, minimum) {
|
|
49
|
+
const a = semver(actual);
|
|
50
|
+
const m = semver(minimum);
|
|
51
|
+
if (!a || !m) return false;
|
|
52
|
+
for (let index = 0; index < 3; index++) {
|
|
53
|
+
if (a[index] > m[index]) return true;
|
|
54
|
+
if (a[index] < m[index]) return false;
|
|
55
|
+
}
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
function exactHttps(value, label, originOnly = false) {
|
|
59
|
+
if (typeof value !== "string") throw new Error(`${label} must be a string`);
|
|
60
|
+
const url = new URL(value);
|
|
61
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash || originOnly && url.href !== `${url.origin}/`) throw new Error(`${label} must be an exact HTTPS ${originOnly ? "origin" : "URL"}`);
|
|
62
|
+
return originOnly ? url.origin : url.href;
|
|
63
|
+
}
|
|
64
|
+
function exactScopes(type, value) {
|
|
65
|
+
const expected = type === "game" ? ["openid", "profile", "game:save"] : ["openid", "profile"];
|
|
66
|
+
if (!Array.isArray(value) || value.length !== expected.length || value.some((scope, index) => scope !== expected[index])) throw new Error(`scopes must equal ${expected.join(" ")}`);
|
|
67
|
+
return expected;
|
|
68
|
+
}
|
|
69
|
+
function cloudSaveSlot(value) {
|
|
70
|
+
if (!Number.isInteger(value) || value < 0 || value > 9) throw new Error("cloud save slot must be an integer from 0 to 9");
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
function cloudSaveSchemaVersion(value) {
|
|
74
|
+
if (!Number.isInteger(value) || value < 1) throw new Error("cloud save schemaVersion must be an integer >= 1");
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
function cloudSaveRevision(value) {
|
|
78
|
+
if (!Number.isInteger(value) || value < 0) throw new Error("cloud save baseRevision must be an integer >= 0");
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function isObject(value) {
|
|
82
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
83
|
+
}
|
|
84
|
+
function validateConfig(value) {
|
|
85
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("ToTop platform config must be an object");
|
|
86
|
+
const input = value;
|
|
87
|
+
const allowed = ["$schema", "version", "clientId", "type", "issuer", "redirectUri", "apiOrigin", "scopes", "minimumSdkVersion"];
|
|
88
|
+
if (Object.keys(input).some((key) => !allowed.includes(key))) throw new Error("ToTop platform config contains an unknown property");
|
|
89
|
+
if (input.version !== CONFIG_VERSION) throw new Error("unsupported ToTop platform config version");
|
|
90
|
+
if (input.type !== "app" && input.type !== "game") throw new Error("type must be app or game");
|
|
91
|
+
if (typeof input.clientId !== "string" || (input.type === "app" ? !APP_ID.test(input.clientId) : !GAME_ID.test(input.clientId))) throw new Error(`invalid ${input.type} clientId`);
|
|
92
|
+
if (!semver(String(input.minimumSdkVersion)) || !atLeast(PLATFORM_SDK_VERSION, String(input.minimumSdkVersion))) throw new Error("SDK upgrade required");
|
|
93
|
+
return {
|
|
94
|
+
version: 1,
|
|
95
|
+
clientId: input.clientId,
|
|
96
|
+
type: input.type,
|
|
97
|
+
issuer: exactHttps(input.issuer, "issuer", true),
|
|
98
|
+
redirectUri: exactHttps(input.redirectUri, "redirectUri"),
|
|
99
|
+
apiOrigin: exactHttps(input.apiOrigin, "apiOrigin", true),
|
|
100
|
+
scopes: exactScopes(input.type, input.scopes),
|
|
101
|
+
minimumSdkVersion: String(input.minimumSdkVersion)
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
var ToTopPlatformClient = class {
|
|
105
|
+
constructor(deps) {
|
|
106
|
+
this.deps = deps;
|
|
107
|
+
this.fetcher = deps.fetch ?? fetch;
|
|
108
|
+
}
|
|
109
|
+
deps;
|
|
110
|
+
config;
|
|
111
|
+
accessToken;
|
|
112
|
+
accessExpiresAt = 0;
|
|
113
|
+
user;
|
|
114
|
+
refreshFlight;
|
|
115
|
+
cloudSaveRevisions = /* @__PURE__ */ new Map();
|
|
116
|
+
generation = 0;
|
|
117
|
+
controllers = /* @__PURE__ */ new Set();
|
|
118
|
+
fetcher;
|
|
119
|
+
key(part) {
|
|
120
|
+
return `${SESSION_PREFIX}${this.config?.clientId ?? "uninitialized"}:${part}`;
|
|
121
|
+
}
|
|
122
|
+
now() {
|
|
123
|
+
return this.deps.now?.() ?? Date.now();
|
|
124
|
+
}
|
|
125
|
+
current(value) {
|
|
126
|
+
return value === this.generation;
|
|
127
|
+
}
|
|
128
|
+
abortAll() {
|
|
129
|
+
for (const controller of this.controllers) controller.abort();
|
|
130
|
+
this.controllers.clear();
|
|
131
|
+
}
|
|
132
|
+
clearState() {
|
|
133
|
+
this.generation++;
|
|
134
|
+
this.abortAll();
|
|
135
|
+
this.accessToken = void 0;
|
|
136
|
+
this.accessExpiresAt = 0;
|
|
137
|
+
this.user = void 0;
|
|
138
|
+
this.refreshFlight = void 0;
|
|
139
|
+
this.cloudSaveRevisions.clear();
|
|
140
|
+
if (this.config) for (const part of ["refresh", "family_expires", "state", "verifier"]) this.deps.storage.removeItem(this.key(part));
|
|
141
|
+
}
|
|
142
|
+
resource(config = this.requireConfig()) {
|
|
143
|
+
const match = GAME_ID.exec(config.clientId);
|
|
144
|
+
return new URL(match ? `/resources/games/${match[1]}` : `/resources/apps/${encodeURIComponent(config.clientId)}`, config.issuer).href;
|
|
145
|
+
}
|
|
146
|
+
requireConfig() {
|
|
147
|
+
if (!this.config) throw new Error("ToTop.init is required");
|
|
148
|
+
return this.config;
|
|
149
|
+
}
|
|
150
|
+
requireGame() {
|
|
151
|
+
const config = this.requireConfig();
|
|
152
|
+
const match = GAME_ID.exec(config.clientId);
|
|
153
|
+
if (!match) throw new Error("cloudSave is only available to reviewed game clients");
|
|
154
|
+
return { config, gameId: match[1] };
|
|
155
|
+
}
|
|
156
|
+
parseCloudSave(value) {
|
|
157
|
+
if (!isObject(value) || typeof value.id !== "string" || typeof value.game_id !== "string" || !Number.isInteger(value.slot) || !isObject(value.payload) || !Number.isInteger(value.schema_version) || !Number.isInteger(value.revision) || typeof value.created_at !== "string" || typeof value.updated_at !== "string") {
|
|
158
|
+
throw new Error("invalid cloud save response");
|
|
159
|
+
}
|
|
160
|
+
const save = {
|
|
161
|
+
id: value.id,
|
|
162
|
+
gameId: value.game_id,
|
|
163
|
+
slot: value.slot,
|
|
164
|
+
payload: value.payload,
|
|
165
|
+
schemaVersion: value.schema_version,
|
|
166
|
+
revision: value.revision,
|
|
167
|
+
createdAt: value.created_at,
|
|
168
|
+
updatedAt: value.updated_at
|
|
169
|
+
};
|
|
170
|
+
this.cloudSaveRevisions.set(save.slot, save.revision);
|
|
171
|
+
return save;
|
|
172
|
+
}
|
|
173
|
+
async init(input = "/totop.auth.json") {
|
|
174
|
+
const raw = typeof input === "string" ? await this.fetcher(new URL(input, this.deps.currentUrl?.() ?? location.href), { credentials: "same-origin", redirect: "error" }).then(async (response) => {
|
|
175
|
+
if (!response.ok) throw new Error("Unable to load ToTop auth config");
|
|
176
|
+
return response.json();
|
|
177
|
+
}) : input;
|
|
178
|
+
const next = validateConfig(raw);
|
|
179
|
+
if (this.config && this.config.clientId !== next.clientId) this.clearState();
|
|
180
|
+
this.config = next;
|
|
181
|
+
const completedCallback = await this.handleCallback();
|
|
182
|
+
if (!completedCallback && this.deps.storage.getItem(this.key("refresh"))) {
|
|
183
|
+
try {
|
|
184
|
+
await this.refresh(false, true);
|
|
185
|
+
} catch {
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return this;
|
|
189
|
+
}
|
|
190
|
+
async handleCallback() {
|
|
191
|
+
const config = this.requireConfig();
|
|
192
|
+
const current = new URL(this.deps.currentUrl?.() ?? location.href);
|
|
193
|
+
if (!current.searchParams.has("code") && !current.searchParams.has("error")) return false;
|
|
194
|
+
const code = current.searchParams.get("code");
|
|
195
|
+
const state = current.searchParams.get("state");
|
|
196
|
+
const expected = this.deps.storage.getItem(this.key("state"));
|
|
197
|
+
const verifier = this.deps.storage.getItem(this.key("verifier"));
|
|
198
|
+
for (const key of ["code", "state", "error", "error_description", "iss"]) current.searchParams.delete(key);
|
|
199
|
+
this.deps.replaceUrl?.(current.href);
|
|
200
|
+
this.deps.storage.removeItem(this.key("state"));
|
|
201
|
+
this.deps.storage.removeItem(this.key("verifier"));
|
|
202
|
+
if (!code || !state || state !== expected || !verifier) {
|
|
203
|
+
this.clearState();
|
|
204
|
+
throw new Error("invalid OAuth callback state");
|
|
205
|
+
}
|
|
206
|
+
const generation = this.generation;
|
|
207
|
+
try {
|
|
208
|
+
await this.exchange(new URLSearchParams({ grant_type: "authorization_code", client_id: config.clientId, resource: this.resource(), code, redirect_uri: config.redirectUri, code_verifier: verifier }), generation, true);
|
|
209
|
+
return true;
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (this.current(generation)) this.clearState();
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async login() {
|
|
216
|
+
return this.requireLogin();
|
|
217
|
+
}
|
|
218
|
+
async requireLogin() {
|
|
219
|
+
const config = this.requireConfig();
|
|
220
|
+
if (this.accessToken && this.accessExpiresAt > this.now() + 5e3) return;
|
|
221
|
+
const verifier = b64url((this.deps.randomBytes ?? random)(32));
|
|
222
|
+
const state = b64url((this.deps.randomBytes ?? random)(24));
|
|
223
|
+
const digest = this.deps.digest ?? (async (value) => new Uint8Array(await crypto.subtle.digest("SHA-256", value)));
|
|
224
|
+
const generation = this.generation;
|
|
225
|
+
const challenge = b64url(await digest(new TextEncoder().encode(verifier)));
|
|
226
|
+
if (!this.current(generation)) return;
|
|
227
|
+
this.deps.storage.setItem(this.key("verifier"), verifier);
|
|
228
|
+
this.deps.storage.setItem(this.key("state"), state);
|
|
229
|
+
let url;
|
|
230
|
+
const game = GAME_ID.exec(config.clientId);
|
|
231
|
+
if (game) {
|
|
232
|
+
url = new URL(`/launch/${game[1]}`, config.issuer);
|
|
233
|
+
url.search = new URLSearchParams({ redirect_uri: config.redirectUri, origin: new URL(config.redirectUri).origin, state, code_challenge: challenge, code_challenge_method: "S256", sdk_version: PLATFORM_SDK_VERSION }).toString();
|
|
234
|
+
} else {
|
|
235
|
+
url = new URL("/oauth/authorize", config.issuer);
|
|
236
|
+
url.search = new URLSearchParams({ client_id: config.clientId, response_type: "code", redirect_uri: config.redirectUri, scope: config.scopes.join(" "), resource: this.resource(), state, code_challenge: challenge, code_challenge_method: "S256" }).toString();
|
|
237
|
+
}
|
|
238
|
+
;
|
|
239
|
+
(this.deps.navigate ?? ((target) => location.assign(target)))(url.href);
|
|
240
|
+
}
|
|
241
|
+
getUser() {
|
|
242
|
+
return this.user ?? null;
|
|
243
|
+
}
|
|
244
|
+
async getAccessToken() {
|
|
245
|
+
if (!this.accessToken || this.accessExpiresAt <= this.now() + 5e3) await this.refresh();
|
|
246
|
+
if (!this.accessToken) throw new Error("login required");
|
|
247
|
+
return this.accessToken;
|
|
248
|
+
}
|
|
249
|
+
async authorizedFetch(input, init = {}) {
|
|
250
|
+
const config = this.requireConfig();
|
|
251
|
+
const url = new URL(input.toString(), config.apiOrigin);
|
|
252
|
+
if (url.origin !== config.apiOrigin) throw new Error("authorizedFetch origin is not allowed");
|
|
253
|
+
const generation = this.generation;
|
|
254
|
+
const controller = new AbortController();
|
|
255
|
+
this.controllers.add(controller);
|
|
256
|
+
const run = async () => this.fetcher(url, { ...init, signal: controller.signal, redirect: "manual", referrerPolicy: "no-referrer", headers: { ...Object.fromEntries(new Headers(init.headers).entries()), Authorization: `Bearer ${await this.getAccessToken()}` } });
|
|
257
|
+
try {
|
|
258
|
+
let response = await run();
|
|
259
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
260
|
+
if (response.status === 401) {
|
|
261
|
+
await this.refresh(true);
|
|
262
|
+
response = await run();
|
|
263
|
+
}
|
|
264
|
+
if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) throw new Error("authenticated cross-origin redirects are forbidden");
|
|
265
|
+
return response;
|
|
266
|
+
} finally {
|
|
267
|
+
this.controllers.delete(controller);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async listCloudSaves() {
|
|
271
|
+
const { gameId } = this.requireGame();
|
|
272
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves`);
|
|
273
|
+
if (!response.ok) throw new Error(`cloud save list failed (${response.status})`);
|
|
274
|
+
const body = await response.json();
|
|
275
|
+
if (!Array.isArray(body.saves)) throw new Error("invalid cloud save list response");
|
|
276
|
+
return body.saves.map((save) => this.parseCloudSave(save));
|
|
277
|
+
}
|
|
278
|
+
async loadCloudSave(slot = 0) {
|
|
279
|
+
const { gameId } = this.requireGame();
|
|
280
|
+
const selectedSlot = cloudSaveSlot(slot);
|
|
281
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves/${selectedSlot}`);
|
|
282
|
+
if (response.status === 404) {
|
|
283
|
+
this.cloudSaveRevisions.delete(selectedSlot);
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
if (!response.ok) throw new Error(`cloud save load failed (${response.status})`);
|
|
287
|
+
const body = await response.json();
|
|
288
|
+
return this.parseCloudSave(body.save);
|
|
289
|
+
}
|
|
290
|
+
async saveCloudSave(payload, options = {}) {
|
|
291
|
+
if (!isObject(payload)) throw new Error("cloud save payload must be a JSON object");
|
|
292
|
+
const serialized = JSON.stringify(payload);
|
|
293
|
+
if (typeof serialized !== "string") throw new Error("cloud save payload must be JSON serializable");
|
|
294
|
+
if (new TextEncoder().encode(serialized).byteLength > MAX_CLOUD_SAVE_BYTES) throw new Error(`cloud save payload exceeds ${MAX_CLOUD_SAVE_BYTES} bytes`);
|
|
295
|
+
const { gameId } = this.requireGame();
|
|
296
|
+
const slot = cloudSaveSlot(options.slot ?? 0);
|
|
297
|
+
const schemaVersion = cloudSaveSchemaVersion(options.schemaVersion ?? 1);
|
|
298
|
+
let baseRevision = options.baseRevision;
|
|
299
|
+
if (baseRevision === void 0) {
|
|
300
|
+
baseRevision = this.cloudSaveRevisions.get(slot);
|
|
301
|
+
if (baseRevision === void 0) baseRevision = (await this.loadCloudSave(slot))?.revision ?? 0;
|
|
302
|
+
}
|
|
303
|
+
baseRevision = cloudSaveRevision(baseRevision);
|
|
304
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves/${slot}`, {
|
|
305
|
+
method: "PUT",
|
|
306
|
+
headers: { "Content-Type": "application/json" },
|
|
307
|
+
body: JSON.stringify({ payload, schema_version: schemaVersion, base_revision: baseRevision })
|
|
308
|
+
});
|
|
309
|
+
const body = await response.json().catch(() => ({}));
|
|
310
|
+
if (response.status === 409) {
|
|
311
|
+
const current = body.current_save ? this.parseCloudSave(body.current_save) : null;
|
|
312
|
+
throw new ToTopCloudSaveConflictError(current);
|
|
313
|
+
}
|
|
314
|
+
if (!response.ok) throw new Error(typeof body.error?.message === "string" ? body.error.message : `cloud save write failed (${response.status})`);
|
|
315
|
+
return this.parseCloudSave(body.save);
|
|
316
|
+
}
|
|
317
|
+
async restoreCloudSave(apply, slot = 0) {
|
|
318
|
+
const save = await this.loadCloudSave(slot);
|
|
319
|
+
if (save) await apply(save.payload, save);
|
|
320
|
+
return save;
|
|
321
|
+
}
|
|
322
|
+
async logout(input = {}) {
|
|
323
|
+
const config = this.config;
|
|
324
|
+
const refreshToken = config ? this.deps.storage.getItem(this.key("refresh")) : null;
|
|
325
|
+
this.clearState();
|
|
326
|
+
if (!config) return;
|
|
327
|
+
if (input.global) {
|
|
328
|
+
const target = new URL("/session/logout", config.issuer);
|
|
329
|
+
target.search = new URLSearchParams({ client_id: config.clientId, post_logout_redirect_uri: config.redirectUri }).toString();
|
|
330
|
+
(this.deps.navigate ?? ((url) => location.assign(url)))(target.href);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (refreshToken) await this.fetcher(new URL("/oauth/revoke", config.issuer), { method: "POST", credentials: "omit", redirect: "error", referrerPolicy: "no-referrer", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token", client_id: config.clientId }) }).catch(() => void 0);
|
|
334
|
+
}
|
|
335
|
+
async refresh(force = false, restoreUser = false) {
|
|
336
|
+
if (!force && this.accessToken && this.accessExpiresAt > this.now() + 5e3) return;
|
|
337
|
+
if (this.refreshFlight) return this.refreshFlight;
|
|
338
|
+
const config = this.requireConfig();
|
|
339
|
+
const token = this.deps.storage.getItem(this.key("refresh"));
|
|
340
|
+
const familyExpires = Number(this.deps.storage.getItem(this.key("family_expires")) ?? 0);
|
|
341
|
+
if (!token || familyExpires <= this.now()) {
|
|
342
|
+
this.clearState();
|
|
343
|
+
throw new Error("login required");
|
|
344
|
+
}
|
|
345
|
+
const generation = this.generation;
|
|
346
|
+
this.refreshFlight = this.exchange(new URLSearchParams({ grant_type: "refresh_token", client_id: config.clientId, resource: this.resource(), refresh_token: token }), generation, restoreUser).catch((error) => {
|
|
347
|
+
if (this.current(generation)) this.clearState();
|
|
348
|
+
throw error;
|
|
349
|
+
}).finally(() => {
|
|
350
|
+
if (this.current(generation)) this.refreshFlight = void 0;
|
|
351
|
+
});
|
|
352
|
+
return this.refreshFlight;
|
|
353
|
+
}
|
|
354
|
+
async exchange(body, generation, initial) {
|
|
355
|
+
const config = this.requireConfig();
|
|
356
|
+
const controller = new AbortController();
|
|
357
|
+
this.controllers.add(controller);
|
|
358
|
+
const authorizationCodeExchange = body.get("grant_type") === "authorization_code";
|
|
359
|
+
try {
|
|
360
|
+
const response = await this.fetcher(new URL("/oauth/token", config.issuer), { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body, signal: controller.signal, credentials: "omit", redirect: "error", referrerPolicy: "no-referrer" });
|
|
361
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
362
|
+
if (!response.ok) throw new Error("token exchange failed");
|
|
363
|
+
const result = await response.json();
|
|
364
|
+
if (result.token_type !== "Bearer" || !result.access_token || !result.refresh_token || authorizationCodeExchange && !result.id_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error("invalid token response");
|
|
365
|
+
let claims = null;
|
|
366
|
+
if (initial) {
|
|
367
|
+
const game = GAME_ID.exec(config.clientId);
|
|
368
|
+
const userUrl = game ? new URL(`/game-api/games/${game[1]}/me`, config.apiOrigin) : new URL(`/app-api/apps/${config.clientId.slice(4)}/me`, config.apiOrigin);
|
|
369
|
+
const userResponse = await this.fetcher(userUrl, { headers: { Authorization: `Bearer ${result.access_token}` }, signal: controller.signal, redirect: "manual", credentials: "omit", referrerPolicy: "no-referrer" });
|
|
370
|
+
if (!userResponse.ok || userResponse.type === "opaqueredirect") throw new Error("identity lookup failed");
|
|
371
|
+
claims = await userResponse.json();
|
|
372
|
+
}
|
|
373
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
374
|
+
if (claims) {
|
|
375
|
+
const id = claims.id;
|
|
376
|
+
const nickname = claims.nickname;
|
|
377
|
+
const avatarUrl = claims.avatarUrl;
|
|
378
|
+
if (typeof id !== "string" || typeof nickname !== "string" || avatarUrl !== void 0 && typeof avatarUrl !== "string") throw new Error("invalid identity response");
|
|
379
|
+
this.user = { id, nickname, avatarUrl: avatarUrl ?? "" };
|
|
380
|
+
}
|
|
381
|
+
this.accessToken = result.access_token;
|
|
382
|
+
this.accessExpiresAt = this.now() + result.expires_in * 1e3;
|
|
383
|
+
this.deps.storage.setItem(this.key("refresh"), result.refresh_token);
|
|
384
|
+
if (!this.deps.storage.getItem(this.key("family_expires"))) this.deps.storage.setItem(this.key("family_expires"), String(this.now() + 8 * 60 * 60 * 1e3));
|
|
385
|
+
} finally {
|
|
386
|
+
this.controllers.delete(controller);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// packages/auth-sdk/src/index.ts
|
|
392
|
+
var client = typeof window === "undefined" ? null : new ToTopPlatformClient({
|
|
393
|
+
storage: window.sessionStorage,
|
|
394
|
+
currentUrl: () => window.location.href,
|
|
395
|
+
navigate: (url) => window.location.assign(url),
|
|
396
|
+
replaceUrl: (url) => window.history.replaceState(null, "", url)
|
|
397
|
+
});
|
|
398
|
+
function browserClient() {
|
|
399
|
+
if (!client) throw new Error("ToTop Platform SDK requires a browser");
|
|
400
|
+
return client;
|
|
401
|
+
}
|
|
402
|
+
var ToTop = {
|
|
403
|
+
version: PLATFORM_SDK_VERSION,
|
|
404
|
+
init: async (input = "/totop.auth.json") => {
|
|
405
|
+
await browserClient().init(input);
|
|
406
|
+
return ToTop;
|
|
407
|
+
},
|
|
408
|
+
handleCallback: () => browserClient().handleCallback(),
|
|
409
|
+
login: () => browserClient().login(),
|
|
410
|
+
requireLogin: () => browserClient().requireLogin(),
|
|
411
|
+
getUser: () => browserClient().getUser(),
|
|
412
|
+
getAccessToken: () => browserClient().getAccessToken(),
|
|
413
|
+
authorizedFetch: (input, init) => browserClient().authorizedFetch(input, init),
|
|
414
|
+
cloudSave: {
|
|
415
|
+
list: () => browserClient().listCloudSaves(),
|
|
416
|
+
load: (slot = 0) => browserClient().loadCloudSave(slot),
|
|
417
|
+
save: (payload, options) => browserClient().saveCloudSave(payload, options),
|
|
418
|
+
restore: (apply, slot = 0) => browserClient().restoreCloudSave(apply, slot)
|
|
419
|
+
},
|
|
420
|
+
logout: (input) => browserClient().logout(input)
|
|
421
|
+
};
|
|
422
|
+
if (typeof window !== "undefined") {
|
|
423
|
+
Object.defineProperty(window, "ToTop", { value: ToTop, configurable: false, writable: false });
|
|
424
|
+
}
|
|
425
|
+
export {
|
|
426
|
+
MemoryTabStorage,
|
|
427
|
+
PLATFORM_SDK_VERSION,
|
|
428
|
+
ToTop,
|
|
429
|
+
ToTopCloudSaveConflictError,
|
|
430
|
+
ToTopPlatformClient,
|
|
431
|
+
validateConfig
|
|
432
|
+
};
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var ToTopPlatformSDK = (() => {
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// packages/auth-sdk/src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
MemoryTabStorage: () => MemoryTabStorage,
|
|
25
|
+
PLATFORM_SDK_VERSION: () => PLATFORM_SDK_VERSION,
|
|
26
|
+
ToTop: () => ToTop,
|
|
27
|
+
ToTopCloudSaveConflictError: () => ToTopCloudSaveConflictError,
|
|
28
|
+
ToTopPlatformClient: () => ToTopPlatformClient,
|
|
29
|
+
validateConfig: () => validateConfig
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// packages/auth-sdk/src/core.ts
|
|
33
|
+
var PLATFORM_SDK_VERSION = "1.1.0";
|
|
34
|
+
var CONFIG_VERSION = 1;
|
|
35
|
+
var MAX_CLOUD_SAVE_BYTES = 1024 * 1024;
|
|
36
|
+
var SESSION_PREFIX = "totop:auth-sdk:";
|
|
37
|
+
var GAME_ID = /^game:([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i;
|
|
38
|
+
var APP_ID = /^app:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
39
|
+
var ToTopCloudSaveConflictError = class extends Error {
|
|
40
|
+
constructor(currentSave) {
|
|
41
|
+
super("Cloud save revision conflict");
|
|
42
|
+
this.currentSave = currentSave;
|
|
43
|
+
this.name = "ToTopCloudSaveConflictError";
|
|
44
|
+
}
|
|
45
|
+
currentSave;
|
|
46
|
+
code = "revision_conflict";
|
|
47
|
+
};
|
|
48
|
+
var MemoryTabStorage = class {
|
|
49
|
+
map = /* @__PURE__ */ new Map();
|
|
50
|
+
getItem(key) {
|
|
51
|
+
return this.map.get(key) ?? null;
|
|
52
|
+
}
|
|
53
|
+
setItem(key, value) {
|
|
54
|
+
this.map.set(key, value);
|
|
55
|
+
}
|
|
56
|
+
removeItem(key) {
|
|
57
|
+
this.map.delete(key);
|
|
58
|
+
}
|
|
59
|
+
keys() {
|
|
60
|
+
return [...this.map.keys()];
|
|
61
|
+
}
|
|
62
|
+
values() {
|
|
63
|
+
return [...this.map.values()];
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
function b64url(bytes) {
|
|
67
|
+
const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
|
|
68
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
69
|
+
}
|
|
70
|
+
function random(length) {
|
|
71
|
+
const bytes = new Uint8Array(length);
|
|
72
|
+
crypto.getRandomValues(bytes);
|
|
73
|
+
return bytes;
|
|
74
|
+
}
|
|
75
|
+
function semver(value) {
|
|
76
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(value);
|
|
77
|
+
return match?.slice(1).map(Number);
|
|
78
|
+
}
|
|
79
|
+
function atLeast(actual, minimum) {
|
|
80
|
+
const a = semver(actual);
|
|
81
|
+
const m = semver(minimum);
|
|
82
|
+
if (!a || !m) return false;
|
|
83
|
+
for (let index = 0; index < 3; index++) {
|
|
84
|
+
if (a[index] > m[index]) return true;
|
|
85
|
+
if (a[index] < m[index]) return false;
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
function exactHttps(value, label, originOnly = false) {
|
|
90
|
+
if (typeof value !== "string") throw new Error(`${label} must be a string`);
|
|
91
|
+
const url = new URL(value);
|
|
92
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash || originOnly && url.href !== `${url.origin}/`) throw new Error(`${label} must be an exact HTTPS ${originOnly ? "origin" : "URL"}`);
|
|
93
|
+
return originOnly ? url.origin : url.href;
|
|
94
|
+
}
|
|
95
|
+
function exactScopes(type, value) {
|
|
96
|
+
const expected = type === "game" ? ["openid", "profile", "game:save"] : ["openid", "profile"];
|
|
97
|
+
if (!Array.isArray(value) || value.length !== expected.length || value.some((scope, index) => scope !== expected[index])) throw new Error(`scopes must equal ${expected.join(" ")}`);
|
|
98
|
+
return expected;
|
|
99
|
+
}
|
|
100
|
+
function cloudSaveSlot(value) {
|
|
101
|
+
if (!Number.isInteger(value) || value < 0 || value > 9) throw new Error("cloud save slot must be an integer from 0 to 9");
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
function cloudSaveSchemaVersion(value) {
|
|
105
|
+
if (!Number.isInteger(value) || value < 1) throw new Error("cloud save schemaVersion must be an integer >= 1");
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
function cloudSaveRevision(value) {
|
|
109
|
+
if (!Number.isInteger(value) || value < 0) throw new Error("cloud save baseRevision must be an integer >= 0");
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
function isObject(value) {
|
|
113
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
114
|
+
}
|
|
115
|
+
function validateConfig(value) {
|
|
116
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("ToTop platform config must be an object");
|
|
117
|
+
const input = value;
|
|
118
|
+
const allowed = ["$schema", "version", "clientId", "type", "issuer", "redirectUri", "apiOrigin", "scopes", "minimumSdkVersion"];
|
|
119
|
+
if (Object.keys(input).some((key) => !allowed.includes(key))) throw new Error("ToTop platform config contains an unknown property");
|
|
120
|
+
if (input.version !== CONFIG_VERSION) throw new Error("unsupported ToTop platform config version");
|
|
121
|
+
if (input.type !== "app" && input.type !== "game") throw new Error("type must be app or game");
|
|
122
|
+
if (typeof input.clientId !== "string" || (input.type === "app" ? !APP_ID.test(input.clientId) : !GAME_ID.test(input.clientId))) throw new Error(`invalid ${input.type} clientId`);
|
|
123
|
+
if (!semver(String(input.minimumSdkVersion)) || !atLeast(PLATFORM_SDK_VERSION, String(input.minimumSdkVersion))) throw new Error("SDK upgrade required");
|
|
124
|
+
return {
|
|
125
|
+
version: 1,
|
|
126
|
+
clientId: input.clientId,
|
|
127
|
+
type: input.type,
|
|
128
|
+
issuer: exactHttps(input.issuer, "issuer", true),
|
|
129
|
+
redirectUri: exactHttps(input.redirectUri, "redirectUri"),
|
|
130
|
+
apiOrigin: exactHttps(input.apiOrigin, "apiOrigin", true),
|
|
131
|
+
scopes: exactScopes(input.type, input.scopes),
|
|
132
|
+
minimumSdkVersion: String(input.minimumSdkVersion)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
var ToTopPlatformClient = class {
|
|
136
|
+
constructor(deps) {
|
|
137
|
+
this.deps = deps;
|
|
138
|
+
this.fetcher = deps.fetch ?? fetch;
|
|
139
|
+
}
|
|
140
|
+
deps;
|
|
141
|
+
config;
|
|
142
|
+
accessToken;
|
|
143
|
+
accessExpiresAt = 0;
|
|
144
|
+
user;
|
|
145
|
+
refreshFlight;
|
|
146
|
+
cloudSaveRevisions = /* @__PURE__ */ new Map();
|
|
147
|
+
generation = 0;
|
|
148
|
+
controllers = /* @__PURE__ */ new Set();
|
|
149
|
+
fetcher;
|
|
150
|
+
key(part) {
|
|
151
|
+
return `${SESSION_PREFIX}${this.config?.clientId ?? "uninitialized"}:${part}`;
|
|
152
|
+
}
|
|
153
|
+
now() {
|
|
154
|
+
return this.deps.now?.() ?? Date.now();
|
|
155
|
+
}
|
|
156
|
+
current(value) {
|
|
157
|
+
return value === this.generation;
|
|
158
|
+
}
|
|
159
|
+
abortAll() {
|
|
160
|
+
for (const controller of this.controllers) controller.abort();
|
|
161
|
+
this.controllers.clear();
|
|
162
|
+
}
|
|
163
|
+
clearState() {
|
|
164
|
+
this.generation++;
|
|
165
|
+
this.abortAll();
|
|
166
|
+
this.accessToken = void 0;
|
|
167
|
+
this.accessExpiresAt = 0;
|
|
168
|
+
this.user = void 0;
|
|
169
|
+
this.refreshFlight = void 0;
|
|
170
|
+
this.cloudSaveRevisions.clear();
|
|
171
|
+
if (this.config) for (const part of ["refresh", "family_expires", "state", "verifier"]) this.deps.storage.removeItem(this.key(part));
|
|
172
|
+
}
|
|
173
|
+
resource(config = this.requireConfig()) {
|
|
174
|
+
const match = GAME_ID.exec(config.clientId);
|
|
175
|
+
return new URL(match ? `/resources/games/${match[1]}` : `/resources/apps/${encodeURIComponent(config.clientId)}`, config.issuer).href;
|
|
176
|
+
}
|
|
177
|
+
requireConfig() {
|
|
178
|
+
if (!this.config) throw new Error("ToTop.init is required");
|
|
179
|
+
return this.config;
|
|
180
|
+
}
|
|
181
|
+
requireGame() {
|
|
182
|
+
const config = this.requireConfig();
|
|
183
|
+
const match = GAME_ID.exec(config.clientId);
|
|
184
|
+
if (!match) throw new Error("cloudSave is only available to reviewed game clients");
|
|
185
|
+
return { config, gameId: match[1] };
|
|
186
|
+
}
|
|
187
|
+
parseCloudSave(value) {
|
|
188
|
+
if (!isObject(value) || typeof value.id !== "string" || typeof value.game_id !== "string" || !Number.isInteger(value.slot) || !isObject(value.payload) || !Number.isInteger(value.schema_version) || !Number.isInteger(value.revision) || typeof value.created_at !== "string" || typeof value.updated_at !== "string") {
|
|
189
|
+
throw new Error("invalid cloud save response");
|
|
190
|
+
}
|
|
191
|
+
const save = {
|
|
192
|
+
id: value.id,
|
|
193
|
+
gameId: value.game_id,
|
|
194
|
+
slot: value.slot,
|
|
195
|
+
payload: value.payload,
|
|
196
|
+
schemaVersion: value.schema_version,
|
|
197
|
+
revision: value.revision,
|
|
198
|
+
createdAt: value.created_at,
|
|
199
|
+
updatedAt: value.updated_at
|
|
200
|
+
};
|
|
201
|
+
this.cloudSaveRevisions.set(save.slot, save.revision);
|
|
202
|
+
return save;
|
|
203
|
+
}
|
|
204
|
+
async init(input = "/totop.auth.json") {
|
|
205
|
+
const raw = typeof input === "string" ? await this.fetcher(new URL(input, this.deps.currentUrl?.() ?? location.href), { credentials: "same-origin", redirect: "error" }).then(async (response) => {
|
|
206
|
+
if (!response.ok) throw new Error("Unable to load ToTop auth config");
|
|
207
|
+
return response.json();
|
|
208
|
+
}) : input;
|
|
209
|
+
const next = validateConfig(raw);
|
|
210
|
+
if (this.config && this.config.clientId !== next.clientId) this.clearState();
|
|
211
|
+
this.config = next;
|
|
212
|
+
const completedCallback = await this.handleCallback();
|
|
213
|
+
if (!completedCallback && this.deps.storage.getItem(this.key("refresh"))) {
|
|
214
|
+
try {
|
|
215
|
+
await this.refresh(false, true);
|
|
216
|
+
} catch {
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return this;
|
|
220
|
+
}
|
|
221
|
+
async handleCallback() {
|
|
222
|
+
const config = this.requireConfig();
|
|
223
|
+
const current = new URL(this.deps.currentUrl?.() ?? location.href);
|
|
224
|
+
if (!current.searchParams.has("code") && !current.searchParams.has("error")) return false;
|
|
225
|
+
const code = current.searchParams.get("code");
|
|
226
|
+
const state = current.searchParams.get("state");
|
|
227
|
+
const expected = this.deps.storage.getItem(this.key("state"));
|
|
228
|
+
const verifier = this.deps.storage.getItem(this.key("verifier"));
|
|
229
|
+
for (const key of ["code", "state", "error", "error_description", "iss"]) current.searchParams.delete(key);
|
|
230
|
+
this.deps.replaceUrl?.(current.href);
|
|
231
|
+
this.deps.storage.removeItem(this.key("state"));
|
|
232
|
+
this.deps.storage.removeItem(this.key("verifier"));
|
|
233
|
+
if (!code || !state || state !== expected || !verifier) {
|
|
234
|
+
this.clearState();
|
|
235
|
+
throw new Error("invalid OAuth callback state");
|
|
236
|
+
}
|
|
237
|
+
const generation = this.generation;
|
|
238
|
+
try {
|
|
239
|
+
await this.exchange(new URLSearchParams({ grant_type: "authorization_code", client_id: config.clientId, resource: this.resource(), code, redirect_uri: config.redirectUri, code_verifier: verifier }), generation, true);
|
|
240
|
+
return true;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (this.current(generation)) this.clearState();
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async login() {
|
|
247
|
+
return this.requireLogin();
|
|
248
|
+
}
|
|
249
|
+
async requireLogin() {
|
|
250
|
+
const config = this.requireConfig();
|
|
251
|
+
if (this.accessToken && this.accessExpiresAt > this.now() + 5e3) return;
|
|
252
|
+
const verifier = b64url((this.deps.randomBytes ?? random)(32));
|
|
253
|
+
const state = b64url((this.deps.randomBytes ?? random)(24));
|
|
254
|
+
const digest = this.deps.digest ?? (async (value) => new Uint8Array(await crypto.subtle.digest("SHA-256", value)));
|
|
255
|
+
const generation = this.generation;
|
|
256
|
+
const challenge = b64url(await digest(new TextEncoder().encode(verifier)));
|
|
257
|
+
if (!this.current(generation)) return;
|
|
258
|
+
this.deps.storage.setItem(this.key("verifier"), verifier);
|
|
259
|
+
this.deps.storage.setItem(this.key("state"), state);
|
|
260
|
+
let url;
|
|
261
|
+
const game = GAME_ID.exec(config.clientId);
|
|
262
|
+
if (game) {
|
|
263
|
+
url = new URL(`/launch/${game[1]}`, config.issuer);
|
|
264
|
+
url.search = new URLSearchParams({ redirect_uri: config.redirectUri, origin: new URL(config.redirectUri).origin, state, code_challenge: challenge, code_challenge_method: "S256", sdk_version: PLATFORM_SDK_VERSION }).toString();
|
|
265
|
+
} else {
|
|
266
|
+
url = new URL("/oauth/authorize", config.issuer);
|
|
267
|
+
url.search = new URLSearchParams({ client_id: config.clientId, response_type: "code", redirect_uri: config.redirectUri, scope: config.scopes.join(" "), resource: this.resource(), state, code_challenge: challenge, code_challenge_method: "S256" }).toString();
|
|
268
|
+
}
|
|
269
|
+
;
|
|
270
|
+
(this.deps.navigate ?? ((target) => location.assign(target)))(url.href);
|
|
271
|
+
}
|
|
272
|
+
getUser() {
|
|
273
|
+
return this.user ?? null;
|
|
274
|
+
}
|
|
275
|
+
async getAccessToken() {
|
|
276
|
+
if (!this.accessToken || this.accessExpiresAt <= this.now() + 5e3) await this.refresh();
|
|
277
|
+
if (!this.accessToken) throw new Error("login required");
|
|
278
|
+
return this.accessToken;
|
|
279
|
+
}
|
|
280
|
+
async authorizedFetch(input, init = {}) {
|
|
281
|
+
const config = this.requireConfig();
|
|
282
|
+
const url = new URL(input.toString(), config.apiOrigin);
|
|
283
|
+
if (url.origin !== config.apiOrigin) throw new Error("authorizedFetch origin is not allowed");
|
|
284
|
+
const generation = this.generation;
|
|
285
|
+
const controller = new AbortController();
|
|
286
|
+
this.controllers.add(controller);
|
|
287
|
+
const run = async () => this.fetcher(url, { ...init, signal: controller.signal, redirect: "manual", referrerPolicy: "no-referrer", headers: { ...Object.fromEntries(new Headers(init.headers).entries()), Authorization: `Bearer ${await this.getAccessToken()}` } });
|
|
288
|
+
try {
|
|
289
|
+
let response = await run();
|
|
290
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
291
|
+
if (response.status === 401) {
|
|
292
|
+
await this.refresh(true);
|
|
293
|
+
response = await run();
|
|
294
|
+
}
|
|
295
|
+
if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) throw new Error("authenticated cross-origin redirects are forbidden");
|
|
296
|
+
return response;
|
|
297
|
+
} finally {
|
|
298
|
+
this.controllers.delete(controller);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async listCloudSaves() {
|
|
302
|
+
const { gameId } = this.requireGame();
|
|
303
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves`);
|
|
304
|
+
if (!response.ok) throw new Error(`cloud save list failed (${response.status})`);
|
|
305
|
+
const body = await response.json();
|
|
306
|
+
if (!Array.isArray(body.saves)) throw new Error("invalid cloud save list response");
|
|
307
|
+
return body.saves.map((save) => this.parseCloudSave(save));
|
|
308
|
+
}
|
|
309
|
+
async loadCloudSave(slot = 0) {
|
|
310
|
+
const { gameId } = this.requireGame();
|
|
311
|
+
const selectedSlot = cloudSaveSlot(slot);
|
|
312
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves/${selectedSlot}`);
|
|
313
|
+
if (response.status === 404) {
|
|
314
|
+
this.cloudSaveRevisions.delete(selectedSlot);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
if (!response.ok) throw new Error(`cloud save load failed (${response.status})`);
|
|
318
|
+
const body = await response.json();
|
|
319
|
+
return this.parseCloudSave(body.save);
|
|
320
|
+
}
|
|
321
|
+
async saveCloudSave(payload, options = {}) {
|
|
322
|
+
if (!isObject(payload)) throw new Error("cloud save payload must be a JSON object");
|
|
323
|
+
const serialized = JSON.stringify(payload);
|
|
324
|
+
if (typeof serialized !== "string") throw new Error("cloud save payload must be JSON serializable");
|
|
325
|
+
if (new TextEncoder().encode(serialized).byteLength > MAX_CLOUD_SAVE_BYTES) throw new Error(`cloud save payload exceeds ${MAX_CLOUD_SAVE_BYTES} bytes`);
|
|
326
|
+
const { gameId } = this.requireGame();
|
|
327
|
+
const slot = cloudSaveSlot(options.slot ?? 0);
|
|
328
|
+
const schemaVersion = cloudSaveSchemaVersion(options.schemaVersion ?? 1);
|
|
329
|
+
let baseRevision = options.baseRevision;
|
|
330
|
+
if (baseRevision === void 0) {
|
|
331
|
+
baseRevision = this.cloudSaveRevisions.get(slot);
|
|
332
|
+
if (baseRevision === void 0) baseRevision = (await this.loadCloudSave(slot))?.revision ?? 0;
|
|
333
|
+
}
|
|
334
|
+
baseRevision = cloudSaveRevision(baseRevision);
|
|
335
|
+
const response = await this.authorizedFetch(`/game-api/games/${gameId}/saves/${slot}`, {
|
|
336
|
+
method: "PUT",
|
|
337
|
+
headers: { "Content-Type": "application/json" },
|
|
338
|
+
body: JSON.stringify({ payload, schema_version: schemaVersion, base_revision: baseRevision })
|
|
339
|
+
});
|
|
340
|
+
const body = await response.json().catch(() => ({}));
|
|
341
|
+
if (response.status === 409) {
|
|
342
|
+
const current = body.current_save ? this.parseCloudSave(body.current_save) : null;
|
|
343
|
+
throw new ToTopCloudSaveConflictError(current);
|
|
344
|
+
}
|
|
345
|
+
if (!response.ok) throw new Error(typeof body.error?.message === "string" ? body.error.message : `cloud save write failed (${response.status})`);
|
|
346
|
+
return this.parseCloudSave(body.save);
|
|
347
|
+
}
|
|
348
|
+
async restoreCloudSave(apply, slot = 0) {
|
|
349
|
+
const save = await this.loadCloudSave(slot);
|
|
350
|
+
if (save) await apply(save.payload, save);
|
|
351
|
+
return save;
|
|
352
|
+
}
|
|
353
|
+
async logout(input = {}) {
|
|
354
|
+
const config = this.config;
|
|
355
|
+
const refreshToken = config ? this.deps.storage.getItem(this.key("refresh")) : null;
|
|
356
|
+
this.clearState();
|
|
357
|
+
if (!config) return;
|
|
358
|
+
if (input.global) {
|
|
359
|
+
const target = new URL("/session/logout", config.issuer);
|
|
360
|
+
target.search = new URLSearchParams({ client_id: config.clientId, post_logout_redirect_uri: config.redirectUri }).toString();
|
|
361
|
+
(this.deps.navigate ?? ((url) => location.assign(url)))(target.href);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (refreshToken) await this.fetcher(new URL("/oauth/revoke", config.issuer), { method: "POST", credentials: "omit", redirect: "error", referrerPolicy: "no-referrer", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token", client_id: config.clientId }) }).catch(() => void 0);
|
|
365
|
+
}
|
|
366
|
+
async refresh(force = false, restoreUser = false) {
|
|
367
|
+
if (!force && this.accessToken && this.accessExpiresAt > this.now() + 5e3) return;
|
|
368
|
+
if (this.refreshFlight) return this.refreshFlight;
|
|
369
|
+
const config = this.requireConfig();
|
|
370
|
+
const token = this.deps.storage.getItem(this.key("refresh"));
|
|
371
|
+
const familyExpires = Number(this.deps.storage.getItem(this.key("family_expires")) ?? 0);
|
|
372
|
+
if (!token || familyExpires <= this.now()) {
|
|
373
|
+
this.clearState();
|
|
374
|
+
throw new Error("login required");
|
|
375
|
+
}
|
|
376
|
+
const generation = this.generation;
|
|
377
|
+
this.refreshFlight = this.exchange(new URLSearchParams({ grant_type: "refresh_token", client_id: config.clientId, resource: this.resource(), refresh_token: token }), generation, restoreUser).catch((error) => {
|
|
378
|
+
if (this.current(generation)) this.clearState();
|
|
379
|
+
throw error;
|
|
380
|
+
}).finally(() => {
|
|
381
|
+
if (this.current(generation)) this.refreshFlight = void 0;
|
|
382
|
+
});
|
|
383
|
+
return this.refreshFlight;
|
|
384
|
+
}
|
|
385
|
+
async exchange(body, generation, initial) {
|
|
386
|
+
const config = this.requireConfig();
|
|
387
|
+
const controller = new AbortController();
|
|
388
|
+
this.controllers.add(controller);
|
|
389
|
+
const authorizationCodeExchange = body.get("grant_type") === "authorization_code";
|
|
390
|
+
try {
|
|
391
|
+
const response = await this.fetcher(new URL("/oauth/token", config.issuer), { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body, signal: controller.signal, credentials: "omit", redirect: "error", referrerPolicy: "no-referrer" });
|
|
392
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
393
|
+
if (!response.ok) throw new Error("token exchange failed");
|
|
394
|
+
const result = await response.json();
|
|
395
|
+
if (result.token_type !== "Bearer" || !result.access_token || !result.refresh_token || authorizationCodeExchange && !result.id_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error("invalid token response");
|
|
396
|
+
let claims = null;
|
|
397
|
+
if (initial) {
|
|
398
|
+
const game = GAME_ID.exec(config.clientId);
|
|
399
|
+
const userUrl = game ? new URL(`/game-api/games/${game[1]}/me`, config.apiOrigin) : new URL(`/app-api/apps/${config.clientId.slice(4)}/me`, config.apiOrigin);
|
|
400
|
+
const userResponse = await this.fetcher(userUrl, { headers: { Authorization: `Bearer ${result.access_token}` }, signal: controller.signal, redirect: "manual", credentials: "omit", referrerPolicy: "no-referrer" });
|
|
401
|
+
if (!userResponse.ok || userResponse.type === "opaqueredirect") throw new Error("identity lookup failed");
|
|
402
|
+
claims = await userResponse.json();
|
|
403
|
+
}
|
|
404
|
+
if (!this.current(generation)) throw new Error("SDK session changed");
|
|
405
|
+
if (claims) {
|
|
406
|
+
const id = claims.id;
|
|
407
|
+
const nickname = claims.nickname;
|
|
408
|
+
const avatarUrl = claims.avatarUrl;
|
|
409
|
+
if (typeof id !== "string" || typeof nickname !== "string" || avatarUrl !== void 0 && typeof avatarUrl !== "string") throw new Error("invalid identity response");
|
|
410
|
+
this.user = { id, nickname, avatarUrl: avatarUrl ?? "" };
|
|
411
|
+
}
|
|
412
|
+
this.accessToken = result.access_token;
|
|
413
|
+
this.accessExpiresAt = this.now() + result.expires_in * 1e3;
|
|
414
|
+
this.deps.storage.setItem(this.key("refresh"), result.refresh_token);
|
|
415
|
+
if (!this.deps.storage.getItem(this.key("family_expires"))) this.deps.storage.setItem(this.key("family_expires"), String(this.now() + 8 * 60 * 60 * 1e3));
|
|
416
|
+
} finally {
|
|
417
|
+
this.controllers.delete(controller);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
// packages/auth-sdk/src/index.ts
|
|
423
|
+
var client = typeof window === "undefined" ? null : new ToTopPlatformClient({
|
|
424
|
+
storage: window.sessionStorage,
|
|
425
|
+
currentUrl: () => window.location.href,
|
|
426
|
+
navigate: (url) => window.location.assign(url),
|
|
427
|
+
replaceUrl: (url) => window.history.replaceState(null, "", url)
|
|
428
|
+
});
|
|
429
|
+
function browserClient() {
|
|
430
|
+
if (!client) throw new Error("ToTop Platform SDK requires a browser");
|
|
431
|
+
return client;
|
|
432
|
+
}
|
|
433
|
+
var ToTop = {
|
|
434
|
+
version: PLATFORM_SDK_VERSION,
|
|
435
|
+
init: async (input = "/totop.auth.json") => {
|
|
436
|
+
await browserClient().init(input);
|
|
437
|
+
return ToTop;
|
|
438
|
+
},
|
|
439
|
+
handleCallback: () => browserClient().handleCallback(),
|
|
440
|
+
login: () => browserClient().login(),
|
|
441
|
+
requireLogin: () => browserClient().requireLogin(),
|
|
442
|
+
getUser: () => browserClient().getUser(),
|
|
443
|
+
getAccessToken: () => browserClient().getAccessToken(),
|
|
444
|
+
authorizedFetch: (input, init) => browserClient().authorizedFetch(input, init),
|
|
445
|
+
cloudSave: {
|
|
446
|
+
list: () => browserClient().listCloudSaves(),
|
|
447
|
+
load: (slot = 0) => browserClient().loadCloudSave(slot),
|
|
448
|
+
save: (payload, options) => browserClient().saveCloudSave(payload, options),
|
|
449
|
+
restore: (apply, slot = 0) => browserClient().restoreCloudSave(apply, slot)
|
|
450
|
+
},
|
|
451
|
+
logout: (input) => browserClient().logout(input)
|
|
452
|
+
};
|
|
453
|
+
if (typeof window !== "undefined") {
|
|
454
|
+
Object.defineProperty(window, "ToTop", { value: ToTop, configurable: false, writable: false });
|
|
455
|
+
}
|
|
456
|
+
return __toCommonJS(index_exports);
|
|
457
|
+
})();
|
package/package.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@totop/platform-sdk",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": { ".": "./dist/totop-platform.esm.js" },
|
|
6
|
+
"main": "./dist/totop-platform.global.js",
|
|
7
|
+
"module": "./dist/totop-platform.esm.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"bin": { "totop-platform": "bin/totop-auth.mjs" },
|
|
10
|
+
"files": ["dist", "bin", "schema", "AI-INTEGRATION.md", "README.md"],
|
|
11
|
+
"scripts": { "build": "npm --prefix ../.. run build:sdk:platform", "prepack": "npm run build" }
|
|
12
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://auth.totop.ai/schemas/totop.auth.schema.json",
|
|
4
|
+
"title": "ToTop Platform SDK configuration",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"required": ["version", "clientId", "type", "issuer", "redirectUri", "apiOrigin", "scopes", "minimumSdkVersion"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"$schema": { "type": "string" },
|
|
10
|
+
"version": { "const": 1 },
|
|
11
|
+
"clientId": { "type": "string", "pattern": "^(app:[a-z0-9][a-z0-9-]{0,62}|game:[0-9a-fA-F-]{36})$" },
|
|
12
|
+
"type": { "enum": ["app", "game"] },
|
|
13
|
+
"issuer": { "type": "string", "format": "uri", "pattern": "^https://" },
|
|
14
|
+
"redirectUri": { "type": "string", "format": "uri", "pattern": "^https://" },
|
|
15
|
+
"apiOrigin": { "type": "string", "format": "uri", "pattern": "^https://[^/]+$" },
|
|
16
|
+
"scopes": { "type": "array", "items": { "type": "string" }, "uniqueItems": true, "minItems": 2, "maxItems": 3 },
|
|
17
|
+
"minimumSdkVersion": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }
|
|
18
|
+
}
|
|
19
|
+
}
|