lazypock 0.20.0 → 0.20.1

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/package.json CHANGED
@@ -1,7 +1,22 @@
1
1
  {
2
2
  "name": "lazypock",
3
- "version": "0.20.0",
3
+ "version": "0.20.1",
4
4
  "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/gnuzd/lazypock-ts.git"
8
+ },
9
+ "homepage": "https://github.com/gnuzd/lazypock-ts#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/gnuzd/lazypock-ts/issues"
12
+ },
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "sideEffects": [
17
+ "./dist/cli.js",
18
+ "./dist/cli.cjs"
19
+ ],
5
20
  "type": "module",
6
21
  "main": "./dist/index.cjs",
7
22
  "module": "./dist/index.js",
@@ -27,7 +42,9 @@
27
42
  "smoke": "npm run build && node smoke-test.mjs && node realtime-test.mjs && node auth-store-test.mjs && node oauth2-relay-test.mjs && tsc --noEmit --strict --target es2020 --module esnext --moduleResolution bundler type-test.ts",
28
43
  "bench": "npm run build && node bench/codegen.mjs && node bench/http-overhead.mjs",
29
44
  "test:integration": "npm run build && node integration-test.mjs",
30
- "prepublishOnly": "npm run build"
45
+ "prepublishOnly": "npm run build",
46
+ "test": "bun test",
47
+ "test:watch": "bun test --watch"
31
48
  },
