@softwarepatterns/am 0.0.2 → 0.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/auth.ts"],"sourcesContent":[null],"names":["STATE","Symbol","resolveStorage","storageConfig","window","localStorage","getBrowserLocalStorage","readJson","storage","key","raw","JSON","parse","safeParse","getItem","writeJson","value","setItem","stringify","removeKey","removeItem","writeTokensIfNewer","next","curRaw","cur","isSessionTokens","expiresAt","writeProfileIfNewer","isSessionProfile","lastUpdatedAt","x","accessToken","refreshToken","expiresIn","tokenType","id","accountId","status","identity","getState","session","camelCaseStr","str","replace","_","letter","toUpperCase","camelCaseObj","input","Array","isArray","map","item","obj","result","Object","keys","prototype","hasOwnProperty","call","snakeCaseStr","toLowerCase","snakeCaseObj","AuthError","Error","constructor","problem","super","title","this","name","freeze","type","code","detail","invalidParams","defaultConfig","fetchFn","f","globalThis","fetch","bind","async","defaultFetchFn","baseUrl","earlyRefreshMs","tokensStorageKey","profileStorageKey","handleResponse","res","json","contentType","headers","get","includes","readJsonSafe","ok","isProblemJson","statusText","undefined","toGenericProblem","getProblemJson","unauthGet","path","query","qs","URLSearchParams","toString","url","method","Accept","unauthPost","body","authFetch","state","init","config","Authorization","tokens","isExpired","early","Math","min","max","Date","now","refresh","cleared","refreshPromise","toSessionTokens","onRefresh","doRefresh","isUnauthenticatedAuthError","e","authFetchWithRefresh","e2","onUnauthenticated","authGet","toSessionProfile","profile","handleAuthenticationResponse","AuthSession","initial","merged","profilePromise","setState","restoreSession","tokensRaw","profileRaw","clear","clearAuth","idToken","toJSON","fromJSON","refetchProfile","onProfileRefetch","doRefetchProfile","sendVerificationEmail","authPost","user","Am","options","createAuthSession","acceptInvite","checkEmail","csrfSession","csrfToken","signIn","signInWithToken","token","signUp","resetPassword","sendMagicLink","sendPasswordReset"],"mappings":"AAaA,MACMA,EAAQC,OAAO,SAwCrB,SAASC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,CACXC,EACArD,GAEA,OAAO,IAAI4C,EAAG5C,GAAQoD,gBAAgBC,EACxC,CAWA,qBAAMD,CAAgBC,GACpB,MAAMR,EAAU5F,KAAK4F,QACfnB,EAAUF,QACRtC,EAAU2D,EAAS,2BAA4B,CACnDQ,WAIJ,OAAO,IAAI5B,EAAYC,EAASmB,EAClC,CAUA,oBAAanC,CACX9F,EACAoF,GAEA,OAAO,IAAI4C,EAAG5C,GAAQU,QAAQ9F,EAChC,CAUA,aAAM8F,CAAQ9F,GACZ,OAAOiG,QACClB,EAAW1C,KAAK4F,QAAS,gBAAiB,CAC9CjI,iBAGN,CASA,mBAAa0I,CACX1D,EAMAI,GAEA,OAAO,IAAI4C,EAAG5C,GAAQsD,OAAO1D,EAC/B,CASA,YAAM0D,CAAO1D,GAMX,MAAM8B,EAAUF,QACR7B,EAAW1C,KAAK4F,QAAS,gBAAiBjD,IAGlD,OAAO,IAAI6B,EAAYC,EAASzE,KAAK4F,QACvC,CASA,0BAAaU,CACX3D,EAIAI,GAEA,OAAO,IAAI4C,EAAG5C,GAAQuD,cAAc3D,EACtC,CASA,mBAAM2D,CAAc3D,GAIlB,OAAOD,EAAW1C,KAAK4F,QAAS,uBAAwBjD,EAC1D,CASA,0BAAa4D,CACX5D,EAKAI,GAEA,OAAO,IAAI4C,EAAG5C,GAAQwD,cAAc5D,EACtC,CASA,mBAAM4D,CAAc5D,GAKlB,OAAOD,EAAW1C,KAAK4F,QAAS,wBAAyBjD,EAC3D,CAQA,8BAAa6D,CACX7D,EAKAI,GAEA,OAAO,IAAI4C,EAAG5C,GAAQyD,kBAAkB7D,EAC1C,CAQA,uBAAM6D,CAAkB7D,GAKtB,OAAOD,EAAW1C,KAAK4F,QAAS,4BAA6BjD,EAC/D"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/auth.ts"],"sourcesContent":[null],"names":["SESSION_STATE","Symbol","AUTH_SESSION","AUTH_STATE","EMITTER","resolveStorage","storageConfig","window","localStorage","getBrowserLocalStorage","readJson","storage","key","raw","JSON","parse","safeParse","getItem","writeJson","value","setItem","stringify","removeKey","removeItem","writeTokensIfNewer","next","curRaw","cur","isSessionTokens","expiresAt","writeProfileIfNewer","isSessionProfile","lastUpdatedAt","x","accessToken","refreshToken","expiresIn","tokenType","id","accountId","status","identity","getSessionState","session","getAuthState","am","setAuthSession","sessionState","event","set","listeners","fn","console","warn","setSessionStateEmitter","emitSessionStateEvent","emit","camelCaseStr","str","replace","_","letter","toUpperCase","camelCaseObj","input","Array","isArray","map","item","obj","result","Object","keys","prototype","hasOwnProperty","call","snakeCaseStr","toLowerCase","snakeCaseObj","AuthError","Error","constructor","problem","super","title","this","name","freeze","type","code","detail","invalidParams","defaultConfig","fetchFn","f","globalThis","fetch","bind","async","defaultFetchFn","baseUrl","earlyRefreshMs","tokensStorageKey","profileStorageKey","fetchSessionResponse","state","init","config","token","headers","Headers","withBearer","tokens","fetchSessionResponseEnsureFresh","isExpired","refresh","res","cleared","e","isUnauthenticatedAuthError","handleJsonOrThrow","json","contentType","get","includes","readJsonSafe","ok","isProblemJson","statusText","undefined","toGenericProblem","getProblemJson","getSessionJsonEnsureFresh","unauthGet","path","query","qs","URLSearchParams","toString","url","method","Accept","unauthPost","body","early","Math","min","max","Date","now","refreshPromise","toSessionTokens","doRefresh","toSessionProfile","profile","doRefetchProfile","authGet","handleAuthenticationResponse","AuthSession","initial","merged","profilePromise","setSessionState","clear","clearAuth","toJSON","fromJSON","refetchProfile","sendVerificationEmail","authPost","Am","createSession","restoreSession","tokensRaw","profileRaw","on","Set","add","delete","acceptInvite","checkEmail","csrfSession","csrfToken","signIn","signInWithToken","signUp","resetPassword","sendMagicLink","sendPasswordReset"],"mappings":"AAWA,MACMA,EAAgBC,OAAO,iBACvBC,EAAeD,OAAO,gBACtBE,EAAaF,OAAO,cACpBG,EAAUH,OAAO,WAiDvB,SAASI,EAAeC,GACtB,OAAKA,EACiB,iBAAlBA,EAZN,WACE,IACE,MAAsB,oBAAXC,OAA+B,KACr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9C,CAOA,eAAM2E,GACJ,OAAOjD,EAAUzF,EAAayC,MAAMsB,OAAQ,mBAC9C,CAOA,YAAM4E,CAAOxC,GAMX,MAAMpC,EAAS/D,EAAayC,MAAMsB,OAC5BoD,EAAUF,QACRf,EAAWnC,EAAQ,gBAAiBoC,IAGtCpG,EAAU,IAAImH,EAAYC,EAASpD,GAEzC,OADA7D,EAAeuC,KAAM1C,GACdA,CACT,CAOA,qBAAM6I,CAAgB5E,GACpB,MAAMD,EAAS/D,EAAayC,MAAMsB,OAC5BoD,EAAUF,QACRxB,EAAU1B,EAAQ,2BAA4B,CAClDC,WAIEjE,EAAU,IAAImH,EAAYC,EAASpD,GAEzC,OADA7D,EAAeuC,KAAM1C,GACdA,CACT,CAOA,YAAM8I,CAAO1C,GAMX,MAAMpC,EAAS/D,EAAayC,MAAMsB,OAC5BoD,EAAUF,QACRf,EAAWnC,EAAQ,gBAAiBoC,IAGtCpG,EAAU,IAAImH,EAAYC,EAASpD,GAEzC,OADA7D,EAAeuC,KAAM1C,GACdA,CACT,CAKA,mBAAM+I,CAAc3C,GAIlB,OAAOD,EAAWlG,EAAayC,MAAMsB,OAAQ,uBAAwBoC,EACvE,CAKA,mBAAM4C,CAAc5C,GAKlB,OAAOD,EAAWlG,EAAayC,MAAMsB,OAAQ,wBAAyBoC,EACxE,CAKA,uBAAM6C,CAAkB7C,GAKtB,OAAOD,EACLlG,EAAayC,MAAMsB,OACnB,4BACAoC,EAEJ"}
@@ -1,38 +1,25 @@
1
- import type { Authentication, ClientId, EmailCheckStatus, LoginMethod, ProblemDetails, SessionProfile, SessionTokens, UserId, UserResource, StorageLike } from "./types";
1
+ import type { Authentication, ClientId, EmailCheckStatus, LoginMethod, ProblemDetails, SessionProfile, SessionTokens, StorageLike } from "./types";
2
2
  type StorageConfig = StorageLike | "localStorage" | null | undefined;
