@crowdedkingdoms/crowdyjs 7.1.1 → 8.0.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/MIGRATION.md CHANGED
@@ -1,3 +1,49 @@
1
+ # CrowdyJS v8 — Passwordless & federated sign-in (BREAKING)
2
+
3
+ **Crowded Kingdoms is passwordless.** Email + password login is removed. Update
4
+ your sign-in flow to one of:
5
+
6
+ - **Magic link (email):**
7
+ ```ts
8
+ await client.auth.requestLoginLink({ email, redirectUri }); // emails a one-time link
9
+ // on the landing page (token from the URL):
10
+ const { user } = await client.auth.completeLoginLink(tokenFromUrl);
11
+ ```
12
+ - **Social (federated / OIDC):**
13
+ ```ts
14
+ const providers = await client.auth.availableLoginProviders(); // e.g. ['google']
15
+ const { authorizeUrl, state } = await client.auth.socialLoginStart('google', callbackUrl);
16
+ location.assign(authorizeUrl);
17
+ // on the callback page:
18
+ await client.auth.socialLoginComplete({ provider: 'google', code, state });
19
+ ```
20
+ - **Dev bypass (development only):** `await client.auth.devLogin(email)` — works only
21
+ when the server has `DEV_AUTH_BYPASS` enabled.
22
+
23
+ **Removed:** `client.auth.login`, `register`, `confirmEmail`, `requestPasswordReset`,
24
+ `resetPassword`, `resendConfirmationEmail`, `changePassword` (and the
25
+ `LoginUserInput` / `RegisterUserInput` / `ResetPasswordInput` types).
26
+
27
+ **New:** `requestLoginLink`, `completeLoginLink`, `socialLoginStart`,
28
+ `socialLoginComplete`, `devLogin`, `availableLoginProviders`, `myIdentities`,
29
+ `linkIdentity`, `unlinkIdentity`. Each sign-in still returns an identity session
30
+ token, stored on the shared session automatically (account is created on first
31
+ sign-in).
32
+
33
+ **Portal consent + connected apps (new on `client.portal`):** `getConsent(appId)`,
34
+ `authorizeApp(appId)`, `revokeAppAuthorization(appId)`, `myAuthorizedApps()`,
35
+ `setAppClientSettings({ appId, redirectUris, clientType, launchUrl })`.
36
+ `handleAuthorizeRequest` now enforces consent: untrusted apps throw
37
+ `PortalConsentRequiredError` unless you pass `{ grantConsent: true }` (call after
38
+ the user approves on the consent screen). Trusted/first-party apps (the Overworld,
39
+ app 1) skip consent. Browser portal entry now requires the destination app's
40
+ `redirect_uris` to be registered (`setAppClientSettings`).
41
+
42
+ Everything else from v7 (the two-client pattern, `client.portal` minting/PKCE,
43
+ app-scoped tokens) is unchanged.
44
+
45
+ ---
46
+
1
47
  # CrowdyJS v7 — Overworld portals & app-scoped tokens (BREAKING)
2
48
 
3
49
  v7 splits the single app-agnostic game token into two credentials and makes
@@ -1,163 +1,100 @@
1
1
  import type { GraphQLClient } from '../client.js';
2
2
  import type { AuthState } from '../auth-state.js';
