@absolutejs/auth 0.57.7 → 0.57.9

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.
@@ -381,23 +381,28 @@ var portableJsonb = customType({
381
381
  fromDriver: (value) => typeof value === "string" ? JSON.parse(value) : value,
382
382
  toDriver: (value) => JSON.stringify(value)
383
383
  });
384
- var agentDelegationsTable = pgTable3("auth_agent_delegations", {
384
+ var bunSqlJsonb = customType({
385
+ dataType: () => "jsonb",
386
+ fromDriver: (value) => typeof value === "string" ? JSON.parse(value) : value,
387
+ toDriver: (value) => value
388
+ });
389
+ var createAgentDelegationsTable = (json) => pgTable3("auth_agent_delegations", {
385
390
  agent_id: varchar3("agent_id", { length: ID_LENGTH3 }).notNull(),
386
- authorization_details: portableJsonb("authorization_details").$type(),
391
+ authorization_details: json("authorization_details").$type(),
387
392
  created_at_ms: bigint3("created_at_ms", { mode: "number" }).notNull(),
388
393
  delegation_id: varchar3("delegation_id", {
389
394
  length: ID_LENGTH3
390
395
  }).primaryKey(),
391
396
  expires_at_ms: bigint3("expires_at_ms", { mode: "number" }),
392
397
  organization_id: varchar3("organization_id", { length: ID_LENGTH3 }),
393
- scopes: portableJsonb("scopes").$type().notNull().default([]),
398
+ scopes: json("scopes").$type().notNull().default([]),
394
399
  status: varchar3("status", { length: STATUS_LENGTH }).$type().notNull(),
395
400
  updated_at_ms: bigint3("updated_at_ms", { mode: "number" }).notNull(),
396
401
  user_id: varchar3("user_id", { length: ID_LENGTH3 }).notNull()
397
402
  });
398
- var agentIdentityRegistrationsTable = pgTable3("auth_agent_identity_registrations", {
403
+ var createAgentIdentityRegistrationsTable = (json) => pgTable3("auth_agent_identity_registrations", {
399
404
  agent_id: varchar3("agent_id", { length: ID_LENGTH3 }).notNull().unique(),
400
- claim_attempt: portableJsonb("claim_attempt").$type(),
405
+ claim_attempt: json("claim_attempt").$type(),
401
406
  claim_attempt_token_hash: varchar3("claim_attempt_token_hash", {
402
407
  length: ID_LENGTH3
403
408
  }).unique(),
@@ -407,8 +412,12 @@ var agentIdentityRegistrationsTable = pgTable3("auth_agent_identity_registration
407
412
  claim_token_hash: varchar3("claim_token_hash", {
408
413
  length: ID_LENGTH3
409
414
  }).notNull().unique(),
410
- created_at_ms: bigint3("created_at_ms", { mode: "number" }).notNull(),
411
- expires_at_ms: bigint3("expires_at_ms", { mode: "number" }).notNull(),
415
+ created_at_ms: bigint3("created_at_ms", {
416
+ mode: "number"
417
+ }).notNull(),
418
+ expires_at_ms: bigint3("expires_at_ms", {
419
+ mode: "number"
420
+ }).notNull(),
412
421
  kind: varchar3("kind", { length: 32 }).$type().notNull(),
413
422
  last_polled_at_ms: bigint3("last_polled_at_ms", { mode: "number" }),
414
423
  login_hint: varchar3("login_hint", { length: ID_LENGTH3 }),
@@ -416,27 +425,37 @@ var agentIdentityRegistrationsTable = pgTable3("auth_agent_identity_registration
416
425
  length: ID_LENGTH3
417
426
  }).primaryKey(),
418
427
  status: varchar3("status", { length: STATUS_LENGTH }).$type().notNull(),
419
- updated_at_ms: bigint3("updated_at_ms", { mode: "number" }).notNull(),
428
+ updated_at_ms: bigint3("updated_at_ms", {
429
+ mode: "number"
430
+ }).notNull(),
420
431
  upstream_client_id: varchar3("upstream_client_id", {
421
432
  length: ID_LENGTH3
422
433
  }),
423
434
  upstream_issuer: varchar3("upstream_issuer", { length: ID_LENGTH3 }),
424
- upstream_subject: varchar3("upstream_subject", { length: ID_LENGTH3 }),
435
+ upstream_subject: varchar3("upstream_subject", {
436
+ length: ID_LENGTH3
437
+ }),
425
438
  user_id: varchar3("user_id", { length: ID_LENGTH3 }),
426
439
  version: integer("version").notNull()
427
440
  }, (table) => [
428
441
  uniqueIndex("auth_agent_identity_upstream_unique").on(table.upstream_issuer, table.upstream_subject, table.upstream_client_id)
429
442
  ]);
430
- var agentRegistrationsTable = pgTable3("auth_agent_registrations", {
443
+ var createAgentRegistrationsTable = (json) => pgTable3("auth_agent_registrations", {
431
444
  agent_id: varchar3("agent_id", { length: ID_LENGTH3 }).primaryKey(),
432
- allowed_scopes: portableJsonb("allowed_scopes").$type().notNull().default([]),
445
+ allowed_scopes: json("allowed_scopes").$type().notNull().default([]),
433
446
  client_id: varchar3("client_id", { length: ID_LENGTH3 }).unique(),
434
447
  created_at_ms: bigint3("created_at_ms", { mode: "number" }).notNull(),
435
- metadata: portableJsonb("metadata").$type(),
448
+ metadata: json("metadata").$type(),
436
449
  name: varchar3("name", { length: NAME_LENGTH }).notNull(),
437
450
  status: varchar3("status", { length: STATUS_LENGTH }).$type().notNull(),
438
451
  updated_at_ms: bigint3("updated_at_ms", { mode: "number" }).notNull()
439
452
  });
453
+ var agentDelegationsBunSqlTable = createAgentDelegationsTable(bunSqlJsonb);
454
+ var agentDelegationsTable = createAgentDelegationsTable(portableJsonb);
455
+ var agentIdentityRegistrationsBunSqlTable = createAgentIdentityRegistrationsTable(bunSqlJsonb);
456
+ var agentIdentityRegistrationsTable = createAgentIdentityRegistrationsTable(portableJsonb);
457
+ var agentRegistrationsBunSqlTable = createAgentRegistrationsTable(bunSqlJsonb);
458
+ var agentRegistrationsTable = createAgentRegistrationsTable(portableJsonb);
440
459
 
441
460
  // src/audit/postgresAuditStore.ts
442
461
  import { desc as desc4, eq as eq4, lt as lt2 } from "drizzle-orm";
@@ -685,17 +704,23 @@ var providers = defineProviders({
685
704
  },
686
705
  apple: {
687
706
  authorizationUrl: "https://appleid.apple.com/auth/authorize",
707
+ createAuthorizationURLSearchParams: {
708
+ response_mode: "form_post"
709
+ },
710
+ createClientSecret: (config) => createAppleClientSecret(config),
688
711
  isOIDC: true,
689
712
  isRefreshable: true,
690
- PKCEMethod: "S256",
691
- profileRequest: {
692
- authIn: "header",
693
- encoding: "application/json",
694
- method: "GET",
695
- url: "https://appleid.apple.com/auth/userinfo"
713
+ revocationRequest: {
714
+ authIn: "body",
715
+ encoding: "application/x-www-form-urlencoded",
716
+ tokenParamName: "token",
717
+ url: "https://appleid.apple.com/auth/revoke"
696
718
  },
697
719
  scopeRequired: false,
698
- subject: ["id"],
720
+ subject: ["sub"],
721
+ subjectBySource: {
722
+ idToken: ["sub"]
723
+ },
699
724
  subjectType: "string",
700
725
  tokenRequest: {
701
726
  authIn: "body",
@@ -764,6 +789,7 @@ var providers = defineProviders({
764
789
  token_type_hint: "refresh_token"
765
790
  }),
766
791
  encoding: "application/json",
792
+ inputSource: "refreshToken",
767
793
  tokenParamName: "token",
768
794
  url: (config) => `https://${config.domain}/oauth/revoke`
769
795
  },
@@ -1895,6 +1921,7 @@ var providers = defineProviders({
1895
1921
  token_type_hint: "refresh_token"
1896
1922
  }),
1897
1923
  encoding: "application/json",
1924
+ inputSource: "refreshToken",
1898
1925
  url: "https://www.reddit.com/api/v1/revoke_token"
1899
1926
  },
1900
1927
  scopeRequired: true,
@@ -2268,49 +2295,27 @@ var providers = defineProviders({
2268
2295
  authorizationUrl: "https://account.withings.com/oauth2_user/authorize2",
2269
2296
  isOIDC: false,
2270
2297
  isRefreshable: true,
2271
- profileRequest: {
2272
- authIn: "header",
2273
- body: async (config) => {
2274
- const props = await getWithingsProps(config);
2275
- if (props === undefined)
2276
- throw new Error("Failed to get Withings search properties");
2277
- const { nonce, hashedSignature } = props;
2278
- return [
2279
- ["action", "getuser"],
2280
- ["nonce", nonce],
2281
- ["client_id", config.clientId],
2282
- ["signature", hashedSignature]
2283
- ];
2284
- },
2285
- encoding: "application/x-www-form-urlencoded",
2286
- method: "POST",
2287
- url: "https://wbsapi.withings.net/v2/oauth2"
2288
- },
2289
2298
  refreshAccessTokenBody: {
2290
2299
  action: "requesttoken"
2291
2300
  },
2292
2301
  revocationRequest: {
2293
- authIn: "header",
2294
- body: async (config) => {
2295
- const props = await getWithingsProps(config);
2296
- if (!props)
2297
- throw new Error("Failed to get Withings props");
2298
- const { nonce, hashedSignature } = props;
2299
- return [
2300
- ["action", "revoke"],
2301
- ["client_id", config.clientId],
2302
- ["nonce", nonce],
2303
- ["signature", hashedSignature]
2304
- ];
2305
- },
2302
+ authIn: "body",
2303
+ body: (config) => getWithingsSignatureParams(config, "revoke"),
2306
2304
  encoding: "application/x-www-form-urlencoded",
2307
- method: "POST",
2308
- url: "https://wbsapi.withings.net/v2/oauth2"
2305
+ includeClientCredentials: false,
2306
+ inputSource: "subject",
2307
+ inputType: "number",
2308
+ tokenParamName: "userid",
2309
+ url: "https://wbsapi.withings.net/v2/oauth2",
2310
+ validateResponse: (value) => assertWithingsSuccess(value)
2309
2311
  },
2310
2312
  scopeDelimiter: ",",
2311
2313
  scopeRequired: true,
2312
2314
  subject: ["userid"],
2313
- subjectType: "string",
2315
+ subjectBySource: {
2316
+ tokenResponse: ["body", "userid"]
2317
+ },
2318
+ subjectType: "number",
2314
2319
  tokenRequest: {
2315
2320
  authIn: "body",
2316
2321
  encoding: "application/x-www-form-urlencoded",
@@ -2469,6 +2474,7 @@ var providers = defineProviders({
2469
2474
  }
2470
2475
  }
2471
2476
  });
2477
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
2472
2478
  var isOIDCProviderOption = (option) => {
2473
2479
  if (!isValidProviderOption(option))
2474
2480
  return false;
@@ -2481,6 +2487,12 @@ var isPKCEProviderOption = (option) => {
2481
2487
  const provider = providers[option];
2482
2488
  return provider.PKCEMethod !== undefined;
2483
2489
  };
2490
+ var isProfileProviderOption = (option) => {
2491
+ if (!isValidProviderOption(option))
2492
+ return false;
2493
+ const provider = providers[option];
2494
+ return provider.profileRequest !== undefined;
2495
+ };
2484
2496
  var isRefreshableProviderOption = (option) => {
2485
2497
  if (!isValidProviderOption(option))
2486
2498
  return false;
@@ -2500,6 +2512,28 @@ var isScopeRequiredProviderOption = (option) => {
2500
2512
  return provider.scopeRequired;
2501
2513
  };
2502
2514
  var isValidProviderOption = (option) => Object.hasOwn(providers, option);
2515
+ var assertWithingsSuccess = (value) => {
2516
+ if (!isObject(value) || value.status !== 0) {
2517
+ const status = isObject(value) ? value.status : "invalid response";
2518
+ const detail = isObject(value) && typeof value.error === "string" ? `: ${value.error}` : "";
2519
+ throw new Error(`Withings request failed (${String(status)})${detail}`);
2520
+ }
2521
+ };
2522
+ var createOAuth2FetchError = async (response) => {
2523
+ const clone = response.clone();
2524
+ const prefix = `HTTP ${response.status} ${response.statusText} for ${response.url}`;
2525
+ const payload = await response.json().catch(() => null);
2526
+ if (payload && typeof payload === "object" && Object.keys(payload).length) {
2527
+ return new Error(`${prefix}
2528
+ ${JSON.stringify(payload)}`);
2529
+ }
2530
+ const text3 = await clone.text().catch(() => "");
2531
+ if (text3) {
2532
+ return new Error(`${prefix}
2533
+ ${text3}`);
2534
+ }
2535
+ return new Error(prefix);
2536
+ };
2503
2537
  var encodeBase64 = (input) => {
2504
2538
  let raw;
2505
2539
  if (typeof input === "string") {
@@ -2510,25 +2544,31 @@ var encodeBase64 = (input) => {
2510
2544
  }
2511
2545
  return btoa(raw);
2512
2546
  };
2513
- var getWithingsProps = async (config) => {
2547
+ var getWithingsSignatureParams = async (config, action) => {
2514
2548
  const timestamp = Math.floor(Date.now() / 1000);
2515
- const signature = `getnonce,${config.clientId},${timestamp}`;
2516
- const hashedSignature = await hmacSha256(signature, config.clientSecret);
2549
+ const nonceSignature = await hmacSha256(`getnonce,${config.clientId},${timestamp}`, config.clientSecret);
2517
2550
  const nonceUrl = new URL("https://wbsapi.withings.net/v2/signature");
2518
2551
  nonceUrl.searchParams.set("action", "getnonce");
2519
2552
  nonceUrl.searchParams.set("client_id", config.clientId);
2520
2553
  nonceUrl.searchParams.set("timestamp", timestamp.toString());
2521
- nonceUrl.searchParams.set("signature", hashedSignature);
2554
+ nonceUrl.searchParams.set("signature", nonceSignature);
2522
2555
  const nonceTarget = nonceUrl.toString();
2523
2556
  const nonceResponse = await fetch(nonceTarget, { method: "POST" });
2557
+ if (!nonceResponse.ok) {
2558
+ throw await createOAuth2FetchError(nonceResponse);
2559
+ }
2524
2560
  const nonceData = await nonceResponse.json();
2525
- if (nonceData.status === 0) {
2526
- return {
2527
- hashedSignature,
2528
- nonce: nonceData.body.nonce
2529
- };
2561
+ if (!isObject(nonceData) || nonceData.status !== 0 || !isObject(nonceData.body) || typeof nonceData.body.nonce !== "string" || nonceData.body.nonce.length === 0) {
2562
+ throw new Error("Withings returned an invalid nonce response");
2530
2563
  }
2531
- return;
2564
+ const { nonce } = nonceData.body;
2565
+ const signature = await hmacSha256(`${action},${config.clientId},${nonce}`, config.clientSecret);
2566
+ return {
2567
+ action,
2568
+ client_id: config.clientId,
2569
+ nonce,
2570
+ signature
2571
+ };
2532
2572
  };
2533
2573
  var hmacSha256 = async (message, secret) => {
2534
2574
  const encoder = new TextEncoder;
@@ -2536,6 +2576,13 @@ var hmacSha256 = async (message, secret) => {
2536
2576
  const sigBuffer = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
2537
2577
  return Array.from(new Uint8Array(sigBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
2538
2578
  };
2579
+ var DAYS_IN_APPLE_CLIENT_SECRET_LIFETIME = 180;
2580
+ var HOURS_PER_DAY = 24;
2581
+ var MINUTES_PER_HOUR = 60;
2582
+ var SECONDS_PER_MINUTE = 60;
2583
+ var APPLE_CLIENT_SECRET_LIFETIME_SECONDS = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_IN_APPLE_CLIENT_SECRET_LIFETIME;
2584
+ var APPLE_ISSUER = "https://appleid.apple.com";
2585
+ var MILLISECONDS_PER_SECOND = 1000;
2539
2586
  var createRandomBase64UrlGenerator = (length) => () => {
2540
2587
  const buffer = crypto.getRandomValues(new Uint8Array(length));
2541
2588
  return base64Url(buffer);
@@ -2543,8 +2590,29 @@ var createRandomBase64UrlGenerator = (length) => () => {
2543
2590
  var generateCodeVerifier = createRandomBase64UrlGenerator(NUM_GENERATOR_BYTES);
2544
2591
  var generateState = createRandomBase64UrlGenerator(NUM_GENERATOR_BYTES);
2545
2592
  var base64Url = (input) => encodeBase64(input).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2593
+ var encodeJwtPart = (value) => base64Url(new TextEncoder().encode(JSON.stringify(value)));
2594
+ var createAppleClientSecret = async (credentials) => {
2595
+ const issuedAt = Math.floor(Date.now() / MILLISECONDS_PER_SECOND);
2596
+ const header = encodeJwtPart({
2597
+ alg: "ES256",
2598
+ kid: credentials.keyId,
2599
+ typ: "JWT"
2600
+ });
2601
+ const payload = encodeJwtPart({
2602
+ aud: APPLE_ISSUER,
2603
+ exp: issuedAt + APPLE_CLIENT_SECRET_LIFETIME_SECONDS,
2604
+ iat: issuedAt,
2605
+ iss: credentials.teamId,
2606
+ sub: credentials.clientId
2607
+ });
2608
+ const signingInput = `${header}.${payload}`;
2609
+ const privateKey = await crypto.subtle.importKey("pkcs8", Uint8Array.from(credentials.pkcs8PrivateKey), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
2610
+ const signature = await crypto.subtle.sign({ hash: "SHA-256", name: "ECDSA" }, privateKey, new TextEncoder().encode(signingInput));
2611
+ return `${signingInput}.${base64Url(signature)}`;
2612
+ };
2546
2613
  var oidcProviderOptions = Object.keys(providers).filter(isOIDCProviderOption);
2547
2614
  var pkceProviderOptions = Object.keys(providers).filter(isPKCEProviderOption);
2615
+ var profileProviderOptions = Object.keys(providers).filter(isProfileProviderOption);
2548
2616
  var providerOptions = Object.keys(providers).filter(isValidProviderOption);
2549
2617
  var refreshableProviderOptions = Object.keys(providers).filter(isRefreshableProviderOption);
2550
2618
  var revocableProviderOptions = Object.keys(providers).filter(isRevocableProviderOption);
@@ -2893,6 +2961,7 @@ var authSessionsTable = pgTable16("auth_sessions", {
2893
2961
  created_at: timestamp2("created_at").notNull().defaultNow(),
2894
2962
  expires_at_ms: bigint14("expires_at_ms", { mode: "number" }).notNull(),
2895
2963
  id: varchar16("id", { length: 255 }).primaryKey(),
2964
+ oauth_subject_json: jsonb8("oauth_subject_json").$type(),
2896
2965
  refresh_token: text6("refresh_token"),
2897
2966
  updated_at: timestamp2("updated_at").notNull().defaultNow(),
2898
2967
  user_json: jsonb8("user_json").$type().notNull()
@@ -2902,6 +2971,7 @@ var authUnregisteredSessionsTable = pgTable16("auth_unregistered_sessions", {
2902
2971
  created_at: timestamp2("created_at").notNull().defaultNow(),
2903
2972
  expires_at_ms: bigint14("expires_at_ms", { mode: "number" }).notNull(),
2904
2973
  id: varchar16("id", { length: 255 }).primaryKey(),
2974
+ oauth_subject_json: jsonb8("oauth_subject_json").$type(),
2905
2975
  refresh_token: text6("refresh_token"),
2906
2976
  session_information_json: jsonb8("session_information_json").$type(),
2907
2977
  updated_at: timestamp2("updated_at").notNull().defaultNow(),
@@ -3178,6 +3248,14 @@ var oidcResourceAudienceMigration = {
3178
3248
  ].join(`
3179
3249
  `)
3180
3250
  };
3251
+ var sessionOAuthSubjectMigration = {
3252
+ id: "0002_oauth_subject",
3253
+ sql: [
3254
+ 'ALTER TABLE "auth_sessions" ADD COLUMN IF NOT EXISTS "oauth_subject_json" jsonb;',
3255
+ 'ALTER TABLE "auth_unregistered_sessions" ADD COLUMN IF NOT EXISTS "oauth_subject_json" jsonb;'
3256
+ ].join(`
3257
+ `)
3258
+ };
3181
3259
  var blockMigrations = {
3182
3260
  adaptive: initMigration("adaptive", [knownDevicesTable, loginHistoryTable]),
3183
3261
  agents: {
@@ -3246,10 +3324,16 @@ var blockMigrations = {
3246
3324
  portal: initMigration("portal", [setupSessionsTable]),
3247
3325
  roles: initMigration("roles", [rolesTable]),
3248
3326
  scim: initMigration("scim", [scimTokensTable]),
3249
- sessions: initMigration("sessions", [
3250
- authSessionsTable,
3251
- authUnregisteredSessionsTable
3252
- ]),
3327
+ sessions: {
3328
+ block: "sessions",
3329
+ migrations: [
3330
+ ...initMigration("sessions", [
3331
+ authSessionsTable,
3332
+ authUnregisteredSessionsTable
3333
+ ]).migrations,
3334
+ sessionOAuthSubjectMigration
3335
+ ]
3336
+ },
3253
3337
  sso: initMigration("sso", [ssoConnectionsTable, samlServiceProvidersTable]),
3254
3338
  vault: initMigration("vault", [vaultEntriesTable]),
3255
3339
  vc: initMigration("vc", [
@@ -3447,5 +3531,5 @@ var main = async () => {
3447
3531
  };
3448
3532
  await main();
3449
3533
 
3450
- //# debugId=C8D20760311031E264756E2164756E21
3534
+ //# debugId=CF3F65D5B7AF923D64756E2164756E21
3451
3535
  //# sourceMappingURL=migrate.js.map