32
49
  "bin": {
33
50
  "lazypock": "./dist/cli.js",
package/src/auth.ts CHANGED
@@ -173,6 +173,35 @@ export class AuthStore {
173
173
  this.notify();
174
174
  }
175
175
 
176
+ /**
177
+ * Replace the cached auth model **without** touching the token, its recorded
178
+ * expiry, or the refresh token.
179
+ *
180
+ * Use this when a read refreshes the identity record (e.g. `me()`, or the
181
+ * server echoing the record back). Routing that through {@link set} would
182
+ * overwrite the access token's real `expiresIn` with the 7-day fallback TTL,
183
+ * so `isExpired` stays false long past the real 15-minute lifetime and the
184
+ * proactive refresh never fires — every request then pays a 401 + retry.
185
+ *
186
+ * @param model The authenticated user record, or null for superusers.
187
+ */
188
+ setModel(model: AuthModel | null): void {
189
+ this._model = model;
190
+
191
+ // Mirrors `set`: derive the auth collection when the caller has not set it.
192
+ if (!this._collectionName && model && typeof model.collectionName === "string") {
193
+ this._collectionName = model.collectionName;
194
+ }
195
+
196
+ void Promise.all([
197
+ model
198
+ ? this.storage.set("auth_model", JSON.stringify(model))
199
+ : this.storage.remove("auth_model"),
200
+ this.persistCollectionName(),
201
+ ]);
202
+ this.notify();
203
+ }
204
+
176
205
  /**
177
206
  * Record a complete auth response: token, model, refresh token and the access
178
207
  * token's real lifetime.
@@ -0,0 +1,289 @@
1
+ // ── Collection auth routes ──────────────────────────────
2
+ // Password, refresh, OAuth2 and the email/verification flows for a single auth
3
+ // collection. Kept out of the CRUD service: these only need a transport, the
4
+ // collection name and the session store.
5
+
6
+ import { ApiError } from "../types";
7
+ import type { ApiRecord, RequestOptions } from "../types";
8
+ import { collectionPath } from "./paths";
9
+ import {
10
+ postWithSession,
11
+ rememberSessionRecord,
12
+ type AuthResponse,
13
+ type SessionContext,
14
+ } from "./session";
15
+ import {
16
+ authorizeWithOAuth2Popup,
17
+ oauth2RedirectOrigin,
18
+ DEFAULT_OAUTH2_TIMEOUT_MS,
19
+ type AuthMethodsList,
20
+ type OAuth2Options,
21
+ type OAuth2AuthCodeOptions,
22
+ type RecordAuth,
23
+ } from "../oauth2";
24
+
25
+ /**
26
+ * Authenticate with email/password against this auth collection.
27
+ * Stores the returned token and user model in the auth store.
28
+ */
29
+ export function authWithPassword(
30
+ ctx: SessionContext,
31
+ identity: string,
32
+ password: string,
33
+ options?: RequestOptions,
34
+ ): Promise<AuthResponse | null> {
35
+ return postWithSession<AuthResponse>(
36
+ ctx,
37
+ collectionPath(ctx.collectionName) + "/auth-with-password",
38
+ { identity, password },
39
+ options,
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Refresh the auth token for the currently authenticated user.
45
+ * Updates the stored token and user model.
46
+ */
47
+ export function authRefresh(
48
+ ctx: SessionContext,
49
+ options?: RequestOptions,
50
+ ): Promise<AuthResponse | null> {
51
+ return postWithSession<AuthResponse>(
52
+ ctx,
53
+ collectionPath(ctx.collectionName) + "/auth-refresh",
54
+ { refreshToken: ctx.authStore?.refreshToken },
55
+ options,
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Get available auth methods for this collection (PocketBase `listAuthMethods`).
61
+ * Returns `password`, `oauth2.providers` (each with `name`, `authURL`,
62
+ * `state`, `codeVerifier`), and `mfa`.
63
+ */
64
+ export function listAuthMethods(
65
+ ctx: SessionContext,
66
+ options?: RequestOptions,
67
+ ): Promise<AuthMethodsList | null> {
68
+ return ctx.http.get<AuthMethodsList>(
69
+ collectionPath(ctx.collectionName) + "/auth-methods",
70
+ options,
71
+ );
72
+ }
73
+
74
+ // ── Email / Verification / Password Reset (PocketBase parity) ──
75
+
76
+ /**
77
+ * Send a password reset email to the given address (PocketBase
78
+ * `requestPasswordReset`). The backend always answers 204 to avoid
79
+ * revealing whether the address exists.
80
+ */
81
+ export async function requestPasswordReset(
82
+ ctx: SessionContext,
83
+ email: string,
84
+ options?: RequestOptions,
85
+ ): Promise<boolean> {
86
+ await ctx.http.post(
87
+ collectionPath(ctx.collectionName) + "/request-password-reset",
88
+ { email },
89
+ options,
90
+ );
91
+ return true;
92
+ }
93
+
94
+ /**
95
+ * Confirm a password reset (PocketBase `confirmPasswordReset`).
96
+ *
97
+ * @param passwordResetToken The token emailed by `requestPasswordReset`.
98
+ * @param password The new password (min 8 chars server-side).
99
+ * @param passwordConfirm Must equal `password`.
100
+ */
101
+ export async function confirmPasswordReset(
102
+ ctx: SessionContext,
103
+ passwordResetToken: string,
104
+ password: string,
105
+ passwordConfirm: string,
106
+ options?: RequestOptions,
107
+ ): Promise<boolean> {
108
+ await ctx.http.post(
109
+ collectionPath(ctx.collectionName) + "/confirm-password-reset",
110
+ { token: passwordResetToken, password, passwordConfirm },
111
+ options,
112
+ );
113
+ return true;
114
+ }
115
+
116
+ /**
117
+ * Send a verification email to the given address (PocketBase
118
+ * `requestVerification`). The backend always answers 204 to avoid
119
+ * revealing whether the address exists.
120
+ */
121
+ export async function requestVerification(
122
+ ctx: SessionContext,
123
+ email: string,
124
+ options?: RequestOptions,
125
+ ): Promise<boolean> {
126
+ await ctx.http.post(
127
+ collectionPath(ctx.collectionName) + "/request-verification",
128
+ { email },
129
+ options,
130
+ );
131
+ return true;
132
+ }
133
+
134
+ /**
135
+ * Confirm an email verification (PocketBase `confirmVerification`).
136
+ * Resolves with the verified auth record.
137
+ */
138
+ export async function confirmVerification<T>(
139
+ ctx: SessionContext,
140
+ verificationToken: string,
141
+ options?: RequestOptions,
142
+ ): Promise<T | null> {
143
+ const data = await ctx.http.post<{ record: ApiRecord }>(
144
+ collectionPath(ctx.collectionName) + "/confirm-verification",
145
+ { token: verificationToken },
146
+ options,
147
+ );
148
+ return (data?.record as T | undefined) ?? null;
149
+ }
150
+
151
+ /**
152
+ * Send an email-change confirmation email to a new address (PocketBase
153
+ * `requestEmailChange`). Requires an authenticated auth-collection user.
154
+ */
155
+ export async function requestEmailChange(
156
+ ctx: SessionContext,
157
+ newEmail: string,
158
+ options?: RequestOptions,
159
+ ): Promise<boolean> {
160
+ await ctx.http.post(
161
+ collectionPath(ctx.collectionName) + "/request-email-change",
162
+ { newEmail },
163
+ options,
164
+ );
165
+ return true;
166
+ }
167
+
168
+ /**
169
+ * Confirm an email change (PocketBase `confirmEmailChange`). Requires the
170
+ * currently authenticated user's password. Resolves with the updated auth
171
+ * record.
172
+ */
173
+ export async function confirmEmailChange<T>(
174
+ ctx: SessionContext,
175
+ emailChangeToken: string,
176
+ password: string,
177
+ options?: RequestOptions,
178
+ ): Promise<T | null> {
179
+ const data = await ctx.http.post<{ record: ApiRecord }>(
180
+ collectionPath(ctx.collectionName) + "/confirm-email-change",
181
+ { token: emailChangeToken, password },
182
+ options,
183
+ );
184
+ return (data?.record as T | undefined) ?? null;
185
+ }
186
+
187
+ // ── OAuth2 ──
188
+
189
+ /**
190
+ * Sign in with an OAuth2 provider (PocketBase `authWithOAuth2` parity).
191
+ *
192
+ * One call handles the whole web flow: fetch the provider's `authURL`, open a
193
+ * popup (or call `options.urlCallback`), receive the single-use authorization
194
+ * `code` the backend relays via `postMessage`, exchange it, populate the auth
195
+ * store, and resolve with `{ token, record, meta }`.
196
+ *
197
+ * `options.createData` is forwarded on first sign-up (the exchange goes
198
+ * through {@link authWithOAuth2Code}), matching PocketBase.
199
+ *
200
+ * React Native / non-browser: the popup flow depends on
201
+ * `window.postMessage`. Use {@link listAuthMethods} + {@link authWithOAuth2Code}
202
+ * instead.
203
+ */
204
+ export async function authWithOAuth2<T>(
205
+ ctx: SessionContext,
206
+ options: OAuth2Options,
207
+ ): Promise<RecordAuth<T>> {
208
+ const {
209
+ provider,
210
+ createData,
211
+ urlCallback,
212
+ popup,
213
+ timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS,
214
+ } = options;
215
+
216
+ const methods = await listAuthMethods(ctx);
217
+ const providerInfo = methods?.oauth2?.providers?.find(
218
+ (p) => p.name === provider,
219
+ );
220
+ if (!providerInfo) {
221
+ throw new ApiError(
222
+ `OAuth2 provider "${provider}" is not enabled for this collection.`,
223
+ methods ?? {},
224
+ 400,
225
+ false,
226
+ "oauth2_unknown_provider",
227
+ );
228
+ }
229
+
230
+ // The redirect page relays only the authorization code (never a token).
231
+ // Exchange it through the shared code path so `createData` is forwarded
232
+ // and the auth store is populated in one place.
233
+ const { code } = await authorizeWithOAuth2Popup({
234
+ authURL: providerInfo.authURL,
235
+ expectedOrigin: oauth2RedirectOrigin(ctx.http.baseUrl),
236
+ urlCallback,
237
+ popup,
238
+ timeoutMs,
239
+ });
240
+
241
+ return authWithOAuth2Code<T>(ctx, {
242
+ provider,
243
+ code,
244
+ codeVerifier: providerInfo.codeVerifier,
245
+ createData,
246
+ });
247
+ }
248
+
249
+ /**
250
+ * Exchange an OAuth2 authorization code directly (PocketBase
251
+ * `authWithOAuth2Code` parity).
252
+ *
253
+ * Used by mobile / non-browser flows: fetch {@link listAuthMethods} to get
254
+ * the provider `authURL` + `codeVerifier`, present the URL yourself,
255
+ * capture the `code` from your redirect/deep link, then call this to
256
+ * finish and populate the auth store.
257
+ */
258
+ export async function authWithOAuth2Code<T>(
259
+ ctx: SessionContext,
260
+ options: OAuth2AuthCodeOptions,
261
+ ): Promise<RecordAuth<T>> {
262
+ const { provider, code, codeVerifier, redirectUrl, createData } = options;
263
+
264
+ const data = await ctx.http.post<RecordAuth<ApiRecord>>(
265
+ collectionPath(ctx.collectionName) + "/auth-with-oauth2",
266
+ {
267
+ provider,
268
+ code,
269
+ codeVerifier,
270
+ redirectUrl: redirectUrl ?? ctx.http.baseUrl + "/oauth2-redirect",
271
+ createData: createData ?? {},
272
+ },
273
+ );
274
+
275
+ if (!data) {
276
+ throw new ApiError(
277
+ "OAuth2 code exchange returned no data.",
278
+ {},
279
+ 0,
280
+ false,
281
+ "oauth2_exchange_failed",
282
+ );
283
+ }
284
+
285
+ rememberSessionRecord(ctx, data as unknown as Record<string, unknown>);
286
+ // SAFETY: `data.record` is the server's auth record for this collection;
287
+ // it satisfies `T` at runtime — `T` is a compile-time lens only.
288
+ return data as unknown as RecordAuth<T>;
289
+ }