3
3
  type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
4
4
  type Config = {
5
5
  baseUrl: string;
6
6
  earlyRefreshMs: number;
7
7
  fetchFn: FetchFn;
8
- onRefresh?: (tokens: SessionTokens) => void | Promise<void>;
9
- onProfileRefetch?: (profile: SessionProfile) => void | Promise<void>;
10
- onUnauthenticated?: (e: AuthError) => void | Promise<void>;
11
8
  profileStorageKey: string;
12
9
  storage: StorageConfig;
13
10
  tokensStorageKey: string;
14
11
  };
12
+ type AuthEventMap = {
13
+ refresh: SessionTokens;
14
+ profileChange: SessionProfile;
15
+ unauthenticated: AuthError;
16
+ sessionChange: AuthSession | null;
17
+ };
15
18
  /**
16
- * Error type for authentication-related failures.
17
- *
18
- * Always thrown on non-2xx responses from auth endpoints. Contains structured ProblemDetails
19
- * from the server when available.
20
- *
21
- * Most 400 errors will also contain `invalidParams` for parameters that caused
22
- * the error, which can be used to display field-level validation messages.
19
+ * AuthError represents structured authentication failures from Accountmaker endpoints.
23
20
  *
24
- * Note that network errors, timeouts, etc. will throw other Error types (e.g. TypeError) unrelated
25
- * to AuthError.
26
- *
27
- * Note that HTTP error codes are distinctly:
28
- * - 400: Client error (bad request, invalid input, etc.)
29
- * - 401: Unauthenticated (we don't know who you are)
30
- * - 402: Payment required (e.g. billing issue)
31
- * - 403: Unauthorized (we know who you are, but you don't have permission)
32
- * - 404: Not found
33
- * - 409: Conflict (email already registered, user already invited, etc.)
34
- * - 429: Too many requests (rate limiting)
35
- * - 500: Internal server error (server's fault)
21
+ * AuthError wraps RFC 7807 Problem Details. invalidParams may be present for field-level validation.
22
+ * Network failures throw other error types.
36
23
  *
37
24
  * Also note that the `type` field often contains a URI that points to documentation about the
38
25
  * specific error type, including how to resolve it, code samples, and links to the RFCs or other
@@ -55,6 +42,16 @@ type Config = {
55
42
  * }
56
43
  * }
57
44
  * ```
45
+ *
46
+ * Note that HTTP error codes are distinctly:
47
+ * - 400: Client error (bad request, invalid input, etc.)
48
+ * - 401: Unauthenticated (we don't know who you are)
49
+ * - 402: Payment required (e.g. billing issue)
50
+ * - 403: Unauthorized (we know who you are, but you don't have permission)
51
+ * - 404: Not found
52
+ * - 409: Conflict (email already registered, user already invited, etc.)
53
+ * - 429: Too many requests (rate limiting)
54
+ * - 500: Internal server error (server's fault)
58
55
  */