3
- import { type LoginMutation, type LoginUserInput, type RegisterMutation, type RegisterUserInput, type ResetPasswordInput } from '../generated/graphql.js';
4
3
  /**
5
- * Authentication and account-lifecycle flows — exposed as `client.auth`.
4
+ * Authentication and account lifecycle — exposed as `client.auth`.
6
5
  *
7
- * Targets the **management-api**: every call routes to `managementUrl` (falling
8
- * back to the game-api endpoint only in legacy single-endpoint mode). The
9
- * management API owns the `game_tokens` table that backs every login / register
10
- * / password / email-confirmation flow; the `token` it returns is a
11
- * `game_tokens` row that game-api validates against the same shared Postgres.
6
+ * Crowded Kingdoms is **passwordless**. There is no email+password login: a user
7
+ * authenticates with an emailed magic link, a federated social provider (OIDC),
8
+ * or in development only — the dev bypass. Every path returns an identity
9
+ * SESSION token (management-plane), which is stored on the shared session state
10
+ * automatically. Gameplay tokens are minted separately via `client.portal`.
12
11
  *
13
- * {@link login} and {@link register} mint that session token **and** store it on
14
- * the shared session state automatically, so every later call on *either*
15
- * endpoint (auth, users, apps, actors, chunks, udp, ...) is authenticated
16
- * without you threading the token through by hand. Use {@link setToken} to
17
- * rehydrate a saved token and {@link getToken} to read the current one. `BigInt`
18
- * ids on the returned user (e.g. `userId`, `orgId`) are decimal strings.
12
+ * Targets the **management-api** (`managementUrl`).
19
13
  *
20
- * **Public no session required:** {@link login}, {@link register},
21
- * {@link confirmEmail}, {@link requestPasswordReset}, {@link resetPassword}, and
22
- * {@link resendConfirmationEmail}. **Require a valid session:** {@link logout},
23
- * {@link logoutAllDevices}, and {@link changePassword}, which otherwise throw
24
- * {@link CrowdyGraphQLError} with `UNAUTHENTICATED` when the bearer token is
25
- * missing, expired, or revoked.
14
+ * **Public (no session):** {@link requestLoginLink}, {@link completeLoginLink},
15
+ * {@link socialLoginStart}, {@link socialLoginComplete}, {@link devLogin},
16
+ * {@link availableLoginProviders}. **Require a session:** {@link logout},
17
+ * {@link logoutAllDevices}, {@link myIdentities}, {@link linkIdentity},
18
+ * {@link unlinkIdentity}.
26
19
  */
