@rebasepro/server 0.26.0 → 0.27.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.
Files changed (55) hide show
  1. package/dist/{GCSStorageController-40FyFeSx.js → GCSStorageController-BUClIfp0.js} +35 -2
  2. package/dist/GCSStorageController-BUClIfp0.js.map +1 -0
  3. package/dist/{S3StorageController-Bl5shp94.js → S3StorageController-CixCQEky.js} +53 -9
  4. package/dist/S3StorageController-CixCQEky.js.map +1 -0
  5. package/dist/access-BFAUvsSs.js.map +1 -1
  6. package/dist/auth/admin-users-route.d.ts +3 -0
  7. package/dist/auth/apple-oauth.d.ts +39 -10
  8. package/dist/auth/capabilities.d.ts +2 -0
  9. package/dist/auth/interfaces.d.ts +55 -0
  10. package/dist/{auth-izI7AEzC.js → auth-DDXPw0mn.js} +179 -25
  11. package/dist/{auth-izI7AEzC.js.map → auth-DDXPw0mn.js.map} +1 -1
  12. package/dist/auth_adapter-B7RUMk6e.js.map +1 -1
  13. package/dist/backend/options.d.ts +29 -1
  14. package/dist/backend-CaG_Jyso.js.map +1 -1
  15. package/dist/{backup-BVbHoKo8.js → backup-B6brPSeB.js} +4 -4
  16. package/dist/{backup-BVbHoKo8.js.map → backup-B6brPSeB.js.map} +1 -1
  17. package/dist/boot/env.d.ts +6 -0
  18. package/dist/cron/cron-loader.d.ts +4 -0
  19. package/dist/{cron-loader-mMhqbVsl.js → cron-loader-CC1Jy_KN.js} +13 -5
  20. package/dist/cron-loader-CC1Jy_KN.js.map +1 -0
  21. package/dist/{cron-routes-Cs33j_Kr.js → cron-routes-BK60Rn1r.js} +2 -2
  22. package/dist/{cron-routes-Cs33j_Kr.js.map → cron-routes-BK60Rn1r.js.map} +1 -1
  23. package/dist/{cron-scheduler-Be7CNghL.js → cron-scheduler-DyCjPlQR.js} +39 -26
  24. package/dist/cron-scheduler-DyCjPlQR.js.map +1 -0
  25. package/dist/{load-failure-L5hvfDoG.js → dynamic-import-Bi3XK5y-.js} +30 -18
  26. package/dist/dynamic-import-Bi3XK5y-.js.map +1 -0
  27. package/dist/{function-loader-B8YzXEsQ.js → function-loader-eFigStYX.js} +14 -5
  28. package/dist/function-loader-eFigStYX.js.map +1 -0
  29. package/dist/functions/function-loader.d.ts +5 -0
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.es.js +596 -87
  32. package/dist/index.es.js.map +1 -1
  33. package/dist/init/docs.d.ts +1 -1
  34. package/dist/init/health.d.ts +13 -0
  35. package/dist/metrics/index.d.ts +8 -0
  36. package/dist/metrics/realtime.d.ts +25 -0
  37. package/dist/services/routed-realtime-service.d.ts +1 -1
  38. package/dist/storage/GCSStorageController.d.ts +9 -1
  39. package/dist/storage/LocalStorageController.d.ts +8 -1
  40. package/dist/storage/S3StorageController.d.ts +4 -2
  41. package/dist/storage/index.d.ts +1 -0
  42. package/dist/storage/policies.d.ts +1 -1
  43. package/dist/storage/streams.d.ts +17 -0
  44. package/dist/storage/types.d.ts +15 -33
  45. package/dist/{upload-validation-Bgo626uY.js → upload-validation-CkkQGs-j.js} +40 -2
  46. package/dist/upload-validation-CkkQGs-j.js.map +1 -0
  47. package/dist/utils/load-failure.d.ts +9 -0
  48. package/package.json +5 -5
  49. package/dist/GCSStorageController-40FyFeSx.js.map +0 -1
  50. package/dist/S3StorageController-Bl5shp94.js.map +0 -1
  51. package/dist/cron-loader-mMhqbVsl.js.map +0 -1
  52. package/dist/cron-scheduler-Be7CNghL.js.map +0 -1
  53. package/dist/function-loader-B8YzXEsQ.js.map +0 -1
  54. package/dist/load-failure-L5hvfDoG.js.map +0 -1
  55. package/dist/upload-validation-Bgo626uY.js.map +0 -1
