@ghostly-solutions/auth 0.2.1 → 0.2.2

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/dist/extension.js CHANGED
@@ -2,11 +2,19 @@
2
2
  var authApiPrefix = "/oauth";
3
3
  var authEndpoints = {
4
4
  authorize: `${authApiPrefix}/authorize`,
5
+ extensionToken: `${authApiPrefix}/extension/token`,
5
6
  session: `${authApiPrefix}/session`,
6
7
  refresh: `${authApiPrefix}/refresh`,
7
8
  logout: `${authApiPrefix}/logout`
8
9
  };
9
10
 
11
+ // src/constants/http-status.ts
12
+ var httpStatus = {
13
+ ok: 200,
14
+ noContent: 204,
15
+ unauthorized: 401
16
+ };
17
+
10
18
  // src/errors/auth-sdk-error.ts
11
19
  var AuthSdkError = class extends Error {
12
20
  code;
@@ -68,13 +76,6 @@ function resolveApiEndpoint(path, apiOrigin) {
68
76
  return `${normalizeApiOrigin(apiOrigin)}${path}`;
69
77
  }
70
78
 
71
- // src/constants/http-status.ts
72
- var httpStatus = {
73
- ok: 200,
74
- noContent: 204,
75
- unauthorized: 401
76
- };
77
-
78
79
  // src/constants/auth-keys.ts
79
80
  var authBroadcast = {
80
81
  channelName: "ghostly-auth-channel",
@@ -152,115 +153,6 @@ function createBroadcastSync(options) {
152
153
  };
153
154
  }
154
155
 
155
- // src/core/http-client.ts
156
- var jsonContentType = "application/json";
157
- var jsonHeaderName = "content-type";
158
- var includeCredentials = "include";
159
- var noStoreCache = "no-store";
160
- function toTypedValue(value) {
161
- return value;
162
- }
163
- function mapHttpStatusToAuthErrorCode(status) {
164
- if (status === httpStatus.unauthorized) {
165
- return authErrorCode.unauthorized;
166
- }
167
- return authErrorCode.apiError;
168
- }
169
- async function parseJsonPayload(response) {
170
- try {
171
- return await response.json();
172
- } catch {
173
- return null;
174
- }
175
- }
176
- async function parseErrorPayload(response) {
177
- const payload = await parseJsonPayload(response);
178
- if (!isObjectRecord(payload)) {
179
- return {
180
- code: null,
181
- details: null,
182
- message: null
183
- };
184
- }
185
- const maybeCode = payload.code;
186
- const maybeMessage = payload.message;
187
- return {
188
- code: isStringValue(maybeCode) ? maybeCode : null,
189
- details: "details" in payload ? payload.details : null,
190
- message: isStringValue(maybeMessage) ? maybeMessage : null
191
- };
192
- }
193
- function buildApiErrorMessage(method, path) {
194
- return `Auth API request failed: ${method} ${path}`;
195
- }
196
- function buildNetworkErrorMessage(method, path) {
197
- return `Auth API network failure: ${method} ${path}`;
198
- }
199
- async function request(options) {
200
- const expectedStatus = options.expectedStatus ?? httpStatus.ok;
201
- const headers = new Headers();
202
- const hasBody = typeof options.body !== "undefined";
203
- if (hasBody) {
204
- headers.set(jsonHeaderName, jsonContentType);
205
- }
206
- const requestInit = {
207
- cache: noStoreCache,
208
- credentials: includeCredentials,
209
- headers,
210
- method: options.method
211
- };
212
- if (hasBody) {
213
- requestInit.body = JSON.stringify(options.body);
214
- }
215
- let response;
216
- try {
217
- response = await fetch(options.path, requestInit);
218
- } catch (error) {
219
- throw new AuthSdkError({
220
- code: authErrorCode.networkError,
221
- details: error,
222
- message: buildNetworkErrorMessage(options.method, options.path),
223
- status: null
224
- });
225
- }
226
- if (response.status !== expectedStatus) {
227
- const parsed = await parseErrorPayload(response);
228
- throw new AuthSdkError({
229
- code: mapHttpStatusToAuthErrorCode(response.status),
230
- details: {
231
- apiCode: parsed.code,
232
- apiDetails: parsed.details
233
- },
234
- message: parsed.message ?? buildApiErrorMessage(options.method, options.path),
235
- status: response.status
236
- });
237
- }
238
- if (response.status === httpStatus.noContent) {
239
- return toTypedValue(null);
240
- }
241
- const payload = await parseJsonPayload(response);
242
- return toTypedValue(payload);
243
- }
244
- function getJson(path) {
245
- return request({
246
- method: "GET",
247
- path
248
- });
249
- }
250
- function postJsonWithoutBody(path) {
251
- return request({
252
- method: "POST",
253
- path
254
- });
255
- }
256
- function postEmpty(path) {
257
- return request({
258
- expectedStatus: httpStatus.noContent,
259
- method: "POST",
260
- path
261
- });
262
- }
263
-
264
156
  // src/core/runtime.ts
265
157
  var browserRuntimeErrorMessage = "Browser runtime is required for this auth operation.";
266
158
  function isBrowserRuntime() {
@@ -330,27 +222,11 @@ var SessionStore = class {
330
222
  }
331
223
  };
332
224
 
333
- // src/core/auth-client.ts
334
- function createInvalidSessionPayloadError(path) {
335
- return new AuthSdkError({
336
- code: authErrorCode.apiError,
337
- details: null,
338
- message: `Auth API response has invalid session shape: ${path}`,
339
- status: null
340
- });
341
- }
342
- function toValidatedSession(payload, path) {
343
- if (!isGhostlySession(payload)) {
344
- throw createInvalidSessionPayloadError(path);
345
- }
346
- return payload;
347
- }
348
- function toSessionPayload(payload, path) {
349
- if (payload === null) {
350
- return null;
351
- }
352
- return toValidatedSession(payload, path);
353
- }
225
+ // src/adapters/extension/auth-client.ts
226
+ var extensionSessionHeader = "X-Ghostly-Session-Id";
227
+ var includeCredentials = "include";
228
+ var noStoreCache = "no-store";
229
+ var tokenFreshnessLeewayMs = 6e4;
354
230
  function createNoopBroadcastSync() {
355
231
  return {
356
232
  close() {
@@ -371,25 +247,133 @@ function createSafeBroadcastSync(onSessionUpdated) {
371
247
  throw error;
372
248
  }
373
249
  }
250
+ function buildApiErrorMessage(method, path) {
251
+ return `Auth API request failed: ${method} ${path}`;
252
+ }
253
+ function buildNetworkErrorMessage(method, path) {
254
+ return `Auth API network failure: ${method} ${path}`;
255
+ }
256
+ function createInvalidSessionPayloadError(path) {
257
+ return new AuthSdkError({
258
+ code: authErrorCode.apiError,
259
+ details: null,
260
+ message: `Auth API response has invalid session shape: ${path}`,
261
+ status: null
262
+ });
263
+ }
374
264
  function toInitResult(session) {
375
265
  return {
376
266
  session,
377
267
  status: session ? "authenticated" : "unauthenticated"
378
268
  };
379
269
  }
380
- function createAuthClient(options = {}) {
381
- let initPromise = null;
382
- const defaultApplication = options.application?.trim() || "";
383
- const sessionStore = new SessionStore();
384
- const broadcastSync = createSafeBroadcastSync((session) => {
385
- sessionStore.setSession(session);
386
- });
270
+ function parseSessionPayload(payload, path) {
271
+ if (payload === null) {
272
+ return null;
273
+ }
274
+ if (!isGhostlySession(payload)) {
275
+ throw createInvalidSessionPayloadError(path);
276
+ }
277
+ return payload;
278
+ }
279
+ function isExtensionAccessToken(value) {
280
+ if (!isObjectRecord(value)) {
281
+ return false;
282
+ }
283
+ return isStringValue(value.accessToken) && isStringValue(value.application) && (value.expiresAt === null || isStringValue(value.expiresAt)) && (value.session === null || isGhostlySession(value.session)) && isStringValue(value.tokenType);
284
+ }
285
+ function isStoredTokenFresh(token) {
286
+ if (!token || !token.accessToken.trim()) {
287
+ return false;
288
+ }
289
+ if (!token.expiresAt) {
290
+ return true;
291
+ }
292
+ const expiresAt = Date.parse(token.expiresAt);
293
+ if (Number.isNaN(expiresAt)) {
294
+ return false;
295
+ }
296
+ return expiresAt - Date.now() > tokenFreshnessLeewayMs;
297
+ }
298
+ function buildAuthorizeUrl(apiOrigin, returnTo, application) {
299
+ const authorizeEndpoint = resolveApiEndpoint(authEndpoints.authorize, apiOrigin);
300
+ const authorizeUrl = new URL(authorizeEndpoint, window.location.origin);
301
+ authorizeUrl.searchParams.set("return_to", returnTo);
302
+ if (application?.trim()) {
303
+ authorizeUrl.searchParams.set("app", application.trim());
304
+ }
305
+ return authorizeUrl.toString();
306
+ }
307
+ function parseErrorPayload(payload) {
308
+ if (!isObjectRecord(payload)) {
309
+ return {
310
+ details: null,
311
+ message: null
312
+ };
313
+ }
314
+ return {
315
+ details: "details" in payload ? payload.details : null,
316
+ message: isStringValue(payload.message) ? payload.message : isStringValue(payload.error) ? payload.error : null
317
+ };
318
+ }
319
+ function createRequest(options) {
387
320
  const resolveEndpoint = (path) => resolveApiEndpoint(path, options.apiOrigin);
388
- const loadSession = async () => {
389
- const payload = await getJson(resolveEndpoint(authEndpoints.session));
390
- return toSessionPayload(payload, authEndpoints.session);
321
+ return async function request(requestOptions) {
322
+ const expectedStatus = requestOptions.expectedStatus ?? httpStatus.ok;
323
+ const headers = new Headers();
324
+ const sessionId = (await options.resolveSessionId?.())?.trim() || "";
325
+ if (sessionId) {
326
+ headers.set(extensionSessionHeader, sessionId);
327
+ }
328
+ let response;
329
+ try {
330
+ response = await fetch(resolveEndpoint(requestOptions.path), {
331
+ cache: noStoreCache,
332
+ credentials: includeCredentials,
333
+ headers,
334
+ method: requestOptions.method
335
+ });
336
+ } catch (error) {
337
+ throw new AuthSdkError({
338
+ code: authErrorCode.networkError,
339
+ details: error,
340
+ message: buildNetworkErrorMessage(requestOptions.method, requestOptions.path),
341
+ status: null
342
+ });
343
+ }
344
+ if (response.status !== expectedStatus) {
345
+ let parsedPayload = null;
346
+ try {
347
+ parsedPayload = await response.json();
348
+ } catch {
349
+ parsedPayload = null;
350
+ }
351
+ const parsed = parseErrorPayload(parsedPayload);
352
+ throw new AuthSdkError({
353
+ code: response.status === httpStatus.unauthorized ? authErrorCode.unauthorized : authErrorCode.apiError,
354
+ details: parsed.details,
355
+ message: parsed.message ?? buildApiErrorMessage(requestOptions.method, requestOptions.path),
356
+ status: response.status
357
+ });
358
+ }
359
+ if (response.status === httpStatus.noContent) {
360
+ return null;
361
+ }
362
+ return await response.json();
391
363
  };
392
- const init = async (initOptions) => {
364
+ }
365
+ function createLoadSession(request) {
366
+ return async () => {
367
+ const payload = await request({
368
+ method: "GET",
369
+ path: authEndpoints.session
370
+ });
371
+ return parseSessionPayload(payload, authEndpoints.session);
372
+ };
373
+ }
374
+ function createInit(sessionStore, loadSession, publishSession) {
375
+ let initPromise = null;
376
+ return async (initOptions) => {
393
377
  const forceRefresh = initOptions?.forceRefresh ?? false;
394
378
  if (sessionStore.hasResolvedSession() && !forceRefresh) {
395
379
  return toInitResult(sessionStore.getSessionIfResolved());
@@ -400,7 +384,7 @@ function createAuthClient(options = {}) {
400
384
  initPromise = (async () => {
401
385
  const session = await loadSession();
402
386
  sessionStore.setSession(session);
403
- broadcastSync.publishSession(session);
387
+ publishSession(session);
404
388
  return toInitResult(session);
405
389
  })();
406
390
  try {
@@ -409,19 +393,91 @@ function createAuthClient(options = {}) {
409
393
  initPromise = null;
410
394
  }
411
395
  };
396
+ }
397
+ function createRefresh(request, sessionStore, publishSession) {
398
+ return async () => {
399
+ const payload = await request({
400
+ method: "POST",
401
+ path: authEndpoints.refresh
402
+ });
403
+ const session = parseSessionPayload(payload, authEndpoints.refresh);
404
+ sessionStore.setSession(session);
405
+ publishSession(session);
406
+ return session;
407
+ };
408
+ }
409
+ function createGetAccessToken(request, sessionStore, publishSession, persistAccessToken, restoreAccessToken) {
410
+ return async (requestOptions) => {
411
+ const forceRefresh = requestOptions?.forceRefresh ?? false;
412
+ const stored = await restoreAccessToken?.() ?? null;
413
+ if (!forceRefresh && isStoredTokenFresh(stored)) {
414
+ if (stored.session) {
415
+ sessionStore.setSession(stored.session);
416
+ }
417
+ return stored;
418
+ }
419
+ const payload = await request({
420
+ method: "GET",
421
+ path: authEndpoints.extensionToken
422
+ });
423
+ if (!isExtensionAccessToken(payload)) {
424
+ throw new AuthSdkError({
425
+ code: authErrorCode.apiError,
426
+ details: null,
427
+ message: `Auth API response has invalid extension token shape: ${authEndpoints.extensionToken}`,
428
+ status: null
429
+ });
430
+ }
431
+ const nextToken = {
432
+ accessToken: payload.accessToken,
433
+ application: payload.application,
434
+ expiresAt: payload.expiresAt,
435
+ session: payload.session,
436
+ tokenType: payload.tokenType
437
+ };
438
+ sessionStore.setSession(nextToken.session);
439
+ publishSession(nextToken.session);
440
+ await persistAccessToken?.(nextToken);
441
+ return nextToken;
442
+ };
443
+ }
444
+ function createLogout(request, sessionStore, publishSession, options) {
445
+ return async () => {
446
+ await request({
447
+ expectedStatus: httpStatus.noContent,
448
+ method: "POST",
449
+ path: authEndpoints.logout
450
+ });
451
+ await options.clearSessionId?.();
452
+ sessionStore.setSession(null);
453
+ publishSession(null);
454
+ await options.persistAccessToken?.(null);
455
+ };
456
+ }
457
+ function createExtensionAuthClient(options) {
458
+ const sessionStore = new SessionStore();
459
+ const broadcastSync = createSafeBroadcastSync((session) => {
460
+ sessionStore.setSession(session);
461
+ });
462
+ const publishSession = broadcastSync.publishSession.bind(broadcastSync);
463
+ const request = createRequest(options);
464
+ const loadSession = createLoadSession(request);
465
+ const init = createInit(sessionStore, loadSession, publishSession);
466
+ const refresh = createRefresh(request, sessionStore, publishSession);
467
+ const getAccessToken = createGetAccessToken(
468
+ request,
469
+ sessionStore,
470
+ publishSession,
471
+ options.persistAccessToken,
472
+ options.restoreAccessToken
473
+ );
474
+ const logout = createLogout(request, sessionStore, publishSession, options);
412
475
  const getSession = async (requestOptions) => {
413
476
  const result = await init({
414
477
  forceRefresh: requestOptions?.forceRefresh ?? false
415
478
  });
416
479
  return result.session;
417
480
  };
418
- const refresh = async () => {
419
- const payload = await postJsonWithoutBody(resolveEndpoint(authEndpoints.refresh));
420
- const session = toSessionPayload(payload, authEndpoints.refresh);
421
- sessionStore.setSession(session);
422
- broadcastSync.publishSession(session);
423
- return session;
424
- };
425
481
  const requireSession = async () => {
426
482
  const session = await getSession();
427
483
  if (session) {
@@ -434,49 +490,24 @@ function createAuthClient(options = {}) {
434
490
  status: httpStatus.unauthorized
435
491
  });
436
492
  };
437
- const login = (loginOptions) => {
438
- const returnTo = resolveReturnToPath(loginOptions?.returnTo);
439
- const authorizeUrl = new URL(resolveEndpoint(authEndpoints.authorize), window.location.origin);
440
- authorizeUrl.searchParams.set("return_to", returnTo);
441
- const application = loginOptions?.application?.trim() || defaultApplication;
442
- if (application) {
443
- authorizeUrl.searchParams.set("app", application);
493
+ const loginWithTabFlow = async (loginOptions) => {
494
+ if (!options.openAuthorizePage) {
495
+ throw new Error("Extension auth client requires openAuthorizePage for tab login flow.");
444
496
  }
445
- window.location.assign(authorizeUrl.toString());
446
- };
447
- const logout = async () => {
448
- await postEmpty(resolveEndpoint(authEndpoints.logout));
449
- sessionStore.setSession(null);
450
- broadcastSync.publishSession(null);
451
- };
452
- const subscribe = sessionStore.subscribe.bind(sessionStore);
453
- return {
454
- init,
455
- getSession,
456
- login,
457
- logout,
458
- refresh,
459
- requireSession,
460
- subscribe
497
+ const returnTo = resolveReturnToPath(loginOptions?.returnTo);
498
+ const authorizeUrl = buildAuthorizeUrl(
499
+ options.apiOrigin,
500
+ returnTo,
501
+ loginOptions?.application ?? options.application
502
+ );
503
+ await options.openAuthorizePage({
504
+ authorizeUrl
505
+ });
461
506
  };
462
- }
463
-
464
- // src/adapters/extension/auth-client.ts
465
- function buildAuthorizeUrl(apiOrigin, returnTo, application) {
466
- const authorizeEndpoint = resolveApiEndpoint(authEndpoints.authorize, apiOrigin);
467
- const authorizeUrl = new URL(authorizeEndpoint, window.location.origin);
468
- authorizeUrl.searchParams.set("return_to", returnTo);
469
- if (application?.trim()) {
470
- authorizeUrl.searchParams.set("app", application.trim());
471
- }
472
- return authorizeUrl.toString();
473
- }
474
- function createExtensionAuthClient(options) {
475
- const baseClient = createAuthClient({
476
- apiOrigin: options.apiOrigin,
477
- application: options.application
478
- });
479
507
  const loginWithWebAuthFlow = async (loginOptions) => {
508
+ if (!options.launchWebAuthFlow) {
509
+ throw new Error("Extension auth client requires launchWebAuthFlow for web auth flow.");
510
+ }
480
511
  const returnTo = resolveReturnToPath(loginOptions?.returnTo);
481
512
  const authorizeUrl = buildAuthorizeUrl(
482
513
  options.apiOrigin,
@@ -486,17 +517,118 @@ function createExtensionAuthClient(options) {
486
517
  await options.launchWebAuthFlow({
487
518
  authorizeUrl
488
519
  });
489
- await baseClient.refresh();
520
+ await refresh();
490
521
  };
491
522
  return {
492
- ...baseClient,
523
+ init,
524
+ getSession,
493
525
  login(loginOptions) {
526
+ if (options.openAuthorizePage) {
527
+ void loginWithTabFlow(loginOptions);
528
+ return;
529
+ }
494
530
  void loginWithWebAuthFlow(loginOptions);
495
531
  },
532
+ logout,
533
+ refresh,
534
+ requireSession,
535
+ subscribe(listener) {
536
+ return sessionStore.subscribe(listener);
537
+ },
538
+ getAccessToken,
539
+ loginWithTabFlow,
496
540
  loginWithWebAuthFlow
497
541
  };
498
542
  }
499
543
 
500
- export { createExtensionAuthClient };
544
+ // src/adapters/extension/chrome-auth-client.ts
545
+ var defaultSessionCookieName = "gs_auth_session";
546
+ var defaultAccessTokenStorageKey = "authToken";
547
+ var defaultTokenExpiresAtStorageKey = "authTokenExpiresAt";
548
+ var defaultSessionStorageKey = "authSession";
549
+ function getChromeRuntime() {
550
+ return globalThis.chrome ?? {};
551
+ }
552
+ function createChromeExtensionAuthClient(options) {
553
+ const sessionCookieName = options.sessionCookieName?.trim() || defaultSessionCookieName;
554
+ const accessTokenStorageKey = options.accessTokenStorageKey?.trim() || defaultAccessTokenStorageKey;
555
+ const tokenExpiresAtStorageKey = options.tokenExpiresAtStorageKey?.trim() || defaultTokenExpiresAtStorageKey;
556
+ const sessionStorageKey = options.sessionStorageKey?.trim() || defaultSessionStorageKey;
557
+ const resolveSessionId = async () => {
558
+ const cookies = getChromeRuntime().cookies;
559
+ if (!cookies) {
560
+ return null;
561
+ }
562
+ const cookie = await cookies.get({
563
+ name: sessionCookieName,
564
+ url: `${options.apiOrigin}/`
565
+ });
566
+ return cookie?.value?.trim() || null;
567
+ };
568
+ const clearSessionId = async () => {
569
+ const cookies = getChromeRuntime().cookies;
570
+ if (!cookies) {
571
+ return;
572
+ }
573
+ await cookies.remove({
574
+ name: sessionCookieName,
575
+ url: `${options.apiOrigin}/`
576
+ });
577
+ };
578
+ const persistAccessToken = async (token) => {
579
+ const storage = getChromeRuntime().storage?.local;
580
+ if (!storage) {
581
+ return;
582
+ }
583
+ if (!token) {
584
+ await storage.remove([accessTokenStorageKey, tokenExpiresAtStorageKey, sessionStorageKey]);
585
+ return;
586
+ }
587
+ await storage.set({
588
+ [accessTokenStorageKey]: token.accessToken,
589
+ [tokenExpiresAtStorageKey]: token.expiresAt || null,
590
+ [sessionStorageKey]: token.session || null
591
+ });
592
+ };
593
+ const restoreAccessToken = async () => {
594
+ const storage = getChromeRuntime().storage?.local;
595
+ if (!storage) {
596
+ return null;
597
+ }
598
+ const stored = await storage.get([
599
+ accessTokenStorageKey,
600
+ tokenExpiresAtStorageKey,
601
+ sessionStorageKey
602
+ ]);
603
+ const rawAccessToken = stored[accessTokenStorageKey];
604
+ if (typeof rawAccessToken !== "string" || rawAccessToken.trim() === "") {
605
+ return null;
606
+ }
607
+ return {
608
+ accessToken: rawAccessToken,
609
+ application: options.application?.trim() || "",
610
+ expiresAt: typeof stored[tokenExpiresAtStorageKey] === "string" ? stored[tokenExpiresAtStorageKey] : null,
611
+ session: stored[sessionStorageKey] ?? null,
612
+ tokenType: "Bearer"
613
+ };
614
+ };
615
+ const openAuthorizePage = async ({ authorizeUrl }) => {
616
+ const tabs = getChromeRuntime().tabs;
617
+ if (!tabs) {
618
+ throw new Error("Chrome tabs API is unavailable.");
619
+ }
620
+ await tabs.create({ active: true, url: authorizeUrl });
621
+ };
622
+ return createExtensionAuthClient({
623
+ ...options,
624
+ clearSessionId,
625
+ openAuthorizePage,
626
+ persistAccessToken,
627
+ resolveSessionId,
628
+ restoreAccessToken
629
+ });
630
+ }
631
+
632
+ export { createChromeExtensionAuthClient, createExtensionAuthClient };
501
633
  //# sourceMappingURL=extension.js.map
502
634
  //# sourceMappingURL=extension.js.map