20
+ export interface AuthUser {
21
+ userId: string;
22
+ email?: string | null;
23
+ gamertag?: string | null;
24
+ }
25
+ export interface AuthResponse {
26
+ /** Identity session token; stored on the session state automatically. */
27
+ token: string;
28
+ gameTokenId: string;
29
+ user: AuthUser;
30
+ }
31
+ export interface UserIdentity {
32
+ identityId: string;
33
+ provider: string;
34
+ subject: string;
35
+ email: string | null;
36
+ emailVerified: boolean;
37
+ createdAt: string;
38
+ lastLoginAt: string | null;
39
+ }
27
40
  export declare class AuthAPI {
28
41
  private readonly graphql;
29
42
  private readonly session;
30
43
  constructor(graphql: GraphQLClient, session: AuthState);
44
+ /** The federated sign-in providers currently enabled (e.g. `['google']`). */
45
+ availableLoginProviders(): Promise<string[]>;
31
46
  /**
32
- * Authenticate with email + password and start a new session. **Public** — no
33
- * existing session required.
34
- *
35
- * On success the returned `token` is minted **and** stored on the shared
36
- * session state, so subsequent calls on any sub-client (management-api or
37
- * game-api) carry it automatically — no need to call {@link setToken}.
38
- *
39
- * @param input - Credentials ({@link LoginUserInput}): `email` and `password`
40
- * (min 8 characters).
41
- * @returns An {@link AuthResponse}: the opaque session `token` (sent as
42
- * `Authorization: Bearer <token>`), `gameTokenId` (the session row id, a
43
- * string), and the authenticated `user`.
44
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` on invalid credentials, or
45
- * `BAD_USER_INPUT` on malformed input.
46
- * @example
47
- * ```ts
48
- * const { user } = await client.auth.login({ email, password });
49
- * // the session token is now stored; later calls are authenticated for you
50
- * await client.users.me();
51
- * ```
47
+ * Passwordless: email the address a one-time magic sign-in link (creating the
48
+ * account on first sign-in). Always resolves `sent: true` (no enumeration). In
49
+ * development (`DEV_AUTH_BYPASS`) the response also carries `devToken`, the
50
+ * token to pass straight to {@link completeLoginLink} without an inbox.
52
51
  */
53
- login(input: LoginUserInput): Promise<LoginMutation['login']>;
52
+ requestLoginLink(input: {
53
+ email: string;
54
+ redirectUri?: string;
55
+ }): Promise<{
56
+ sent: boolean;
57
+ devToken: string | null;
58
+ }>;
59
+ /** Complete a magic-link sign-in; stores the session token on success. */
60
+ completeLoginLink(token: string): Promise<AuthResponse>;
54
61
  /**
55
- * Create a new (initially unconfirmed) account, send a confirmation email, and
56
- * return a session for immediate login. **Public** no existing session
57
- * required. Same token-persistence behaviour as {@link login}: the new `token`
58
- * is stored on the shared session state automatically.
59
- *
60
- * @param input - New-account details ({@link RegisterUserInput}): `email`
61
- * (where the confirmation email is sent), `password` (min 8 characters), and
62
- * an optional initial `gamertag` (min 3 characters; can also be set later via
63
- * `client.users.updateGamertag`).
64
- * @returns An {@link AuthResponse} (session `token`, `gameTokenId`, and the new
65
- * `user`).
66
- * @throws {CrowdyGraphQLError} `BAD_USER_INPUT` if the email already exists or
67
- * the input is invalid.
62
+ * Begin a federated (social) sign-in. Returns an `authorizeUrl` to redirect the
63
+ * user to and an opaque `state` to round-trip back to {@link socialLoginComplete}.
68
64
  */
69
- register(input: RegisterUserInput): Promise<RegisterMutation['register']>;
65
+ socialLoginStart(provider: string, redirectUri: string): Promise<{
66
+ authorizeUrl: string;
67
+ state: string;
68
+ }>;
69
+ /** Complete a federated sign-in from the provider callback; stores the token. */
70
+ socialLoginComplete(input: {
71
+ provider: string;
72
+ code: string;
73
+ state: string;
74
+ }): Promise<AuthResponse>;
70
75
  /**
71
- * Single-device logout: revoke the `game_tokens` row that authenticated this
72
- * request; other devices/tokens are unaffected. After a successful server-side
73
- * revoke the in-memory token is cleared from the shared session state so the
74
- * other sub-clients stop using it. Requires a valid session.
75
- *
76
- * @returns `true` if a token was revoked, or `false` if the request carried no
77
- * game token.
78
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` if the session is invalid.
76
+ * DEV ONLY bypass sign-in (active only when the server has `DEV_AUTH_BYPASS`).
77
+ * Returns a session for `email` without email/social verification; stores it.
78
+ * Throws `FORBIDDEN` when the bypass is disabled (e.g. production).
79
79
  */
80
+ devLogin(email: string): Promise<AuthResponse>;
81
+ /** The signed-in user's linked sign-in identities. Requires a session. */
82
+ myIdentities(): Promise<UserIdentity[]>;
83
+ /** Link an additional federated identity (from a social callback). */
84
+ linkIdentity(input: {
85
+ provider: string;
86
+ code: string;
87
+ state: string;
88
+ }): Promise<UserIdentity>;
89
+ /** Unlink a federated identity (cannot remove the last sign-in method). */
90
+ unlinkIdentity(identityId: string): Promise<boolean>;
91
+ /** Single-device logout; clears the in-memory token on success. */
80
92
  logout(): Promise<boolean>;
81
- /**
82
- * Revoke **every** active session for the authenticated user (deletes all
83
- * their `game_tokens` rows and records revocations). Requires a valid session;
84
- * use {@link logout} to end only the current one.
85
- *
86
- * Note: unlike {@link logout}, this does not clear the SDK's in-memory token —
87
- * call {@link setToken}`(null)` afterwards if you also want to drop it locally.
88
- *
89
- * @returns `true` on success.
90
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` if the session is invalid.
91
- */
93
+ /** Revoke every active session for the user. Requires a session. */
92
94
  logoutAllDevices(): Promise<boolean>;
93
- /**
94
- * Confirm a user's email address using the token from the confirmation email.
95
- * **Public** — the token itself authorizes the call.
96
- *
97
- * @param token - The confirmation token from the emailed link.
98
- * @returns `true` on success, or `false` if the token is invalid or expired.
99
- * @throws {CrowdyGraphQLError} on transport/validation failures (invalid or
100
- * expired tokens resolve to `false` rather than throwing).
101
- */
102
- confirmEmail(token: string): Promise<boolean>;
103
- /**
104
- * Start the password-reset flow by emailing a reset link to the address.
105
- * **Public**. Always returns `true` regardless of whether the email exists or
106
- * is confirmed, to prevent account enumeration.
107
- *
108
- * @param email - Email address to send the password-reset link to.
109
- * @returns `true` (always, even when no such account exists).
110
- * @throws {CrowdyGraphQLError} on transport/validation failures.
111
- */
112
- requestPasswordReset(email: string): Promise<boolean>;
113
- /**
114
- * Complete a password reset using the reset token and a new password.
115
- * **Public** — the reset token authorizes the call. Existing sessions are
116
- * **not** revoked.
117
- *
118
- * @param input - {@link ResetPasswordInput}: the `token` from the emailed reset
119
- * link and the `newPassword` to set (min 8 characters).
120
- * @returns `true` on success.
121
- * @throws {CrowdyGraphQLError} `BAD_USER_INPUT` if the token is invalid or
122
- * expired.
123
- */
124
- resetPassword(input: ResetPasswordInput): Promise<boolean>;
125
- /**
126
- * Re-send the email-confirmation link. **Public**. Always returns `true`
127
- * regardless of whether the account exists or is already confirmed (prevents
128
- * enumeration); the email is only actually sent for existing unconfirmed
129
- * accounts.
130
- *
131
- * @param email - Email address of the account to re-send confirmation to.
132
- * @returns `true` (always).
133
- * @throws {CrowdyGraphQLError} on transport/validation failures.
134
- */
135
- resendConfirmationEmail(email: string): Promise<boolean>;
136
- /**
137
- * Change the authenticated user's password after verifying the current one.
138
- * Requires a valid session. Existing sessions are **not** revoked.
139
- *
140
- * @param currentPassword - The user's current password, for verification.
141
- * @param newPassword - The new password to set (min 8 characters).
142
- * @returns `true` on success.
143
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` without a valid session, or
144
- * `BAD_USER_INPUT` if the current password is wrong.
145
- */
146
- changePassword(currentPassword: string, newPassword: string): Promise<boolean>;
147
- /**
148
- * Imperatively replace the in-memory bearer token on the shared session state
149
- * (e.g. to rehydrate a token persisted to disk). Affects every sub-client.
150
- * Local only — performs no network call. Pass `null` to clear it.
151
- *
152
- * @param token - The bearer token to use, or `null` to clear the session.
153
- */
95
+ /** Imperatively set the in-memory bearer token (e.g. rehydrate). */
154
96
  setToken(token: string | null): void;
155
- /**
156
- * Read the current in-memory bearer token from the shared session state. Local
157
- * only — performs no network call.
158
- *
159
- * @returns The current bearer token, or `null` if none is set.
160
- */
97
+ /** Read the current in-memory bearer token. */
161
98
  getToken(): string | null;
162
99
  }