@@ -9,6 +9,9 @@
9
9
  * PUT /users/:uid
10
10
  * DELETE /users/:uid
11
11
  * DELETE /users/:uid/mfa
12
+ * GET /guests
13
+ * DELETE /guests
14
+ * DELETE /guests/:uid
12
15
  * POST /bootstrap
13
16
  */
14
17
  import { Hono } from "hono";
@@ -1,7 +1,23 @@
1
1
  import type { OAuthProvider } from "./interfaces.js";
2
2
  import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
- /** Extra field Apple's client sends that no other provider has. */
4
- export interface AppleCodeFlowPayload extends OAuthCodeFlowPayload {
3
+ /**
4
+ * The request body `POST /auth/apple` accepts.
5
+ *
6
+ * Apple mints a code for one of two kinds of client, and the token exchange
7
+ * has to name the same one:
8
+ * - **Web** — the code was issued to the Services ID through a browser
9
+ * authorization, so it carries the `redirectUri` that authorization used.
10
+ * - **Native** — the code came from `ASAuthorizationController` in an iOS,
11
+ * iPadOS or macOS app. It was issued to the app's bundle id and there was no
12
+ * redirect, so the client names the `bundleId` instead.
13
+ *
14
+ * Exactly one of the two is sent.
15
+ */
16
+ export interface AppleCodeFlowPayload extends Omit<OAuthCodeFlowPayload, "redirectUri"> {
17
+ /** Web sign-in: the redirect URI the browser authorization used. */
18
+ redirectUri?: string;
19
+ /** Native sign-in: the bundle id of the app that obtained the code. */
20
+ bundleId?: string;
5
21
  /**
6
22
  * Apple sends the user's *name* only on the first authorization, so the
7
23
  * frontend has to forward it. It is display data and nothing else — the
@@ -14,6 +30,24 @@ export interface AppleCodeFlowPayload extends OAuthCodeFlowPayload {
14
30
  };
15
31
  };
16
32
  }
33
+ export interface AppleProviderConfig {
34
+ /**
35
+ * The Services ID that web sign-in authorizes against. Optional when
36
+ * `bundleIds` is set: an app that only signs in from iOS has no Services ID.
37
+ */
38
+ clientId?: string;
39
+ /**
40
+ * Bundle ids of the native apps (iOS, iPadOS, macOS) whose codes this
41
+ * backend accepts. A native code is issued to the app, not to the Services
42
+ * ID, so each app is a client of its own. Apple's `sub` is per team, so the
43
+ * same person signing in on the web and in the app is one identity.
44
+ */
45
+ bundleIds?: string[];
46
+ teamId: string;
47
+ keyId: string;
48
+ /** The raw PEM contents of the .p8 private key file */
49
+ privateKey: string;
50
+ }
17
51
  /**
18
52
  * Creates an Apple Sign In OAuth Provider integration.
19
53
  *
@@ -21,15 +55,10 @@ export interface AppleCodeFlowPayload extends OAuthCodeFlowPayload {
21
55
  * token exchange (valid up to 6 months). This provider handles that automatically.
22
56
  *
23
57
  * Required Apple Developer configuration:
24
- * - Services ID (clientId)
58
+ * - Services ID (clientId) for web sign-in, and/or the bundle ids of the
59
+ * native apps (bundleIds)
25
60
  * - Key ID from the private key registered with Apple
26
61
  * - Team ID from Apple Developer account
27
62
  * - Private key (.p8 file contents) downloaded from Apple Developer portal
28
63
  */
29
- export declare function createAppleProvider(config: {
30
- clientId: string;
31
- teamId: string;
32
- keyId: string;
33
- /** The raw PEM contents of the .p8 private key file */
34
- privateKey: string;
35
- }): OAuthProvider<AppleCodeFlowPayload>;
64
+ export declare function createAppleProvider(config: AppleProviderConfig): OAuthProvider<AppleCodeFlowPayload>;
@@ -40,6 +40,8 @@ export interface BuiltinAuthCapabilityInputs {
40
40
  emailConfigured: boolean;
41
41
  /** OAuth provider ids the backend has wired, e.g. `["google", "github"]`. */
42
42
  enabledProviders: string[];
43
+ /** Public client ids by provider id, for the providers that publish one. */
44
+ providerClientIds?: Record<string, string>;
43
45
  }
44
46
  /**
45
47
  * Build the capability document for the built-in auth adapter.
@@ -95,6 +95,14 @@ export interface OAuthProvider<T = unknown> {
95
95
  id: string;
96
96
  /** Zod schema validating the expected request payload (e.g. { code: string }) */
97
97
  schema: z.ZodSchema<T>;
98
+ /**
99
+ * The client id a browser needs to *start* this provider's sign-in, when
100
+ * it is public. Published in `GET /auth/config` as
101
+ * `providerClientIds[id]`, so a login screen can offer the button from
102
+ * the backend's configuration alone rather than from a second copy of the
103
+ * id in the frontend's environment. Never set it to anything secret.
104
+ */
105
+ publicClientId?: string;
98
106
  /**
99
107
  * Verify external tokens/codes and return a standardized user profile.
100
108
  *
@@ -257,6 +265,32 @@ export interface PaginatedUsersResult {
257
265
  limit: number;
258
266
  offset: number;
259
267
  }
268
+ /** The window and filter of {@link UserRepository.listGuests}. */
269
+ export interface ListGuestsOptions {
270
+ /** Max results per page (default 25) */
271
+ limit?: number;
272
+ /** Number of results to skip (default 0) */
273
+ offset?: number;
274
+ /** Only the guests last seen before this instant. */
275
+ lastSeenBefore?: Date;
276
+ }
277
+ /** A row anonymous sign-in made, that has not become an account. */
278
+ export interface GuestData {
279
+ id: string;
280
+ createdAt: Date;
281
+ /**
282
+ * When its newest refresh token was issued: a session refreshing rotates
283
+ * its token, so this moves while a guest keeps coming back. `createdAt`
284
+ * when no token is left.
285
+ */
286
+ lastSeenAt: Date;
287
+ }
288
+ /** Result of {@link UserRepository.listGuests}. */
289
+ export interface PaginatedGuestsResult {
290
+ guests: GuestData[];
291
+ /** How many guests match, ignoring limit and offset. */
292
+ total: number;
293
+ }
260
294
  /**
261
295
  * Abstract user repository interface.
262
296
  * Handles all user-related database operations.
@@ -334,6 +368,27 @@ export interface UserRepository {
334
368
  * instead (`isUserTableEmpty` / `isOnlyUser` in `registration-policy.ts`).
335
369
  */
336
370
  firstUserIds?(limit: number): Promise<string[]>;
371
+ /**
372
+ * The guests, the ones last seen longest ago first — a stable order, for
373
+ * the same `lastSeenBefore` and offset.
374
+ *
375
+ * A guest is `isAnonymous` with no way to sign back in: no password and no
376
+ * linked identity. The flag alone is not enough, because a row can carry it
377
+ * and still belong to someone who signs in.
378
+ *
379
+ * Optional, with {@link deleteGuest}: the admin guest routes answer 501 on
380
+ * a repository without them.
381
+ */
382
+ listGuests?(options?: ListGuestsOptions): Promise<PaginatedGuestsResult>;
383
+ /**
384
+ * Delete this user if it is a guest, as {@link listGuests} means it, and
385
+ * say whether it did. The statement that deletes is what decides, so an
386
+ * account can never go through here, whatever the caller read a moment ago.
387
+ *
388
+ * A row of the project's own that requires the guest (`ON DELETE RESTRICT`)
389
+ * is a 409 `GUEST_REFERENCED`.
390
+ */
391
+ deleteGuest?(id: string): Promise<boolean>;
337
392
  /**
338
393
  * Update user's password hash. `null` removes the password: the account
339
394
  * then signs in only by link, code or provider.
@@ -14,7 +14,7 @@ import { t as firstSqlRow } from "./sql-rows-C6GEc2oE.js";
14
14
  import { a as resolveListLimitParam } from "./query-parser-CDXWf2hH.js";
15
15
  import { _ as verifyAccessToken, a as generateAccessToken, c as getAccessTokenExpiry, d as hasAsymmetricSigningKey, f as hashRefreshToken, h as processJwtService, i as customClaimsOf, l as getJwks, m as jwtOf, n as configureJwt, o as generateDownloadToken, p as isJwtConfigured, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as randomInt$1, x as require_jsonwebtoken } from "./jwt-rDS0884_.js";
16
16
  import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-CjRrn12l.js";
17
- import { a as isDataException, c as warnIfDatabaseClosed, i as errorHandler, o as isDatabaseUnreachable, t as ApiError } from "./errors-OMWkKSH-.js";
17
+ import { a as isDataException, c as warnIfDatabaseClosed, i as errorHandler, o as isDatabaseUnreachable, r as declaredErrorAnswer, t as ApiError } from "./errors-OMWkKSH-.js";
18
18
  import { createHash, randomBytes, randomInt } from "node:crypto";
19
19
  import { Hono } from "hono";
20
20
  import { promisify } from "util";
@@ -5907,7 +5907,7 @@ function createAuthRoutes(config) {
5907
5907
  * `anonymousLogin` go through the shared predicates for exactly that reason.
5908
5908
  */
5909
5909
  function buildBuiltinAuthCapabilities(inputs) {
5910
- const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, emailConfigured, enabledProviders } = inputs;
5910
+ const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, emailConfigured, enabledProviders, providerClientIds } = inputs;
5911
5911
  return {
5912
5912
  hasBuiltInAuthRoutes: true,
5913
5913
  emailPasswordLogin: true,
@@ -5928,6 +5928,7 @@ function buildBuiltinAuthCapabilities(inputs) {
5928
5928
  disableSelfRegistration
5929
5929
  }),