59
56
  export declare class AuthError extends Error {
60
57
  readonly problem: ProblemDetails;
@@ -67,45 +64,20 @@ export declare class AuthError extends Error {
67
64
  get invalidParams(): ProblemDetails["invalidParams"] | undefined;
68
65
  }
69
66
  /**
70
- * You receive an AuthSession after successful sign-in/register/etc.
67
+ * AuthSession represents an authenticated user with automatic token refresh and persisted state.
71
68
  *
72
- * It contains the current access token, user profile, and methods to perform authorized
73
- * requests.
74
- *
75
- * Features:
76
- * - session.fetch() will always use a valid access token (refreshing automatically)
77
- * - All non-2xx responses throw AuthError
78
- * - Tokens and profile are automatically persisted to storage (if configured)
69
+ * AuthSession owns tokens, profile data, refresh logic, and authenticated requests.
79
70
  */
80
71
  export declare class AuthSession {
81
72
  constructor(initial: Authentication, config: Partial<Config>);
82
- /**
83
- * Restores an AuthSession from persisted storage. Returns null if no valid session
84
- * is found.
85
- *
86
- * @example
87
- * ```ts
88
- * const session = AuthSession.restoreSession();
89
- * if (session) {
90
- * console.log("Restored session for user:", session.profile);
91
- * } else {
92
- * console.log("No valid session found.");
93
- * }
94
- * ```
95
- */
96
- static restoreSession(config?: Partial<Config>): AuthSession | null;
97
73
  /**
98
74
  * Removes all persisted data (tokens, profile) from storage, and prevents future
99
- * refreshs of token and profile data. Does NOT clear current token or profile data from the
75
+ * refreshes of token and profile data. Does NOT clear current token or profile data from the
100
76
  * session memory, but effectively deactivates the session for future use.
101
77
  */
102
78
  clear(): void;
103
- accessToken(): string;
104
- refreshToken(): string;
105
- idToken(): string | undefined;
106
- expiresIn(): number;
107
- expiresAt(): Date;
108
- profile(): SessionProfile | null;
79
+ get tokens(): SessionTokens;
80
+ get profile(): SessionProfile;
109
81
  toJSON(): Authentication;
110
82
  /**
111
83
  * Creates an AuthSession from existing authentication data. Useful for restoring
@@ -118,38 +90,31 @@ export declare class AuthSession {
118
90
  */
119
91
  isExpired(): boolean;
120
92
  /**
121
- * Perform an authenticated fetch. Used to call your own APIs with the current
122
- * session's access token. Any service can validate the token against Am's public
123
- * keys at https://api.accountmaker.com/.well-known/jwks.json?client_id={clientId}
124
- *
125
- * Automatically:
126
- * - Adds Authorization header
127
- * - Refreshes token if expired
128
- * - Retries once on 401 if refresh succeeds
129
- *
130
- * Assumes the response is JSON and parses it. Throws AuthError on non-2xx responses.
93
+ * Performs standard fetch() with a Bearer token and automatic refresh.
131
94
  *
132
- * If the error is a RFC 7807 Problem Details response, the AuthError.problem
133
- * will contain the full details.
95
+ * Returns Response, does not parse the body, does not throw for HTTP status codes.
96
+ * Throws AuthError when refresh fails, trows runtime errors on network failure.
134
97
  *
135
98
  * @example
136
99
  * ```ts
137
- * const res = await session.fetch('/api/projects');
100
+ * const res = await session.fetch("/api/projects");
138
101
  * const projects = await res.json();
139
102
  * ```
140
103
  *
141
- * Throws AuthError on network errors, etc.
142
- * @throws AuthError
104
+ * Any service can validate tokens using:
105
+ * https://api.accountmaker.com/.well-known/jwks.json?client_id={clientId}
143
106
  */
144
- fetch(url: string | URL, init?: RequestInit): Promise<any>;
107
+ fetch(url: string | URL, init?: RequestInit): Promise<Response>;
145
108
  /**
146
- * Refreshes the access token using the refresh token. Updates the stored tokens on
147
- * success. This is called automatically by fetch() if the token is expired or close to
148
- * expiring.
109
+ * Replaces the access token using the refresh token.
110
+ *
111
+ * It is called automatically by all other methods when the access token is expired or near expiry.
149
112
  */
150
113
  refresh(): Promise<void>;
151
114
  /**
152
- * Refetches the user's profile from the server and updates the stored profile.
115
+ * refetchProfile() replaces the cached profile with server state.
116
+ *
117
+ * Concurrent calls are deduplicated.
153
118
  *
154
119
  * @example
155
120
  * ```ts
@@ -162,29 +127,19 @@ export declare class AuthSession {
162
127
  */
163
128
  refetchProfile(): Promise<void>;
164
129
  /**
165
- * Sends a verification email to the user's primary email address. This only succeeds if
166
- * called by the currently authenticated user or an account admin.
130
+ * Requests a verification email for the current user.
167
131
  *
168
132
  * Throws AuthError on network errors, etc.
169
133
  * @throws AuthError
170
134
  */
171
135
  sendVerificationEmail(): Promise<void>;
172
- /**
173
- * Fetches a user by ID.
174
- *
175
- * Throws AuthError on invalid user ID, network errors, etc.
176
- * @throws AuthError
177
- */
178
- user(id: UserId): Promise<UserResource>;
179
136
  }
180
137
  /**
181
- * Use `Am` to perform initial sign-in, registration, password reset flows, magic links,
182
- * invite acceptance, and other unauthenticated actions.
138
+ * Am runs authentication flows and produces AuthSession.
183
139
  *
184
- * Once authentication succeeds, these methods return an `AuthSession` that you use
185
- * for all subsequent authenticated requests.
140
+ * Use Am before a session exists (sign-in, sign-up, magic link, invites, password reset, CSRF).
186
141
  *
187
- * Example:
142
+ * @example
188
143
  * ```ts
189
144
  * const am = new Am();
190
145
  * const session = await am.signIn({ email: 'user@example.com', password: 'secret' });
@@ -192,68 +147,55 @@ export declare class AuthSession {
192
147
  * ```
193
148
  */
194
149
  export declare class Am {
195
- private options;
196
150
  constructor(config?: Partial<Config>);
197
151
  /**
198
- * Creates an AuthSession from existing authentication data. Useful for restoring
199
- * a session from custom storage or creating a session from custom server-provided data.
152
+ * session returns the current AuthSession or null.
153
+ *
154
+ * Use restoreSession() to load from storage.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * const session = am.session;
159
+ * if (!session) throw new Error("Not authenticated");
160
+ * ```
200
161
  */
201
- static createAuthSession(initial: Authentication, config?: Partial<Config>): AuthSession;
162
+ get session(): AuthSession | null;
202
163
  /**
203
- * Creates an AuthSession from existing authentication data. Useful for restoring
204
- * a session from custom storage or creating a session from custom server-provided data.
164
+ * Constructs AuthSession from existing tokens and profile.
165
+ *
166
+ * Use this after a server-side auth handshake or custom persistence.
205
167
  */
206
- createAuthSession(initial: Authentication): AuthSession;
168
+ createSession(initial: Authentication): AuthSession;
207
169
  /**
208
- * Accepts an invitation to join an account. On success, returns an AuthSession
209
- * containing fresh tokens and profile. Tokens are automatically persisted (if
210
- * storage is enabled).
170
+ * restoreSession loads AuthSession from storage or returns null.
211
171
  *
212
- * Throws AuthError on invalid or expired token, etc.
213
- * @throws AuthError
172
+ * Invalid or partial stored data is cleared.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * const am = new Am({ storage: 'localStorage' });
177
+ * const session = am.restoreSession();
178
+ * if (session) session.fetch("/api/me");
179
+ * ```
214
180
  */
215
- static acceptInvite(query: {
216
- clientId: ClientId;
217
- token: string;
218
- }, config?: Partial<Config>): Promise<AuthSession>;
181
+ restoreSession(): AuthSession | null;
219
182
  /**
220
- * Accepts an invitation to join an account. On success, returns an AuthSession
221
- * containing fresh tokens and profile. Tokens are automatically persisted (if
222
- * storage is enabled).
183
+ * Subscribes to auth events and returns an unsubscribe function.
184
+ */
185
+ on<K extends keyof AuthEventMap>(event: K, fn: (v: AuthEventMap[K]) => void): () => boolean;
186
+ /**
187
+ * acceptInvite exchanges an invite token for a fresh AuthSession.
223
188
  *
224
- * Throws AuthError on invalid or expired token, etc.
225
- * @throws AuthError
189
+ * Throws AuthError on invalid, expired, or already-used tokens.
226
190
  */
227
191
  acceptInvite(query: {
228
192
  clientId: ClientId;
229
193
  token: string;
230
194
  }): Promise<AuthSession>;
231
195
  /**
232
- * Checks the status of an email address for authentication purposes. Indicates whether the
233
- * email is associated with an active account, and what login methods are preferred and
234
- * available for that user. This can be used to enforce login expierences for enterprise SSO or
235
- * to prefer passwordless login methods.
236
- *
237
- * Throws AuthError on invalid client ID, network errors, etc.
238
- * @throws AuthError
239
- */
240
- static checkEmail(body: {
241
- clientId: ClientId;
242
- email: string;
243
- csrfToken?: string;
244
- }, config?: Partial<Config>): Promise<{
245
- status: EmailCheckStatus;
246
- preferred: LoginMethod[];
247
- available: LoginMethod[];
248
- }>;
249
- /**
250
- * Checks the status of an email address for authentication purposes. Indicates whether the
251
- * email is associated with an active account, and what login methods are preferred and
252
- * available for that user. This can be used to enforce login expierences for enterprise SSO or
253
- * to prefer passwordless login methods.
196
+ * checkEmail returns how an email should authenticate for this client.
254
197
  *
255
- * Throws AuthError on invalid client ID, network errors, etc.
256
- * @throws AuthError
198
+ * Use this to choose password vs magic link vs SSO before rendering a login form.
257
199
  */
258
200
  checkEmail(body: {
259
201
  clientId: ClientId;
@@ -265,66 +207,25 @@ export declare class Am {
265
207
  available: LoginMethod[];
266
208
  }>;
267
209
  /**
268
- * When called, sets a httpOnly CSRF session cookie. Then when rendering a form, call csrfToken()
269
- * to get the signed token to include in the form. When the form is submitted, the server
270
- * will verify the signed token against the session cookie. This prevents a certain class
271
- * of CSRF attacks that rely on being able to read values from the target site.
272
- */
273
- static csrfSession(config?: Partial<Config>): Promise<{
274
- csrfToken: string;
275
- }>;
276
- /**
277
- * When called, sets a httpOnly CSRF session cookie. Then when rendering a form, call csrfToken()
278
- * to get the signed token to include in the form. When the form is submitted, the server
279
- * will verify the signed token against the session cookie. This prevents a certain class
280
- * of CSRF attacks that rely on being able to read values from the target site.
281
- */
282
- csrfSession(): Promise<{
283
- csrfToken: string;
284
- }>;
285
- /**
286
- * Fetches a signed CSRF token for use in forms. Call csrfSession() first to set a httpOnly CSRF
287
- * session cookie, then call this method to get the signed token, then include the token in your
288
- * form submissions. When the form is submitted, the server will verify the signed token against
289
- * the httpOnly session cookie. This prevents a certain class of CSRF attacks that rely on being
290
- * able to read values from the target site.
210
+ * Sets the httpOnly CSRF cookie.
291
211
  *
292
- * @throws AuthError
212
+ * Call csrfToken() next to fetch a signed token for form posts.
293
213
  */
294
- static csrfToken(config?: Partial<Config>): Promise<{
214
+ csrfSession(): Promise<{
295
215
  csrfToken: string;
296
216
  }>;
297
217
  /**
298
- * Fetches a signed CSRF token for use in forms. Call csrfSession() first to set a httpOnly CSRF
299
- * session cookie, then call this method to get the signed token, then include the token in your
300
- * form submissions. When the form is submitted, the server will verify the signed token against
301
- * the httpOnly session cookie. This prevents a certain class of CSRF attacks that rely on being
302
- * able to read values from the target site.
218
+ * Returns a signed CSRF token for form posts.
303
219
  *
304
- * @throws AuthError
220
+ * Call csrfSession() first to set the CSRF cookie.
305
221
  */
306
222
  csrfToken(): Promise<{
307
223
  csrfToken: string;
308
224
  }>;
309
225
  /**
310
- * On success, returns an AuthSession containing fresh tokens and profile.
311
- * Tokens are automatically persisted (if storage is enabled).
312
- *
313
- * Throws AuthError on invalid credentials, unverified email, etc.
314
- * @throws AuthError
315
- */
316
- static signIn(body: {
317
- clientId: ClientId;
318
- email: string;
319
- password: string;
320
- csrfToken?: string;
321
- }, config?: Partial<Config>): Promise<AuthSession>;
322
- /**
323
- * On success, returns an AuthSession containing fresh tokens and profile.
324
- * Tokens are automatically persisted (if storage is enabled).
226
+ * Authenticates with email and password and returns a new AuthSession.
325
227
  *
326
- * Throws AuthError on invalid credentials, unverified email, etc.
327
- * @throws AuthError
228
+ * Tokens and profile are persisted when storage is configured.
328
229
  */
329
230
  signIn(body: {
330
231
  clientId: ClientId;
@@ -333,62 +234,15 @@ export declare class Am {
333
234
  csrfToken?: string;
334
235
  }): Promise<AuthSession>;
335
236
  /**
336
- * Authenticates using a one-time token (e.g., magic link or invite token).
337
- *
338
- * On success, returns an AuthSession containing fresh tokens and profile.
339
- * Tokens are automatically persisted (if storage is enabled).
340
- *
341
- * Throws AuthError on invalid or expired token, etc.
342
- * @throws AuthError
343
- */
344
- static signInWithToken(token: string, config?: Partial<Config>): Promise<AuthSession>;
345
- /**
346
- * Authenticates using a one-time token (e.g., magic link or invite token).
237
+ * Authenticates with a one-time token and returns a new AuthSession.
347
238
  *
348
- * On success, returns an AuthSession containing fresh tokens and profile.
349
- * Tokens are automatically persisted (if storage is enabled).
350
- *
351
- * Throws AuthError on invalid or expired token, etc.
352
- * @throws AuthError
239
+ * Use this for magic links and similar one-time login flows.
353
240
  */
354
241
  signInWithToken(token: string): Promise<AuthSession>;
355
242
  /**
356
- * Manually refreshes session tokens using the provided refresh token. Does NOT
357
- * persist tokens. Use AuthSession.refresh() to refresh and persist tokens in an
358
- * existing session.
359
- *
360
- * Throws AuthError on invalid or expired refresh token, etc.
361
- * @throws AuthError
362
- */
363
- static refresh(refreshToken: string, config?: Partial<Config>): Promise<SessionTokens>;
364
- /**
365
- * Manually refreshes session tokens using the provided refresh token. Does NOT
366
- * persist tokens. Use AuthSession.refresh() to refresh and persist tokens in an
367
- * existing session.
368
- *
369
- * Throws AuthError on invalid or expired refresh token, etc.
370
- * @throws AuthError
371
- */
372
- refresh(refreshToken: string): Promise<SessionTokens>;
373
- /**
374
- * Successful registration immediately authenticates the user and returns an
375
- * AuthSession. Tokens are automatically persisted (if storage is enabled).
376
- *
377
- * Throws AuthError on invalid data, existing email, etc.
378
- * @throws AuthError
379
- */
380
- static signUp(body: {
381
- clientId: ClientId;
382
- email: string;
383
- password: string;
384
- csrfToken?: string;
385
- }, config?: Partial<Config>): Promise<AuthSession>;
386
- /**
387
- * Successful registration immediately authenticates the user and returns an
388
- * AuthSession. Tokens are automatically persisted (if storage is enabled).
243
+ * Creates a new user and returns a new AuthSession.
389
244
  *
390
- * Throws AuthError on invalid data, existing email, etc.
391
- * @throws AuthError
245
+ * Tokens and profile are persisted when storage is configured.
392
246
  */
393
247
  signUp(body: {
394
248
  clientId: ClientId;
@@ -397,45 +251,14 @@ export declare class Am {
397
251
  csrfToken?: string;
398
252
  }): Promise<AuthSession>;
399
253
  /**
400
- * Completes a password reset using the token received via email. On success,
401
- * the user's password is updated.
402
- *
403
- * Throws AuthError on invalid or expired token, weak password, etc.
404
- * @throws AuthError
405
- */
406
- static resetPassword(body: {
407
- token: string;
408
- newPassword: string;
409
- }, config?: Partial<Config>): Promise<void>;
410
- /**
411
- * Completes a password reset using the token received via email. On success,
412
- * the user's password is updated.
413
- *
414
- * Throws AuthError on invalid or expired token, weak password, etc.
415
- * @throws AuthError
254
+ * Sets a new password using a one-time reset token.
416
255
  */
417
256
  resetPassword(body: {
418
257
  token: string;
419
258
  newPassword: string;
420
259
  }): Promise<void>;
421
260
  /**
422
- * Sends a magic link email to the specified address. A magic link allows
423
- * passwordless authentication.
424
- *
425
- * Throws AuthError on invalid email format, etc.
426
- * @throws AuthError
427
- */
428
- static sendMagicLink(body: {
429
- clientId: ClientId;
430
- email: string;
431
- csrfToken?: string;
432
- }, config?: Partial<Config>): Promise<void>;
433
- /**
434
- * Sends a magic link email to the specified address. A magic link allows
435
- * passwordless authentication.
436
- *
437
- * Throws AuthError on invalid email format, etc.
438
- * @throws AuthError
261
+ * Sends a one-time sign-in link to an email address.
439
262
  */
440
263
  sendMagicLink(body: {
441
264
  clientId: ClientId;
@@ -443,21 +266,7 @@ export declare class Am {
443
266
  csrfToken?: string;
444
267
  }): Promise<void>;
445
268
  /**
446
- * Sends a password reset email to the specified address.
447
- *
448
- * Throws AuthError on invalid email format, etc.
449
- * @throws AuthError
450
- */
451
- static sendPasswordReset(body: {
452
- clientId: ClientId;
453
- email: string;
454
- csrfToken?: string;
455
- }, config?: Partial<Config>): Promise<void>;
456
- /**
457
- * Sends a password reset email to the specified address.
458
- *
459
- * Throws AuthError on invalid email format, etc.
460
- * @throws AuthError
269
+ * Sends a password reset link to an email address.
461
270
  */
462
271
  sendPasswordReset(body: {
463
272
  clientId: ClientId;
@@ -80,6 +80,7 @@ export type AccountStatus = "active" | "trial" | "past_due" | "suspended" | "clo
80
80
  */
81
81
  export type AccountResource = {
82
82
  id: AccountId;
83
+ parentId: AccountId | null;
83
84
  /** Display name chosen by the account owner */
84
85
  name: string | null;
85
86
  /** URL to the account's avatar image */
@@ -98,7 +99,7 @@ export type AccountResource = {
98
99
  * - suspended: Access restricted due to billing or policy
99
100
  * - closed: Permanently closed
100
101
  */
101
- export type UserStatus = "active" | "trial" | "past_due" | "suspended" | "closed";
102
+ export type UserStatus = "active" | "disabled" | "suspended" | "deleted";
102
103
  /**
103
104
  * A reference to a user. Will not be deleted even due to GDPR requests or account closures,
104
105
  * to maintain referential integrity in audit logs and historical records.
@@ -174,7 +175,9 @@ export type SessionTokens = {
174
175
  export type SessionProfile = UserResource & {
175
176
  identity: UserIdentity | null;
176
177
  emailCredentials: EmailCredential[];
177
- memberships: Membership[];
178
+ memberships: (Membership & {
179
+ account: AccountResource;
180
+ })[];
178
181
  /** Currently active membership in the accessToken (determined by preferredMembershipId or context) */
179
182
  activeMembership: Membership | null;
180
183
  lastUpdatedAt: number;
@@ -184,7 +187,7 @@ export type SessionProfile = UserResource & {
184
187
  */
185
188
  export type Authentication = {
186
189
  tokens: SessionTokens;
187
- profile: SessionProfile | null;
190
+ profile: SessionProfile;
188
191
  };
189
192
  /**
190
193
  * Result of checkEmail() indicating whether the email is registered.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softwarepatterns/am",
3
- "version": "0.0.2",
3
+ "version": "0.1.0",
4
4
  "description": "Auth client SDK for AccountMaker (Am)",
5
5
  "keywords": [
6
6
  "authentication",
@@ -47,8 +47,7 @@
47
47
  "test:unit": "bun test src",
48
48
  "test:integration": "NODE_TLS_REJECT_UNAUTHORIZED=0 bun test test/integration",
49
49
  "typecheck": "bunx tsc --noEmit",
50
- "check": "npm run typecheck && npm run build",
51
- "digest": "bunx ai-digest -i . -o codebase.md --whitespace-removal --show-output-files"
50
+ "check": "npm run typecheck && npm run build"
52
51
  },
53
52
  "publishConfig": {
54
53
  "access": "public"