163
100
  //# sourceMappingURL=auth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/domains/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAUL,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACxB,MAAM,yBAAyB,CAAC;AAEjC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,OAAO;IAEhB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBADP,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,SAAS;IAGrC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,KAAK,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAQnE;;;;;;;;;;;;;;OAcG;IACG,QAAQ,CACZ,KAAK,EAAE,iBAAiB,GACvB,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;IAQxC;;;;;;;;;OASG;IACG,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC;IAMhC;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,OAAO,CAAC;IAK1C;;;;;;;;OAQG;IACG,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAKnD;;;;;;;;OAQG;IACG,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO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C,OAAO,CAAC;IAO1D,mEAAmE;IAC7D,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC;IAMhC,oEAAoE;IAC9D,gBAAgB,IAAI,OAAO,CAAC,OAAO,CAAC;IAK1C,oEAAoE;IACpE,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAIpC,+CAA+C;IAC/C,QAAQ,IAAI,MAAM,GAAG,IAAI;CAG1B"}
@@ -1,207 +1,110 @@
1
- import { ChangePasswordDocument, ConfirmEmailDocument, LoginDocument, LogoutAllDevicesDocument, LogoutDocument, RegisterDocument, RequestPasswordResetDocument, ResendConfirmationEmailDocument, ResetPasswordDocument, } from '../generated/graphql.js';
2
- /**
3
- * Authentication and account-lifecycle flows exposed as `client.auth`.
4
- *
5
- * Targets the **management-api**: every call routes to `managementUrl` (falling
6
- * back to the game-api endpoint only in legacy single-endpoint mode). The
7
- * management API owns the `game_tokens` table that backs every login / register
8
- * / password / email-confirmation flow; the `token` it returns is a
9
- * `game_tokens` row that game-api validates against the same shared Postgres.
10
- *
11
- * {@link login} and {@link register} mint that session token **and** store it on
12
- * the shared session state automatically, so every later call on *either*
13
- * endpoint (auth, users, apps, actors, chunks, udp, ...) is authenticated
14
- * without you threading the token through by hand. Use {@link setToken} to
15
- * rehydrate a saved token and {@link getToken} to read the current one. `BigInt`
16
- * ids on the returned user (e.g. `userId`, `orgId`) are decimal strings.
17
- *
18
- * **Public — no session required:** {@link login}, {@link register},
19
- * {@link confirmEmail}, {@link requestPasswordReset}, {@link resetPassword}, and
20
- * {@link resendConfirmationEmail}. **Require a valid session:** {@link logout},
21
- * {@link logoutAllDevices}, and {@link changePassword}, which otherwise throw
22
- * {@link CrowdyGraphQLError} with `UNAUTHENTICATED` when the bearer token is
23
- * missing, expired, or revoked.
24
- */
1
+ import { parse } from 'graphql';
2
+ import { LogoutAllDevicesDocument, LogoutDocument } from '../generated/graphql.js';
3
+ const AUTH_RESPONSE_FIELDS = 'token gameTokenId user { userId email gamertag }';
4
+ const IDENTITY_FIELDS = 'identityId provider subject email emailVerified createdAt lastLoginAt';
5
+ const RequestLoginLinkDocument = parse(`mutation RequestLoginLink($input: RequestLoginLinkInput!) { requestLoginLink(input: $input) { sent devToken } }`);
6
+ const CompleteLoginLinkDocument = parse(`mutation CompleteLoginLink($input: CompleteLoginLinkInput!) { completeLoginLink(input: $input) { ${AUTH_RESPONSE_FIELDS} } }`);
7
+ const SocialLoginStartDocument = parse(`mutation SocialLoginStart($input: SocialLoginStartInput!) { socialLoginStart(input: $input) { authorizeUrl state } }`);
8
+ const SocialLoginCompleteDocument = parse(`mutation SocialLoginComplete($input: SocialLoginCompleteInput!) { socialLoginComplete(input: $input) { ${AUTH_RESPONSE_FIELDS} } }`);
9
+ const DevLoginDocument = parse(`mutation DevLogin($input: DevLoginInput!) { devLogin(input: $input) { ${AUTH_RESPONSE_FIELDS} } }`);
10
+ const AvailableLoginProvidersDocument = parse(`query AvailableLoginProviders { availableLoginProviders }`);
11
+ const MyIdentitiesDocument = parse(`query MyIdentities { myIdentities { ${IDENTITY_FIELDS} } }`);
12
+ const LinkIdentityDocument = parse(`mutation LinkIdentity($input: LinkIdentityInput!) { linkIdentity(input: $input) { ${IDENTITY_FIELDS} } }`);
13
+ const UnlinkIdentityDocument = parse(`mutation UnlinkIdentity($identityId: String!) { unlinkIdentity(identityId: $identityId) }`);
25
14
  export class AuthAPI {
26
15
  constructor(graphql, session) {
27
16
  this.graphql = graphql;
28
17
  this.session = session;
29
18
  }
30
- /**
31
- * Authenticate with email + password and start a new session. **Public** — no
32
- * existing session required.
33
- *
34
- * On success the returned `token` is minted **and** stored on the shared
35
- * session state, so subsequent calls on any sub-client (management-api or
36
- * game-api) carry it automatically — no need to call {@link setToken}.
37
- *
38
- * @param input - Credentials ({@link LoginUserInput}): `email` and `password`
39
- * (min 8 characters).
40
- * @returns An {@link AuthResponse}: the opaque session `token` (sent as
41
- * `Authorization: Bearer <token>`), `gameTokenId` (the session row id, a
42
- * string), and the authenticated `user`.
43
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` on invalid credentials, or
44
- * `BAD_USER_INPUT` on malformed input.
45
- * @example
46
- * ```ts
47
- * const { user } = await client.auth.login({ email, password });
48
- * // the session token is now stored; later calls are authenticated for you
49
- * await client.users.me();
50
- * ```
51
- */
52
- async login(input) {
53
- const data = await this.graphql.request(LoginDocument, { input });
54
- if (data.login?.token) {
55
- this.session.setToken(data.login.token);
56
- }
57
- return data.login;
58
- }
59
- /**
60
- * Create a new (initially unconfirmed) account, send a confirmation email, and
61
- * return a session for immediate login. **Public** — no existing session
62
- * required. Same token-persistence behaviour as {@link login}: the new `token`
63
- * is stored on the shared session state automatically.
64
- *
65
- * @param input - New-account details ({@link RegisterUserInput}): `email`
66
- * (where the confirmation email is sent), `password` (min 8 characters), and
67
- * an optional initial `gamertag` (min 3 characters; can also be set later via
68
- * `client.users.updateGamertag`).
69
- * @returns An {@link AuthResponse} (session `token`, `gameTokenId`, and the new
70
- * `user`).
71
- * @throws {CrowdyGraphQLError} `BAD_USER_INPUT` if the email already exists or
72
- * the input is invalid.
73
- */
74
- async register(input) {
75
- const data = await this.graphql.request(RegisterDocument, { input });
76
- if (data.register?.token) {
77
- this.session.setToken(data.register.token);
78
- }
79
- return data.register;
19
+ /** The federated sign-in providers currently enabled (e.g. `['google']`). */
20
+ async availableLoginProviders() {
21
+ const data = await this.graphql.request(AvailableLoginProvidersDocument);
22
+ return data.availableLoginProviders;
80
23
  }
81
24
  /**
82
- * Single-device logout: revoke the `game_tokens` row that authenticated this
83
- * request; other devices/tokens are unaffected. After a successful server-side
84
- * revoke the in-memory token is cleared from the shared session state so the
85
- * other sub-clients stop using it. Requires a valid session.
86
- *
87
- * @returns `true` if a token was revoked, or `false` if the request carried no
88
- * game token.
89
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` if the session is invalid.
25
+ * Passwordless: email the address a one-time magic sign-in link (creating the
26
+ * account on first sign-in). Always resolves `sent: true` (no enumeration). In
27
+ * development (`DEV_AUTH_BYPASS`) the response also carries `devToken`, the
28
+ * token to pass straight to {@link completeLoginLink} without an inbox.
90
29
  */
91
- async logout() {
92
- const data = await this.graphql.request(LogoutDocument);
93
- this.session.setToken(null);
94
- return data.logout;
30
+ async requestLoginLink(input) {
31
+ const data = await this.graphql.request(RequestLoginLinkDocument, { input });
32
+ return data.requestLoginLink;
95
33
  }
96
- /**
97
- * Revoke **every** active session for the authenticated user (deletes all
98
- * their `game_tokens` rows and records revocations). Requires a valid session;
99
- * use {@link logout} to end only the current one.
100
- *
101
- * Note: unlike {@link logout}, this does not clear the SDK's in-memory token
102
- * call {@link setToken}`(null)` afterwards if you also want to drop it locally.
103
- *
104
- * @returns `true` on success.
105
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` if the session is invalid.
106
- */
107
- async logoutAllDevices() {
108
- const data = await this.graphql.request(LogoutAllDevicesDocument);
109
- return data.logoutAllDevices;
110
- }
111
- /**
112
- * Confirm a user's email address using the token from the confirmation email.
113
- * **Public** — the token itself authorizes the call.
114
- *
115
- * @param token - The confirmation token from the emailed link.
116
- * @returns `true` on success, or `false` if the token is invalid or expired.
117
- * @throws {CrowdyGraphQLError} on transport/validation failures (invalid or
118
- * expired tokens resolve to `false` rather than throwing).
119
- */
120
- async confirmEmail(token) {
121
- const data = await this.graphql.request(ConfirmEmailDocument, { token });
122
- return data.confirmEmail;
34
+ /** Complete a magic-link sign-in; stores the session token on success. */
35
+ async completeLoginLink(token) {
36
+ const data = await this.graphql.request(CompleteLoginLinkDocument, {
37
+ input: { token },
38
+ });
39
+ if (data.completeLoginLink?.token)
40
+ this.session.setToken(data.completeLoginLink.token);
41
+ return data.completeLoginLink;
123
42
  }
124
43
  /**
125
- * Start the password-reset flow by emailing a reset link to the address.
126
- * **Public**. Always returns `true` regardless of whether the email exists or
127
- * is confirmed, to prevent account enumeration.
128
- *
129
- * @param email - Email address to send the password-reset link to.
130
- * @returns `true` (always, even when no such account exists).
131
- * @throws {CrowdyGraphQLError} on transport/validation failures.
44
+ * Begin a federated (social) sign-in. Returns an `authorizeUrl` to redirect the
45
+ * user to and an opaque `state` to round-trip back to {@link socialLoginComplete}.
132
46
  */
133
- async requestPasswordReset(email) {
134
- const data = await this.graphql.request(RequestPasswordResetDocument, {
135
- email,
47
+ async socialLoginStart(provider, redirectUri) {
48
+ const data = await this.graphql.request(SocialLoginStartDocument, {
49
+ input: { provider, redirectUri },
136
50
  });
137
- return data.requestPasswordReset;
51
+ return data.socialLoginStart;
138
52
  }
139
- /**
140
- * Complete a password reset using the reset token and a new password.
141
- * **Public** the reset token authorizes the call. Existing sessions are
142
- * **not** revoked.
143
- *
144
- * @param input - {@link ResetPasswordInput}: the `token` from the emailed reset
145
- * link and the `newPassword` to set (min 8 characters).
146
- * @returns `true` on success.
147
- * @throws {CrowdyGraphQLError} `BAD_USER_INPUT` if the token is invalid or
148
- * expired.
149
- */
150
- async resetPassword(input) {
151
- const data = await this.graphql.request(ResetPasswordDocument, {
53
+ /** Complete a federated sign-in from the provider callback; stores the token. */
54
+ async socialLoginComplete(input) {
55
+ const data = await this.graphql.request(SocialLoginCompleteDocument, {
152
56
  input,
153
57
  });
154
- return data.resetPassword;
58
+ if (data.socialLoginComplete?.token)
59
+ this.session.setToken(data.socialLoginComplete.token);
60
+ return data.socialLoginComplete;
155
61
  }
156
62
  /**
157
- * Re-send the email-confirmation link. **Public**. Always returns `true`
158
- * regardless of whether the account exists or is already confirmed (prevents
159
- * enumeration); the email is only actually sent for existing unconfirmed
160
- * accounts.
161
- *
162
- * @param email - Email address of the account to re-send confirmation to.
163
- * @returns `true` (always).
164
- * @throws {CrowdyGraphQLError} on transport/validation failures.
63
+ * DEV ONLY bypass sign-in (active only when the server has `DEV_AUTH_BYPASS`).
64
+ * Returns a session for `email` without email/social verification; stores it.
65
+ * Throws `FORBIDDEN` when the bypass is disabled (e.g. production).
165
66
  */
166
- async resendConfirmationEmail(email) {
167
- const data = await this.graphql.request(ResendConfirmationEmailDocument, {
168
- email,
67
+ async devLogin(email) {
68
+ const data = await this.graphql.request(DevLoginDocument, {
69
+ input: { email },
169
70
  });
170
- return data.resendConfirmationEmail;
71
+ if (data.devLogin?.token)
72
+ this.session.setToken(data.devLogin.token);
73
+ return data.devLogin;
171
74
  }
172
- /**
173
- * Change the authenticated user's password after verifying the current one.
174
- * Requires a valid session. Existing sessions are **not** revoked.
175
- *
176
- * @param currentPassword - The user's current password, for verification.
177
- * @param newPassword - The new password to set (min 8 characters).
178
- * @returns `true` on success.
179
- * @throws {CrowdyGraphQLError} `UNAUTHENTICATED` without a valid session, or
180
- * `BAD_USER_INPUT` if the current password is wrong.
181
- */
182
- async changePassword(currentPassword, newPassword) {
183
- const data = await this.graphql.request(ChangePasswordDocument, {
184
- currentPassword,
185
- newPassword,
75
+ /** The signed-in user's linked sign-in identities. Requires a session. */
76
+ async myIdentities() {
77
+ const data = await this.graphql.request(MyIdentitiesDocument);
78
+ return data.myIdentities;
79
+ }
80
+ /** Link an additional federated identity (from a social callback). */
81
+ async linkIdentity(input) {
82
+ const data = await this.graphql.request(LinkIdentityDocument, { input });
83
+ return data.linkIdentity;
84
+ }
85
+ /** Unlink a federated identity (cannot remove the last sign-in method). */
86
+ async unlinkIdentity(identityId) {
87
+ const data = await this.graphql.request(UnlinkIdentityDocument, {
88
+ identityId,
186
89
  });
187
- return data.changePassword;
90
+ return data.unlinkIdentity;
188
91
  }
189
- /**
190
- * Imperatively replace the in-memory bearer token on the shared session state
191
- * (e.g. to rehydrate a token persisted to disk). Affects every sub-client.
192
- * Local only — performs no network call. Pass `null` to clear it.
193
- *
194
- * @param token - The bearer token to use, or `null` to clear the session.
195
- */
92
+ /** Single-device logout; clears the in-memory token on success. */
93
+ async logout() {
94
+ const data = await this.graphql.request(LogoutDocument);
95
+ this.session.setToken(null);
96
+ return data.logout;
97
+ }
98
+ /** Revoke every active session for the user. Requires a session. */
99
+ async logoutAllDevices() {
100
+ const data = await this.graphql.request(LogoutAllDevicesDocument);
101
+ return data.logoutAllDevices;
102
+ }
103
+ /** Imperatively set the in-memory bearer token (e.g. rehydrate). */
196
104
  setToken(token) {
197
105
  this.session.setToken(token);
198
106
  }
199
- /**
200
- * Read the current in-memory bearer token from the shared session state. Local
201
- * only — performs no network call.
202
- *
203
- * @returns The current bearer token, or `null` if none is set.
204
- */
107
+ /** Read the current in-memory bearer token. */
205
108
  getToken() {
206
109
  return this.session.getToken();
207
110
  }