5930
5930
  enabledProviders,
5931
+ ...providerClientIds && Object.keys(providerClientIds).length > 0 ? { providerClientIds } : {},
5931
5932
  needsSetup
5932
5933
  };
5933
5934
  }
@@ -6174,10 +6175,34 @@ function mayPickUsers(c) {
6174
6175
  * PUT /users/:uid
6175
6176
  * DELETE /users/:uid
6176
6177
  * DELETE /users/:uid/mfa
6178
+ * GET /guests
6179
+ * DELETE /guests
6180
+ * DELETE /guests/:uid
6177
6181
  * POST /bootstrap
6178
6182
  */
6179
6183
  /** Upper bound for `GET /users?ids=…`, so one request can't fan out unbounded. */
6180
6184
  var MAX_USER_IDS_PER_LOOKUP = 100;
6185
+ /**
6186
+ * How many guests one `DELETE /guests` takes, so a project with a million of
6187
+ * them is cleaned over many short requests. Each guest is a few statements.
6188
+ */
6189
+ var GUESTS_PER_DELETE = 200;
6190
+ /** A repository without the guest operations cannot answer these routes. */
6191
+ function requireGuestStore(repo) {
6192
+ if (typeof repo.listGuests !== "function" || typeof repo.deleteGuest !== "function") throw new ApiError(501, "NOT_SUPPORTED", "This backend's auth repository cannot list or delete guests.");
6193
+ }
6194
+ /** `?lastSeenBefore=`, which reaches the guests' deletion: a date in the past, or a refusal. */
6195
+ function readLastSeenBefore(c) {
6196
+ const value = c.req.query("lastSeenBefore");
6197
+ if (value === void 0) return void 0;
6198
+ const date = new Date(value);
6199
+ if (Number.isNaN(date.getTime()) || date.getTime() > Date.now()) throw ApiError.badRequest("`lastSeenBefore` must be a date in the past", "INVALID_INPUT");
6200
+ return date;
6201
+ }
6202
+ /** `?offset=`, as `GET /users` reads it. */
6203
+ function readOffset(c) {
6204
+ return Math.max(0, parseInt(c.req.query("offset") ?? "0", 10) || 0);
6205
+ }
6181
6206
  function createAdminUsersRoute(config) {
6182
6207
  const router = new Hono();
6183
6208
  const authRepo = config.authRepo;
@@ -6465,6 +6490,108 @@ function createAdminUsersRoute(config) {
6465
6490
  removedFactors: factors.length
6466
6491
  });
6467
6492
  });
6493
+ /**
6494
+ * Delete one guest under the rules and hooks of `DELETE /users/:uid`, and
6495
+ * say whether it went. It does not go when it is not a guest any more:
6496
+ * `deleteGuest` decides that in the statement that deletes. The sessions
6497
+ * end after it, not before as there: a guest who became an account a moment
6498
+ * ago keeps the ones it has.
6499
+ */
6500
+ async function removeGuest(c, repo, uid) {
6501
+ assertMayManageAccount(c, await authRepo.getUserRoleIds(uid));
6502
+ await assertUserDeletionsAllowed(authRepo, [uid]);
6503
+ if (ops.beforeUserDelete) await ops.beforeUserDelete(uid);
6504
+ if (!await repo.deleteGuest(uid)) return false;
6505
+ await authRepo.deleteAllRefreshTokensForUser(uid);
6506
+ runAfterUserDelete(ops, uid);
6507
+ return true;
6508
+ }
6509
+ /**
6510
+ * The guests anonymous sign-in left behind, the ones last seen longest ago
6511
+ * first, with how many there are. `?lastSeenBefore=` narrows them to the
6512
+ * ones `DELETE /guests` would take, which makes `total` its dry run.
6513
+ *
6514
+ * A route of its own, not a filter on `GET /users`: a runtime that does not
6515
+ * know a filter ignores it and answers with every account.
6516
+ */
6517
+ router.get("/guests", requireScope("users:read"), async (c) => {
6518
+ requireGuestStore(authRepo);
6519
+ const limit = resolveListLimitParam(c.req.query("limit"), { defaultLimit: 25 });
6520
+ const offset = readOffset(c);
6521
+ const { guests, total } = await authRepo.listGuests({
6522
+ limit,
6523
+ offset,
6524
+ lastSeenBefore: readLastSeenBefore(c)
6525
+ });
6526
+ const listed = guests.map((guest) => ({
6527
+ uid: guest.id,
6528
+ createdAt: guest.createdAt.toISOString(),
6529
+ lastSeenAt: guest.lastSeenAt.toISOString()
6530
+ }));
6531
+ return c.json({
6532
+ guests: listed,
6533
+ total,
6534
+ limit,
6535
+ offset
6536
+ });
6537
+ });
6538
+ /**
6539
+ * Delete one batch of the guests last seen before `?lastSeenBefore=`, which
6540
+ * is required: nothing here means "all of them". Every id comes from
6541
+ * `listGuests` and goes through `deleteGuest`, so no account can be reached.
6542
+ *
6543
+ * One guest that cannot go does not stop the rest: it is reported in
6544
+ * `skipped` and stays at the front of the order, which is why the caller
6545
+ * passes how many it has skipped as `?offset=`.
6546
+ */
6547
+ router.delete("/guests", requireScope("users:write"), async (c) => {
6548
+ requireGuestStore(authRepo);
6549
+ const lastSeenBefore = readLastSeenBefore(c);
6550
+ if (!lastSeenBefore) throw ApiError.badRequest("`lastSeenBefore` is required", "INVALID_INPUT");
6551
+ const offset = readOffset(c);
6552
+ const { guests, total } = await authRepo.listGuests({
6553
+ limit: GUESTS_PER_DELETE,
6554
+ offset,
6555
+ lastSeenBefore
6556
+ });
6557
+ const result = {
6558
+ deleted: 0,
6559
+ skipped: [],
6560
+ remaining: Math.max(0, total - offset - guests.length)
6561
+ };
6562
+ for (const { id } of guests) try {
6563
+ if (await removeGuest(c, authRepo, id)) result.deleted++;
6564
+ } catch (err) {
6565
+ const answer = declaredErrorAnswer(err);
6566
+ if (!answer) logger.error("Could not delete a guest", {
6567
+ uid: id,
6568
+ error: err instanceof Error ? err.message : err
6569
+ });
6570
+ result.skipped.push({
6571
+ uid: id,
6572
+ code: answer?.code ?? "INTERNAL_ERROR",
6573
+ message: answer?.message ?? "Could not delete this guest. See the server log."
6574
+ });
6575
+ }
6576
+ logger.info("[Security Audit] Guests deleted by an administrator", {
6577
+ eventType: "auth.guests.deleted",
6578
+ by: c.get("user")?.uid,
6579
+ lastSeenBefore: lastSeenBefore.toISOString(),
6580
+ deleted: result.deleted,
6581
+ skipped: result.skipped.length
6582
+ });
6583
+ return c.json(result);
6584
+ });
6585
+ router.delete("/guests/:uid", requireScope("users:write"), async (c) => {
6586
+ requireGuestStore(authRepo);
6587
+ const uid = c.req.param("uid");
6588
+ const existing = await authRepo.getUserById(uid);
6589
+ if (!existing) throw ApiError.notFound("User not found");
6590
+ const refuse = () => ApiError.badRequest("This user is an account, not a guest.", "NOT_ANONYMOUS");
6591
+ if (existing.isAnonymous !== true) throw refuse();
6592
+ if (!await removeGuest(c, authRepo, uid)) throw refuse();
6593
+ return c.json({ success: true });
6594
+ });
6468
6595
  router.delete("/users/:uid", requireScope("users:write"), async (c) => {
6469
6596
  const uid = c.req.param("uid");
6470
6597
  if (c.get("user")?.uid === uid) throw ApiError.badRequest("Cannot delete your own account", "SELF_DELETE");
@@ -6730,7 +6857,8 @@ function createBuiltinAuthAdapter(config) {
6730
6857
  enableMagicLink,
6731
6858
  enableEmailOtp,
6732
6859
  emailConfigured: !!emailService?.isConfigured(),
6733
- enabledProviders: oauthProviders.map((p) => p.id)
6860
+ enabledProviders: oauthProviders.map((p) => p.id),
6861
+ providerClientIds: Object.fromEntries(oauthProviders.flatMap((p) => p.publicClientId ? [[p.id, p.publicClientId]] : []))
6734
6862
  });
6735
6863
  }
6736
6864
  };
@@ -8120,53 +8248,79 @@ var APPLE_JWKS_URI = "https://appleid.apple.com/auth/keys";
8120
8248
  * token exchange (valid up to 6 months). This provider handles that automatically.
8121
8249
  *
8122
8250
  * Required Apple Developer configuration:
8123
- * - Services ID (clientId)
8251
+ * - Services ID (clientId) for web sign-in, and/or the bundle ids of the
8252
+ * native apps (bundleIds)
8124
8253
  * - Key ID from the private key registered with Apple
8125
8254
  * - Team ID from Apple Developer account
8126
8255
  * - Private key (.p8 file contents) downloaded from Apple Developer portal
8127
8256
  */
8128
8257
  function createAppleProvider(config) {
8258
+ const bundleIds = (config.bundleIds ?? []).map((id) => id.trim()).filter(Boolean);
8259
+ if (!config.clientId && bundleIds.length === 0) throw new Error("Apple sign-in needs a Services ID (clientId), at least one app bundle id (bundleIds), or both.");
8129
8260
  /**
8130
8261
  * Generate a client_secret JWT signed with the Apple private key.
8131
- * Apple requires this instead of a static client_secret.
8262
+ * Apple requires this instead of a static client_secret, and its `sub`
8263
+ * names the client the code was issued to.
8132
8264
  */
8133
- async function generateClientSecret() {
8265
+ async function generateClientSecret(clientId) {
8134
8266
  return import_jsonwebtoken.default.sign({}, config.privateKey, {
8135
8267
  algorithm: "ES256",
8136
8268
  keyid: config.keyId,
8137
8269
  issuer: config.teamId,
8138
8270
  expiresIn: "180d",
8139
8271
  audience: "https://appleid.apple.com",
8140
- subject: config.clientId
8272
+ subject: clientId
8141
8273
  });
8142
8274
  }
8275
+ /**
8276
+ * The client the code was issued to, or null when this backend does not
8277
+ * know it. The bundle id is the caller's claim, so it is only ever taken
8278
+ * from the configured list — and Apple refuses the exchange anyway if the
8279
+ * code was issued to a different client than the one named.
8280
+ */
8281
+ function resolveClient(payload) {
8282
+ if (payload.bundleId !== void 0) return bundleIds.includes(payload.bundleId) ? { clientId: payload.bundleId } : null;
8283
+ return config.clientId ? {
8284
+ clientId: config.clientId,
8285
+ redirectUri: payload.redirectUri
8286
+ } : null;
8287
+ }
8143
8288
  return {
8144
8289
  id: "apple",
8145
- schema: oauthCodeFlowSchema().extend({
8146
- /**
8147
- * Apple sends user info only on first authorization; the frontend
8148
- * must forward it. Only the *name* is accepted — an `email` here
8149
- * used to be promoted to the account's identity whenever the
8150
- * id_token had no `email` claim, and an attacker chooses whether
8151
- * that claim is absent simply by omitting the `email` scope from
8152
- * their own authorization request.
8153
- */
8154
- user: z.object({ name: z.object({
8155
- firstName: z.string().optional(),
8156
- lastName: z.string().optional()
8157
- }).optional() }).optional() }),
8290
+ publicClientId: config.clientId,
8291
+ schema: oauthCodeFlowSchema().extend({
8292
+ redirectUri: z.string().url("Valid redirect URI is required").optional(),
8293
+ bundleId: z.string().min(1).optional(),
8294
+ /**
8295
+ * Apple sends user info only on first authorization; the frontend
8296
+ * must forward it. Only the *name* is accepted — an `email` here
8297
+ * used to be promoted to the account's identity whenever the
8298
+ * id_token had no `email` claim, and an attacker chooses whether
8299
+ * that claim is absent simply by omitting the `email` scope from
8300
+ * their own authorization request.
8301
+ */
8302
+ user: z.object({ name: z.object({
8303
+ firstName: z.string().optional(),
8304
+ lastName: z.string().optional()
8305
+ }).optional() }).optional()
8306
+ }).refine((payload) => payload.redirectUri === void 0 !== (payload.bundleId === void 0), { message: "Send redirectUri for web sign-in or bundleId for a native app, not both" }),
8158
8307
  verify: async (payload) => {
8308
+ const client = resolveClient(payload);
8309
+ if (!client) {
8310
+ logger.error(payload.bundleId !== void 0 ? "Apple sign-in from an app bundle id this backend does not list in bundleIds" : "Apple web sign-in needs a Services ID (clientId), and none is configured");
8311
+ return null;
8312
+ }
8159
8313
  try {
8160
- const clientSecret = await generateClientSecret();
8314
+ const clientSecret = await generateClientSecret(client.clientId);
8161
8315
  const tokenResponse = await fetch("https://appleid.apple.com/auth/token", {
8162
8316
  method: "POST",
8163
8317
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
8164
8318
  body: new URLSearchParams({
8165
- client_id: config.clientId,
8319
+ client_id: client.clientId,
8166
8320
  client_secret: clientSecret,
8167
8321
  code: payload.code,
8168
8322
  grant_type: "authorization_code",
8169
- redirect_uri: payload.redirectUri,
8323
+ ...client.redirectUri ? { redirect_uri: client.redirectUri } : {},
8170
8324
  ...pkceTokenParams(payload.codeVerifier)
8171
8325
  })
8172
8326
  });
@@ -8179,7 +8333,7 @@ user: z.object({ name: z.object({
8179
8333
  idToken: tokenData.id_token,
8180
8334
  jwksUri: APPLE_JWKS_URI,
8181
8335
  issuer: APPLE_ISSUER,
8182
- audience: config.clientId
8336
+ audience: client.clientId
8183
8337
  }) : null;
8184
8338
  if (!decoded) {
8185
8339
  logger.error("Apple token exchange returned no verifiable id_token");
@@ -8760,4 +8914,4 @@ var auth_exports = /* @__PURE__ */ __exportAll({
8760
8914
  //#endregion
8761
8915
  export { getEmailChangeTemplate as $, createDataRateLimiter as A, SMTPEmailService as B, createJwksRoutes as C, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as D, isBootstrapWindowOpen as E, clearActiveDevEmailSink as F, verifyPassword as G, resolveAuthHooks as H, createDevEmailSink as I, completeUserCreation as J, adapterRefusal as K, devEmailSinkFor as L, setSharedRateLimitStore as M, MemoryRateLimitStore as N, createAuthLimiters as O, activeDevEmailSink as P, getEmailChangeNoticeTemplate as Q, extractLinks as R, createApiKeyStore as S, configureUserPicking as T, hashPassword as U, createEmailService as V, validatePasswordStrength as W, assertEmailLinkBases as X, generateSecurePassword as Y, resolveEmailLinkBase as Z, oauthCodeFlowSchema as _, createBitbucketProvider as a, getWelcomeEmailTemplate as at, createApiKeyRoutes as b, createTwitterProvider as c, escapeHtml as ct, createMicrosoftProvider as d, createSqlRateLimitStore as dt, getEmailOtpTemplate as et, tryVerifyOidcIdToken as f, resolveRateLimitStoreKind as ft, createGoogleProvider as g, createLinkedinProvider as h, createSlackProvider as i, getUserInvitationTemplate as it, createRateLimiter as j, createDataRateLimitCheck as k, createFacebookProvider as l, html as lt, createGitHubProvider as m, createCustomAuthAdapter as n, getMagicLinkTemplate as nt, createGitLabProvider as o, resolveEmailBranding as ot, verifyOidcIdToken as p, securityRuleToConditions as pt, createAdapterAuthMiddleware as q, createSpotifyProvider as r, getPasswordResetTemplate as rt, createDiscordProvider as s, RawHtml as st, auth_exports as t, getEmailVerificationTemplate as tt, createAppleProvider as u, raw as ut, pkceTokenParams as v, createBuiltinAuthAdapter as w, createPersonalKeyRoutes as x, providerVerifiedEmail as y, registerDevEmailSink as z };
8762
8916
 
8763
- //# sourceMappingURL=auth-izI7AEzC.js.map
8917
+ //# sourceMappingURL=auth-DDXPw0mn.js.map