@shware/security 8.0.1 → 9.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.
Files changed (62) hide show
  1. package/README.md +15 -6
  2. package/dist/auth/error.cjs.map +1 -1
  3. package/dist/auth/error.d.cts +5 -2
  4. package/dist/auth/error.d.cts.map +1 -1
  5. package/dist/auth/error.d.mts +5 -2
  6. package/dist/auth/error.d.mts.map +1 -1
  7. package/dist/auth/error.mjs.map +1 -1
  8. package/dist/auth/index.cjs +45 -15
  9. package/dist/auth/index.cjs.map +1 -1
  10. package/dist/auth/index.d.cts +12 -3
  11. package/dist/auth/index.d.cts.map +1 -1
  12. package/dist/auth/index.d.mts +12 -3
  13. package/dist/auth/index.d.mts.map +1 -1
  14. package/dist/auth/index.mjs +45 -15
  15. package/dist/auth/index.mjs.map +1 -1
  16. package/dist/auth/types.d.cts +20 -9
  17. package/dist/auth/types.d.cts.map +1 -1
  18. package/dist/auth/types.d.mts +20 -9
  19. package/dist/auth/types.d.mts.map +1 -1
  20. package/dist/index.d.cts +2 -2
  21. package/dist/index.d.mts +2 -2
  22. package/dist/oauth2/client.cjs +10 -1
  23. package/dist/oauth2/client.cjs.map +1 -1
  24. package/dist/oauth2/client.d.cts +7 -1
  25. package/dist/oauth2/client.d.cts.map +1 -1
  26. package/dist/oauth2/client.d.mts +7 -1
  27. package/dist/oauth2/client.d.mts.map +1 -1
  28. package/dist/oauth2/client.mjs +10 -1
  29. package/dist/oauth2/client.mjs.map +1 -1
  30. package/dist/oauth2/provider/apple.cjs +4 -0
  31. package/dist/oauth2/provider/apple.cjs.map +1 -1
  32. package/dist/oauth2/provider/apple.d.cts.map +1 -1
  33. package/dist/oauth2/provider/apple.d.mts.map +1 -1
  34. package/dist/oauth2/provider/apple.mjs +4 -0
  35. package/dist/oauth2/provider/apple.mjs.map +1 -1
  36. package/dist/oauth2/provider/common.cjs +1 -0
  37. package/dist/oauth2/provider/common.cjs.map +1 -1
  38. package/dist/oauth2/provider/common.d.cts +1 -0
  39. package/dist/oauth2/provider/common.d.cts.map +1 -1
  40. package/dist/oauth2/provider/common.d.mts +1 -0
  41. package/dist/oauth2/provider/common.d.mts.map +1 -1
  42. package/dist/oauth2/provider/common.mjs +1 -0
  43. package/dist/oauth2/provider/common.mjs.map +1 -1
  44. package/dist/oauth2/provider/facebook.cjs +4 -0
  45. package/dist/oauth2/provider/facebook.cjs.map +1 -1
  46. package/dist/oauth2/provider/facebook.d.cts.map +1 -1
  47. package/dist/oauth2/provider/facebook.d.mts.map +1 -1
  48. package/dist/oauth2/provider/facebook.mjs +4 -0
  49. package/dist/oauth2/provider/facebook.mjs.map +1 -1
  50. package/dist/oauth2/provider/google.cjs +4 -0
  51. package/dist/oauth2/provider/google.cjs.map +1 -1
  52. package/dist/oauth2/provider/google.d.cts.map +1 -1
  53. package/dist/oauth2/provider/google.d.mts.map +1 -1
  54. package/dist/oauth2/provider/google.mjs +4 -0
  55. package/dist/oauth2/provider/google.mjs.map +1 -1
  56. package/dist/oauth2/types.cjs.map +1 -1
  57. package/dist/oauth2/types.d.cts +21 -0
  58. package/dist/oauth2/types.d.cts.map +1 -1
  59. package/dist/oauth2/types.d.mts +21 -0
  60. package/dist/oauth2/types.d.mts.map +1 -1
  61. package/dist/oauth2/types.mjs.map +1 -1
  62. package/package.json +1 -1
@@ -42,10 +42,16 @@ export declare class OAuth2Client {
42
42
  */
43
43
  private getNativeClient;
44
44
  private resolveSecret;
45
- createAuthorizationUri({ provider, state, pkce }: {
45
+ /** Which of the provider's flows echo a nonce in the id token (`Provider.nonce`). */
46
+ nonceSupport(provider: string): Promise<{
47
+ web: boolean;
48
+ native: boolean;
49
+ }>;
50
+ createAuthorizationUri({ provider, state, pkce, nonce }: {
46
51
  provider: string;
47
52
  state: string;
48
53
  pkce?: PkceParameters;
54
+ nonce?: string;
49
55
  }): Promise<URL>;
50
56
  /** Exchanges a code issued to the provider's web client: the redirect flow and One Tap. */
51
57
  exchangeAuthorizationCode({ provider, code, pkce }: {
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.cts","names":["_$__types0.UserInfo"],"sources":["../../src/oauth2/client.ts"],"mappings":";qBAkBa,8CAAyB;;;;;;;yBAQpC;qBAEW,uCAAkB;;;;;;;;;;yBAY7B;qBAEW;mBACM;EACjB,YAAY,QAAQ;MAIhB;MAIA;MAIA;;UAKU;UAUN;;UAKM;;;;;;UAaA;;;;;;UAcA;UAYA;EAIR,yBACJ,UACA,OACA;IAEA;IACA;IACA,OAAO;MACL,QAAQ;;EAYN,4BACJ,UACA,MACA;IAEA;IACA;IACA,OAAO;MACL;IAAU;IAAkB,OAAO;;;EAcjC,cACJ,UACA,UACA,OACA;IAEA;IACA;IACA,OAAO,cAAc;IACrB,WAAW;MACZ,QADYA;;EAOP,eAAe,UAAU;IAAgB;IAAkB;MAAoB;;;;;EAS/E,qBACJ,UACA,UACA;IAEA;IACA;IACA;MACE,QAAQ;EAON,cACJ,UACA,UACA;IAEA;IACA;IACA;MACD;;;;;EAWK,oBACJ,UACA,eAAe,kBAAkB,eACjC;IAEA;IACA,aAAa;IACb,OAAO,KAAK;MACb"}
1
+ {"version":3,"file":"client.d.cts","names":["_$__types0.UserInfo"],"sources":["../../src/oauth2/client.ts"],"mappings":";qBAkBa,8CAAyB;;;;;;;yBAQpC;qBAEW,uCAAkB;;;;;;;;;;yBAY7B;qBAEW;mBACM;EACjB,YAAY,QAAQ;MAIhB;MAIA;MAIA;;UAKU;UAUN;;UAKM;;;;;;UAaA;;;;;;UAcA;UAYA;;EAKR,aAAa,mBAAmB;IAAU;IAAc;;EAKxD,yBACJ,UACA,OACA,MACA;IAEA;IACA;IACA,OAAO;IACP;MACE,QAAQ;;EAaN,4BACJ,UACA,MACA;IAEA;IACA;IACA,OAAO;MACL;IAAU;IAAkB,OAAO;;;EAcjC,cACJ,UACA,UACA,OACA;IAEA;IACA;IACA,OAAO,cAAc;IACrB,WAAW;MACZ,QADYA;;EAOP,eAAe,UAAU;IAAgB;IAAkB;MAAoB;;;;;EAS/E,qBACJ,UACA,UACA;IAEA;IACA;IACA;MACE,QAAQ;EAON,cACJ,UACA,UACA;IAEA;IACA;IACA;MACD;;;;;EAWK,oBACJ,UACA,eAAe,kBAAkB,eACjC;IAEA;IACA,aAAa;IACb,OAAO,KAAK;MACb"}
@@ -42,10 +42,16 @@ export declare class OAuth2Client {
42
42
  */
43
43
  private getNativeClient;
44
44
  private resolveSecret;
45
- createAuthorizationUri({ provider, state, pkce }: {
45
+ /** Which of the provider's flows echo a nonce in the id token (`Provider.nonce`). */
46
+ nonceSupport(provider: string): Promise<{
47
+ web: boolean;
48
+ native: boolean;
49
+ }>;
50
+ createAuthorizationUri({ provider, state, pkce, nonce }: {
46
51
  provider: string;
47
52
  state: string;
48
53
  pkce?: PkceParameters;
54
+ nonce?: string;
49
55
  }): Promise<URL>;
50
56
  /** Exchanges a code issued to the provider's web client: the redirect flow and One Tap. */
51
57
  exchangeAuthorizationCode({ provider, code, pkce }: {
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.mts","names":["_$__types0.UserInfo"],"sources":["../../src/oauth2/client.ts"],"mappings":";qBAkBa,8CAAyB;;;;;;;yBAQpC;qBAEW,uCAAkB;;;;;;;;;;yBAY7B;qBAEW;mBACM;EACjB,YAAY,QAAQ;MAIhB;MAIA;MAIA;;UAKU;UAUN;;UAKM;;;;;;UAaA;;;;;;UAcA;UAYA;EAIR,yBACJ,UACA,OACA;IAEA;IACA;IACA,OAAO;MACL,QAAQ;;EAYN,4BACJ,UACA,MACA;IAEA;IACA;IACA,OAAO;MACL;IAAU;IAAkB,OAAO;;;EAcjC,cACJ,UACA,UACA,OACA;IAEA;IACA;IACA,OAAO,cAAc;IACrB,WAAW;MACZ,QADYA;;EAOP,eAAe,UAAU;IAAgB;IAAkB;MAAoB;;;;;EAS/E,qBACJ,UACA,UACA;IAEA;IACA;IACA;MACE,QAAQ;EAON,cACJ,UACA,UACA;IAEA;IACA;IACA;MACD;;;;;EAWK,oBACJ,UACA,eAAe,kBAAkB,eACjC;IAEA;IACA,aAAa;IACb,OAAO,KAAK;MACb"}
1
+ {"version":3,"file":"client.d.mts","names":["_$__types0.UserInfo"],"sources":["../../src/oauth2/client.ts"],"mappings":";qBAkBa,8CAAyB;;;;;;;yBAQpC;qBAEW,uCAAkB;;;;;;;;;;yBAY7B;qBAEW;mBACM;EACjB,YAAY,QAAQ;MAIhB;MAIA;MAIA;;UAKU;UAUN;;UAKM;;;;;;UAaA;;;;;;UAcA;UAYA;;EAKR,aAAa,mBAAmB;IAAU;IAAc;;EAKxD,yBACJ,UACA,OACA,MACA;IAEA;IACA;IACA,OAAO;IACP;MACE,QAAQ;;EAaN,4BACJ,UACA,MACA;IAEA;IACA;IACA,OAAO;MACL;IAAU;IAAkB,OAAO;;;EAcjC,cACJ,UACA,UACA,OACA;IAEA;IACA;IACA,OAAO,cAAc;IACrB,WAAW;MACZ,QADYA;;EAOP,eAAe,UAAU;IAAgB;IAAkB;MAAoB;;;;;EAS/E,qBACJ,UACA,UACA;IAEA;IACA;IACA;MACE,QAAQ;EAON,cACJ,UACA,UACA;IAEA;IACA;IACA;MACD;;;;;EAWK,oBACJ,UACA,eAAe,kBAAkB,eACjC;IAEA;IACA,aAAa;IACb,OAAO,KAAK;MACb"}
@@ -87,11 +87,20 @@ var OAuth2Client = class {
87
87
  async resolveSecret(secret, clientId) {
88
88
  return typeof secret === "function" ? secret(clientId) : secret;
89
89
  }
90
- async createAuthorizationUri({ provider, state, pkce }) {
90
+ /** Which of the provider's flows echo a nonce in the id token (`Provider.nonce`). */
91
+ async nonceSupport(provider) {
92
+ const { nonce } = (await this.getProviderConfig(provider)).provider;
93
+ return {
94
+ web: nonce?.web ?? false,
95
+ native: nonce?.native ?? false
96
+ };
97
+ }
98
+ async createAuthorizationUri({ provider, state, pkce, nonce }) {
91
99
  const { implementation, client } = await this.getWebClient(provider);
92
100
  return implementation.createAuthorizationUri({
93
101
  pkce,
94
102
  state,
103
+ nonce,
95
104
  scope: client.scope,
96
105
  clientId: client.clientId,
97
106
  redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider)
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../../src/oauth2/client.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { object, optional, string } from 'zod/v4-mini';\nimport { OAuth2Error } from './error';\nimport type {\n AuthorizationResponse,\n ClientSecret,\n NativeClient,\n NativeCredential,\n OAuth2ClientConfig,\n OAuth2Token,\n OidcToken,\n OneTapProvider,\n PkceParameters,\n Provider,\n ProviderConfig,\n WebClient,\n} from './types';\n\nexport const oauth2RedirectQuerySchema = object({\n code: optional(string()),\n state: optional(string()),\n error: optional(string()),\n error_description: optional(string()),\n error_uri: optional(string()),\n // Apple's form_post: the user's name as JSON, first authorization only.\n user: optional(string()),\n});\n\nexport const googleOneTapSchema = object({\n // login_uri\n code: optional(string()),\n state: optional(string()),\n error: optional(string()),\n error_description: optional(string()),\n error_uri: optional(string()),\n nonce: optional(string()),\n g_csrf_token: optional(string()),\n hd: optional(string()),\n // callback\n credential: optional(string()),\n});\n\nexport class OAuth2Client {\n private readonly config: OAuth2ClientConfig;\n constructor(config: OAuth2ClientConfig) {\n this.config = config;\n }\n\n get baseUri() {\n return this.config.baseUri;\n }\n\n get successUri() {\n return this.config.successUri;\n }\n\n get errorUri() {\n return this.config.errorUri;\n }\n\n /** The provider key comes from the request path, so an unknown one is the caller's error. */\n private async getProviderConfig(provider: string): Promise<ProviderConfig> {\n const providers =\n typeof this.config.providers === 'function'\n ? await this.config.providers()\n : this.config.providers;\n const config = Object.hasOwn(providers, provider) ? providers[provider] : undefined;\n if (!config) throw new OAuth2Error(400, 'invalid_request', `Unknown provider: ${provider}`);\n return config;\n }\n\n private defaultRedirectUri(provider: string) {\n return `${this.config.baseUri}/login/oauth2/code/${provider}`;\n }\n\n /** The redirect flow and One Tap sign in as the provider's web client. */\n private async getWebClient(provider: string) {\n const config = await this.getProviderConfig(provider);\n if (!config.web) {\n throw new OAuth2Error(400, 'invalid_request', `Provider ${provider} has no web client`);\n }\n return { implementation: config.provider, client: config.web };\n }\n\n /**\n * Any configured client of the provider, looked up by id: refresh and revoke use the client a\n * token was issued to, and the native login the one the app names. The web client counts too:\n * an Android app's server auth code and a Facebook app's tokens are issued to it.\n */\n private async getClient(provider: string, clientId: string) {\n const config = await this.getProviderConfig(provider);\n const client = [config.web, ...(config.native ?? [])].find((c) => c?.clientId === clientId);\n if (!client) {\n throw new OAuth2Error(400, 'invalid_client', `${clientId} is not a client of ${provider}`);\n }\n return { implementation: config.provider, client };\n }\n\n /**\n * The client a native login signs in as: the one the app names with `client_id`, which must be\n * configured; without one, the only native client, or the web client when there is no native\n * one. Several native clients and no `client_id` is ambiguous and refused rather than guessed.\n */\n private async getNativeClient(provider: string, clientId: string | undefined) {\n if (clientId !== undefined) return this.getClient(provider, clientId);\n const config = await this.getProviderConfig(provider);\n const native = config.native ?? [];\n const client: WebClient | NativeClient | undefined =\n native.length === 0 ? config.web : native.length === 1 ? native[0] : undefined;\n if (!client) {\n throw new OAuth2Error(400, 'invalid_request', `client_id is required for ${provider}`);\n }\n return { implementation: config.provider, client };\n }\n\n private async resolveSecret(secret: ClientSecret | undefined, clientId: string) {\n return typeof secret === 'function' ? secret(clientId) : secret;\n }\n\n async createAuthorizationUri({\n provider,\n state,\n pkce,\n }: {\n provider: string;\n state: string;\n pkce?: PkceParameters;\n }): Promise<URL> {\n const { implementation, client } = await this.getWebClient(provider);\n return implementation.createAuthorizationUri({\n pkce,\n state,\n scope: client.scope,\n clientId: client.clientId,\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n });\n }\n\n /** Exchanges a code issued to the provider's web client: the redirect flow and One Tap. */\n async exchangeAuthorizationCode({\n provider,\n code,\n pkce,\n }: {\n provider: string;\n code: string;\n pkce?: PkceParameters;\n }): Promise<{ clientId: string; token: OAuth2Token }> {\n const { implementation, client } = await this.getWebClient(provider);\n const { clientId } = client;\n const token = await implementation.exchangeAuthorizationCode({\n code,\n pkce,\n clientId,\n clientSecret: await this.resolveSecret(client.clientSecret, clientId),\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n });\n return { clientId, token };\n }\n\n /** `clientId` is the client the token was issued to, as `exchangeAuthorizationCode` returns it. */\n async getUserInfo({\n provider,\n clientId,\n token,\n response,\n }: {\n provider: string;\n clientId: string;\n token: OAuth2Token | OidcToken;\n response?: AuthorizationResponse;\n }) {\n const { implementation } = await this.getClient(provider, clientId);\n return implementation.getUserInfo(token, { clientId, response });\n }\n\n /** Verifies a Google One Tap / FedCM credential, which is issued to the web client. */\n async getTokenInfo({ provider, credential }: { provider: string; credential: string }) {\n const { implementation, client } = await this.getWebClient(provider);\n if (!isOneTapProvider(implementation)) {\n throw new OAuth2Error(400, 'invalid_request', `Provider ${provider} has no One Tap`);\n }\n const { clientId } = client;\n return { clientId, ...(await implementation.getTokenInfo(credential, clientId)) };\n }\n\n async refreshAccessToken({\n provider,\n clientId,\n refreshToken,\n }: {\n provider: string;\n clientId: string;\n refreshToken: string;\n }): Promise<OAuth2Token> {\n const { implementation, client } = await this.getClient(provider, clientId);\n invariant(implementation.refreshAccessToken, 'Provider does not support refreshAccessToken');\n const clientSecret = await this.resolveSecret(client.clientSecret, clientId);\n return implementation.refreshAccessToken({ refreshToken, clientId, clientSecret });\n }\n\n async revokeToken({\n provider,\n clientId,\n token,\n }: {\n provider: string;\n clientId: string;\n token: string;\n }) {\n const { implementation, client } = await this.getClient(provider, clientId);\n invariant(implementation.revokeToken, 'Provider does not support revokeToken');\n const clientSecret = await this.resolveSecret(client.clientSecret, clientId);\n await implementation.revokeToken({ token, clientId, clientSecret });\n }\n\n /**\n * Signs in with what a native app posted. `credentials.code_verifier`, when present, is the PKCE\n * verifier for the code exchange and reaches the provider as `pkce`, not in `credentials`.\n */\n async loginOAuth2Native({\n provider,\n credentials: { code_verifier, ...credentials },\n pkce = code_verifier === undefined ? undefined : { code_verifier },\n }: {\n provider: string;\n credentials: NativeCredential;\n pkce?: Omit<PkceParameters, 'code_challenge' | 'code_challenge_method'>;\n }) {\n const { implementation, client } = await this.getNativeClient(provider, credentials.client_id);\n invariant(implementation.loginOAuth2Native, 'Provider does not support loginOAuth2Native');\n const { clientId } = client;\n\n const result = await implementation.loginOAuth2Native({\n clientId,\n clientSecret: await this.resolveSecret(client.clientSecret, clientId),\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n credentials,\n pkce,\n });\n return { clientId, ...result };\n }\n}\n\nfunction isOneTapProvider(provider: Provider): provider is OneTapProvider {\n return typeof (provider as Partial<OneTapProvider>).getTokenInfo === 'function';\n}\n"],"mappings":";;;;AAkBA,MAAa,4BAA4B,OAAO;CAC9C,MAAM,SAAS,OAAO,CAAC;CACvB,OAAO,SAAS,OAAO,CAAC;CACxB,OAAO,SAAS,OAAO,CAAC;CACxB,mBAAmB,SAAS,OAAO,CAAC;CACpC,WAAW,SAAS,OAAO,CAAC;CAE5B,MAAM,SAAS,OAAO,CAAC;AACzB,CAAC;AAED,MAAa,qBAAqB,OAAO;CAEvC,MAAM,SAAS,OAAO,CAAC;CACvB,OAAO,SAAS,OAAO,CAAC;CACxB,OAAO,SAAS,OAAO,CAAC;CACxB,mBAAmB,SAAS,OAAO,CAAC;CACpC,WAAW,SAAS,OAAO,CAAC;CAC5B,OAAO,SAAS,OAAO,CAAC;CACxB,cAAc,SAAS,OAAO,CAAC;CAC/B,IAAI,SAAS,OAAO,CAAC;CAErB,YAAY,SAAS,OAAO,CAAC;AAC/B,CAAC;AAED,IAAa,eAAb,MAA0B;CACxB;CACA,YAAY,QAA4B;EACtC,KAAK,SAAS;CAChB;CAEA,IAAI,UAAU;EACZ,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,aAAa;EACf,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO;CACrB;;CAGA,MAAc,kBAAkB,UAA2C;EACzE,MAAM,YACJ,OAAO,KAAK,OAAO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EAC3F,MAAM,eAAe,MAAM,KAAK,cAAc,OAAO,cAAc,QAAQ;EAC3E,OAAO,eAAe,mBAAmB;GAAE;GAAc;GAAU;EAAa,CAAC;CACnF;CAEA,MAAM,YAAY,EAChB,UACA,UACA,SAKC;EACD,MAAM,EAAE,gBAAgB,WAAW,MAAM,KAAK,UAAU,UAAU,QAAQ;EAC1E,UAAU,eAAe,aAAa,uCAAuC;EAC7E,MAAM,eAAe,MAAM,KAAK,cAAc,OAAO,cAAc,QAAQ;EAC3E,MAAM,eAAe,YAAY;GAAE;GAAO;GAAU;EAAa,CAAC;CACpE;;;;;CAMA,MAAM,kBAAkB,EACtB,UACA,aAAa,EAAE,eAAe,GAAG,eACjC,OAAO,kBAAkB,KAAA,IAAY,KAAA,IAAY,EAAE,cAAc,KAKhE;EACD,MAAM,EAAE,gBAAgB,WAAW,MAAM,KAAK,gBAAgB,UAAU,YAAY,SAAS;EAC7F,UAAU,eAAe,mBAAmB,6CAA6C;EACzF,MAAM,EAAE,aAAa;EASrB,OAAO;GAAE;GAAU,GAAG,MAPD,eAAe,kBAAkB;IACpD;IACA,cAAc,MAAM,KAAK,cAAc,OAAO,cAAc,QAAQ;IACpE,aAAa,OAAO,eAAe,KAAK,mBAAmB,QAAQ;IACnE;IACA;GACF,CAAC;EAC4B;CAC/B;AACF;AAEA,SAAS,iBAAiB,UAAgD;CACxE,OAAO,OAAQ,SAAqC,iBAAiB;AACvE"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../../src/oauth2/client.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { object, optional, string } from 'zod/v4-mini';\nimport { OAuth2Error } from './error';\nimport type {\n AuthorizationResponse,\n ClientSecret,\n NativeClient,\n NativeCredential,\n OAuth2ClientConfig,\n OAuth2Token,\n OidcToken,\n OneTapProvider,\n PkceParameters,\n Provider,\n ProviderConfig,\n WebClient,\n} from './types';\n\nexport const oauth2RedirectQuerySchema = object({\n code: optional(string()),\n state: optional(string()),\n error: optional(string()),\n error_description: optional(string()),\n error_uri: optional(string()),\n // Apple's form_post: the user's name as JSON, first authorization only.\n user: optional(string()),\n});\n\nexport const googleOneTapSchema = object({\n // login_uri\n code: optional(string()),\n state: optional(string()),\n error: optional(string()),\n error_description: optional(string()),\n error_uri: optional(string()),\n nonce: optional(string()),\n g_csrf_token: optional(string()),\n hd: optional(string()),\n // callback\n credential: optional(string()),\n});\n\nexport class OAuth2Client {\n private readonly config: OAuth2ClientConfig;\n constructor(config: OAuth2ClientConfig) {\n this.config = config;\n }\n\n get baseUri() {\n return this.config.baseUri;\n }\n\n get successUri() {\n return this.config.successUri;\n }\n\n get errorUri() {\n return this.config.errorUri;\n }\n\n /** The provider key comes from the request path, so an unknown one is the caller's error. */\n private async getProviderConfig(provider: string): Promise<ProviderConfig> {\n const providers =\n typeof this.config.providers === 'function'\n ? await this.config.providers()\n : this.config.providers;\n const config = Object.hasOwn(providers, provider) ? providers[provider] : undefined;\n if (!config) throw new OAuth2Error(400, 'invalid_request', `Unknown provider: ${provider}`);\n return config;\n }\n\n private defaultRedirectUri(provider: string) {\n return `${this.config.baseUri}/login/oauth2/code/${provider}`;\n }\n\n /** The redirect flow and One Tap sign in as the provider's web client. */\n private async getWebClient(provider: string) {\n const config = await this.getProviderConfig(provider);\n if (!config.web) {\n throw new OAuth2Error(400, 'invalid_request', `Provider ${provider} has no web client`);\n }\n return { implementation: config.provider, client: config.web };\n }\n\n /**\n * Any configured client of the provider, looked up by id: refresh and revoke use the client a\n * token was issued to, and the native login the one the app names. The web client counts too:\n * an Android app's server auth code and a Facebook app's tokens are issued to it.\n */\n private async getClient(provider: string, clientId: string) {\n const config = await this.getProviderConfig(provider);\n const client = [config.web, ...(config.native ?? [])].find((c) => c?.clientId === clientId);\n if (!client) {\n throw new OAuth2Error(400, 'invalid_client', `${clientId} is not a client of ${provider}`);\n }\n return { implementation: config.provider, client };\n }\n\n /**\n * The client a native login signs in as: the one the app names with `client_id`, which must be\n * configured; without one, the only native client, or the web client when there is no native\n * one. Several native clients and no `client_id` is ambiguous and refused rather than guessed.\n */\n private async getNativeClient(provider: string, clientId: string | undefined) {\n if (clientId !== undefined) return this.getClient(provider, clientId);\n const config = await this.getProviderConfig(provider);\n const native = config.native ?? [];\n const client: WebClient | NativeClient | undefined =\n native.length === 0 ? config.web : native.length === 1 ? native[0] : undefined;\n if (!client) {\n throw new OAuth2Error(400, 'invalid_request', `client_id is required for ${provider}`);\n }\n return { implementation: config.provider, client };\n }\n\n private async resolveSecret(secret: ClientSecret | undefined, clientId: string) {\n return typeof secret === 'function' ? secret(clientId) : secret;\n }\n\n /** Which of the provider's flows echo a nonce in the id token (`Provider.nonce`). */\n async nonceSupport(provider: string): Promise<{ web: boolean; native: boolean }> {\n const { nonce } = (await this.getProviderConfig(provider)).provider;\n return { web: nonce?.web ?? false, native: nonce?.native ?? false };\n }\n\n async createAuthorizationUri({\n provider,\n state,\n pkce,\n nonce,\n }: {\n provider: string;\n state: string;\n pkce?: PkceParameters;\n nonce?: string;\n }): Promise<URL> {\n const { implementation, client } = await this.getWebClient(provider);\n return implementation.createAuthorizationUri({\n pkce,\n state,\n nonce,\n scope: client.scope,\n clientId: client.clientId,\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n });\n }\n\n /** Exchanges a code issued to the provider's web client: the redirect flow and One Tap. */\n async exchangeAuthorizationCode({\n provider,\n code,\n pkce,\n }: {\n provider: string;\n code: string;\n pkce?: PkceParameters;\n }): Promise<{ clientId: string; token: OAuth2Token }> {\n const { implementation, client } = await this.getWebClient(provider);\n const { clientId } = client;\n const token = await implementation.exchangeAuthorizationCode({\n code,\n pkce,\n clientId,\n clientSecret: await this.resolveSecret(client.clientSecret, clientId),\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n });\n return { clientId, token };\n }\n\n /** `clientId` is the client the token was issued to, as `exchangeAuthorizationCode` returns it. */\n async getUserInfo({\n provider,\n clientId,\n token,\n response,\n }: {\n provider: string;\n clientId: string;\n token: OAuth2Token | OidcToken;\n response?: AuthorizationResponse;\n }) {\n const { implementation } = await this.getClient(provider, clientId);\n return implementation.getUserInfo(token, { clientId, response });\n }\n\n /** Verifies a Google One Tap / FedCM credential, which is issued to the web client. */\n async getTokenInfo({ provider, credential }: { provider: string; credential: string }) {\n const { implementation, client } = await this.getWebClient(provider);\n if (!isOneTapProvider(implementation)) {\n throw new OAuth2Error(400, 'invalid_request', `Provider ${provider} has no One Tap`);\n }\n const { clientId } = client;\n return { clientId, ...(await implementation.getTokenInfo(credential, clientId)) };\n }\n\n async refreshAccessToken({\n provider,\n clientId,\n refreshToken,\n }: {\n provider: string;\n clientId: string;\n refreshToken: string;\n }): Promise<OAuth2Token> {\n const { implementation, client } = await this.getClient(provider, clientId);\n invariant(implementation.refreshAccessToken, 'Provider does not support refreshAccessToken');\n const clientSecret = await this.resolveSecret(client.clientSecret, clientId);\n return implementation.refreshAccessToken({ refreshToken, clientId, clientSecret });\n }\n\n async revokeToken({\n provider,\n clientId,\n token,\n }: {\n provider: string;\n clientId: string;\n token: string;\n }) {\n const { implementation, client } = await this.getClient(provider, clientId);\n invariant(implementation.revokeToken, 'Provider does not support revokeToken');\n const clientSecret = await this.resolveSecret(client.clientSecret, clientId);\n await implementation.revokeToken({ token, clientId, clientSecret });\n }\n\n /**\n * Signs in with what a native app posted. `credentials.code_verifier`, when present, is the PKCE\n * verifier for the code exchange and reaches the provider as `pkce`, not in `credentials`.\n */\n async loginOAuth2Native({\n provider,\n credentials: { code_verifier, ...credentials },\n pkce = code_verifier === undefined ? undefined : { code_verifier },\n }: {\n provider: string;\n credentials: NativeCredential;\n pkce?: Omit<PkceParameters, 'code_challenge' | 'code_challenge_method'>;\n }) {\n const { implementation, client } = await this.getNativeClient(provider, credentials.client_id);\n invariant(implementation.loginOAuth2Native, 'Provider does not support loginOAuth2Native');\n const { clientId } = client;\n\n const result = await implementation.loginOAuth2Native({\n clientId,\n clientSecret: await this.resolveSecret(client.clientSecret, clientId),\n redirectUri: client.redirectUri ?? this.defaultRedirectUri(provider),\n credentials,\n pkce,\n });\n return { clientId, ...result };\n }\n}\n\nfunction isOneTapProvider(provider: Provider): provider is OneTapProvider {\n return typeof (provider as Partial<OneTapProvider>).getTokenInfo === 'function';\n}\n"],"mappings":";;;;AAkBA,MAAa,4BAA4B,OAAO;CAC9C,MAAM,SAAS,OAAO,CAAC;CACvB,OAAO,SAAS,OAAO,CAAC;CACxB,OAAO,SAAS,OAAO,CAAC;CACxB,mBAAmB,SAAS,OAAO,CAAC;CACpC,WAAW,SAAS,OAAO,CAAC;CAE5B,MAAM,SAAS,OAAO,CAAC;AACzB,CAAC;AAED,MAAa,qBAAqB,OAAO;CAEvC,MAAM,SAAS,OAAO,CAAC;CACvB,OAAO,SAAS,OAAO,CAAC;CACxB,OAAO,SAAS,OAAO,CAAC;CACxB,mBAAmB,SAAS,OAAO,CAAC;CACpC,WAAW,SAAS,OAAO,CAAC;CAC5B,OAAO,SAAS,OAAO,CAAC;CACxB,cAAc,SAAS,OAAO,CAAC;CAC/B,IAAI,SAAS,OAAO,CAAC;CAErB,YAAY,SAAS,OAAO,CAAC;AAC/B,CAAC;AAED,IAAa,eAAb,MAA0B;CACxB;CACA,YAAY,QAA4B;EACtC,KAAK,SAAS;CAChB;CAEA,IAAI,UAAU;EACZ,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,aAAa;EACf,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO;CACrB;;CAGA,MAAc,kBAAkB,UAA2C;EACzE,MAAM,YACJ,OAAO,KAAK,OAAO,cAAc,aAC7B,MAAM,KAAK,OAAO,UAAU,IAC5B,KAAK,OAAO;EAClB,MAAM,SAAS,OAAO,OAAO,WAAW,QAAQ,IAAI,UAAU,YAAY,KAAA;EAC1E,IAAI,CAAC,QAAQ,MAAM,IAAI,YAAY,KAAK,mBAAmB,qBAAqB,UAAU;EAC1F,OAAO;CACT;CAEA,mBAA2B,UAAkB;EAC3C,OA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Ae,mBAAmB;GAAE;GAAc;GAAU;EAAa,CAAC;CACnF;CAEA,MAAM,YAAY,EAChB,UACA,UACA,SAKC;EACD,MAAM,EAAE,gBAAgB,WAAW,MAAM,KAAK,UAAU,UAAU,QAAQ;EAC1E,UAAU,eAAe,aAAa,uCAAuC;EAC7E,MAAM,eAAe,MAAM,KAAK,cAAc,OAAO,cAAc,QAAQ;EAC3E,MAAM,eAAe,YAAY;GAAE;GAAO;GAAU;EAAa,CAAC;CACpE;;;;;CAMA,MAAM,kBAAkB,EACtB,UACA,aAAa,EAAE,eAAe,GAAG,eACjC,OAAO,kBAAkB,KAAA,IAAY,KAAA,IAAY,EAAE,cAAc,KAKhE;EACD,MAAM,EAAE,gBAAgB,WAAW,MAAM,KAAK,gBAAgB,UAAU,YAAY,SAAS;EAC7F,UAAU,eAAe,mBAAmB,6CAA6C;EACzF,MAAM,EAAE,aAAa;EASrB,OAAO;GAAE;GAAU,GAAG,MAPD,eAAe,kBAAkB;IACpD;IACA,cAAc,MAAM,KAAK,cAAc,OAAO,cAAc,QAAQ;IACpE,aAAa,OAAO,eAAe,KAAK,mBAAmB,QAAQ;IACnE;IACA;GACF,CAAC;EAC4B;CAC/B;AACF;AAEA,SAAS,iBAAiB,UAAgD;CACxE,OAAO,OAAQ,SAAqC,iBAAiB;AACvE"}
@@ -17,6 +17,10 @@ function createAppleProvider() {
17
17
  "name",
18
18
  "email"
19
19
  ],
20
+ nonce: {
21
+ web: true,
22
+ native: true
23
+ },
20
24
  createAuthorizationUri({ pkce: _, ...params }) {
21
25
  return require_oauth2_provider_common.createAuthorizationUri({
22
26
  ...params,
@@ -1 +1 @@
1
- {"version":3,"file":"apple.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken","parseAppleUser","nameClaims","cleanPersonName"],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { tokenUri } = this;\n const { code } = credentials;\n const response = await exchangeAuthorizationCode({ code, tokenUri, ...params });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n const token = (await response.json()) as AppleToken;\n const { data, claims } = await this.getUserInfo(token, { clientId: params.clientId });\n // The app gets the name from Apple on the first authorization only and passes it along in\n // the login body as the platform's `fullName`.\n const fullName = cleanPersonName(credentials.fullName);\n const name = nameClaims({\n given_name: fullName?.givenName ?? undefined,\n family_name: fullName?.familyName ?? undefined,\n middle_name: fullName?.middleName ?? undefined,\n nickname: fullName?.nickname ?? undefined,\n });\n const userInfo: UserInfo<AppleUserInfo> = {\n data: fullName ? { ...(data as AppleUserInfo), fullName } : (data as AppleUserInfo),\n claims: { ...claims, ...name },\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const apple = createAppleProvider();\n\n// Claims of Apple's id token. It carries no name or picture, not even on the first authorization.\n// https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\nexport interface AppleIdToken {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n sub: string;\n email: string;\n email_verified: true | 'true';\n is_private_email: boolean;\n /** Native flow, first authorization only: 0 unsupported, 1 unknown, 2 likely real. */\n real_user_status?: number;\n nonce?: string;\n nonce_supported?: boolean;\n}\n\n/**\n * `userInfo.data` of an Apple login: the id token's claims, plus the unsigned name the client\n * passed on the first authorization, cleaned (see `nameClaims` for the standard claims made of it).\n */\nexport interface AppleUserInfo extends AppleIdToken {\n /** Web flow: Apple's form_post `user`, as Apple names it. */\n user?: AppleUser;\n /** Native flow: the login body's `fullName`, which alone keeps `namePrefix` / `nameSuffix`. */\n fullName?: PersonNameComponents;\n}\n\n// https://developer.apple.com/documentation/devicemanagement/implementing-the-oauth2-authentication-user-enrollment-flow\n// https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens\nexport interface AppleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n}\n\nexport interface AppleNativeCredential extends NativeCredential {\n state: string;\n code: string;\n id_token: string;\n}\n\n// https://developer.apple.com/documentation/sign_in_with_apple/errorresponse\nexport interface AppleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'invalid_scope';\n}\n"],"mappings":";;;;;;;AAcA,MAAM,eAAe;AAGrB,SAAgB,sBAAgC;CAC9C,OAAO;EAEL,kBAAkB;EAClB,UAAU;EACV,WAAW;EACX,mBAAmB;EACnB,cAAc;GAAC;GAAU;GAAQ;EAAO;EACxC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAOA,+BAAAA,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAMC,+BAAAA,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,KAAK;GAC9C;GACA,OAAQ,MAAM,SAAS,KAAK;EAC9B;EACA,MAAM,YAAY,EAAE,YAAY,EAAE,UAAU,YAAY;GACtD,CAAA,GAAA,cAAA,UAAA,CAAU,UAAU,sBAAsB;GAC1C,CAAA,GAAA,cAAA,UAAA,CAAU,KAAK,WAAW,uBAAuB;GAGjD,MAAM,QAAQ,MAAMC,+BAAAA,cAA4B,UAAU;IACxD,WAAW,KAAK;IAChB,QAAQ;IACR,UAAU;GACZ,CAAC;GAID,MAAM,OAAOC,oBAA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ims","cleanPersonName"],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n // The web flow's id token echoes the request's nonce; the app's carries the one bound into\n // ASAuthorizationAppleIDRequest, hashed or not (`nonce_supported`).\n nonce: { web: true, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { tokenUri } = this;\n const { code } = credentials;\n const response = await exchangeAuthorizationCode({ code, tokenUri, ...params });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n const token = (await response.json()) as AppleToken;\n const { data, claims } = await this.getUserInfo(token, { clientId: params.clientId });\n // The app gets the name from Apple on the first authorization only and passes it along in\n // the login body as the platform's `fullName`.\n const fullName = cleanPersonName(credentials.fullName);\n const name = nameClaims({\n given_name: fullName?.givenName ?? undefined,\n family_name: fullName?.familyName ?? undefined,\n middle_name: fullName?.middleName ?? undefined,\n nickname: fullName?.nickname ?? undefined,\n });\n const userInfo: UserInfo<AppleUserInfo> = {\n data: fullName ? { ...(data as AppleUserInfo), fullName } : (data as AppleUserInfo),\n claims: { ...claims, ...name },\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const apple = createAppleProvider();\n\n// Claims of Apple's id token. It carries no name or picture, not even on the first authorization.\n// https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\nexport interface AppleIdToken {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n sub: string;\n email: string;\n email_verified: true | 'true';\n is_private_email: boolean;\n /** Native flow, first authorization only: 0 unsupported, 1 unknown, 2 likely real. */\n real_user_status?: number;\n nonce?: string;\n nonce_supported?: boolean;\n}\n\n/**\n * `userInfo.data` of an Apple login: the id token's claims, plus the unsigned name the client\n * passed on the first authorization, cleaned (see `nameClaims` for the standard claims made of it).\n */\nexport interface AppleUserInfo extends AppleIdToken {\n /** Web flow: Apple's form_post `user`, as Apple names it. */\n user?: AppleUser;\n /** Native flow: the login body's `fullName`, which alone keeps `namePrefix` / `nameSuffix`. */\n fullName?: PersonNameComponents;\n}\n\n// https://developer.apple.com/documentation/devicemanagement/implementing-the-oauth2-authentication-user-enrollment-flow\n// https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens\nexport interface AppleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n}\n\nexport interface AppleNativeCredential extends NativeCredential {\n state: string;\n code: string;\n id_token: string;\n}\n\n// https://developer.apple.com/documentation/sign_in_with_apple/errorresponse\nexport interface AppleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'invalid_scope';\n}\n"],"mappings":";;;;;;;AAcA,MAAM,eAAe;AAGrB,SAAgB,sBAAgC;CAC9C,OAAO;EAEL,kBAAkB;EAClB,UAAU;EACV,WAAW;EACX,mBAAmB;EACnB,cAAc;GAAC;GAAU;GAAQ;EAAO;EAGxC,OAAO;GAAE,KAAK;GAAM,QAAQ;EAAK;EACjC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAOA,+BAAAA,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAMC,+BAAAA,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,KAAK;GAC9C;GACA,OAAQ,MAAM,SAAS,KAAK;EAC9B;EACA,MAAM,YAAY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AAO;IAAE;IAAO,UAAA;KAHd,MAAM,WAAW;MAAE,GAAI;MAAwB;KAAS,IAAK;KAC7D,QAAQ;MAAE,GAAG;MAAQ,GAAG;KAAK;IAER;GAAE;EAC3B;CACF;AACF;AAEA,MAAa,QAAQ,oBAAoB"}
@@ -1 +1 @@
1
- {"version":3,"file":"apple.d.cts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAgF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
1
+ {"version":3,"file":"apple.d.cts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAmF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
@@ -1 +1 @@
1
- {"version":3,"file":"apple.d.mts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAgF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
1
+ {"version":3,"file":"apple.d.mts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAmF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
@@ -16,6 +16,10 @@ function createAppleProvider() {
16
16
  "name",
17
17
  "email"
18
18
  ],
19
+ nonce: {
20
+ web: true,
21
+ native: true
22
+ },
19
23
  createAuthorizationUri({ pkce: _, ...params }) {
20
24
  return createAuthorizationUri({
21
25
  ...params,
@@ -1 +1 @@
1
- {"version":3,"file":"apple.mjs","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { tokenUri } = this;\n const { code } = credentials;\n const response = await exchangeAuthorizationCode({ code, tokenUri, ...params });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n const token = (await response.json()) as AppleToken;\n const { data, claims } = await this.getUserInfo(token, { clientId: params.clientId });\n // The app gets the name from Apple on the first authorization only and passes it along in\n // the login body as the platform's `fullName`.\n const fullName = cleanPersonName(credentials.fullName);\n const name = nameClaims({\n given_name: fullName?.givenName ?? undefined,\n family_name: fullName?.familyName ?? undefined,\n middle_name: fullName?.middleName ?? undefined,\n nickname: fullName?.nickname ?? undefined,\n });\n const userInfo: UserInfo<AppleUserInfo> = {\n data: fullName ? { ...(data as AppleUserInfo), fullName } : (data as AppleUserInfo),\n claims: { ...claims, ...name },\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const apple = createAppleProvider();\n\n// Claims of Apple's id token. It carries no name or picture, not even on the first authorization.\n// https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\nexport interface AppleIdToken {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n sub: string;\n email: string;\n email_verified: true | 'true';\n is_private_email: boolean;\n /** Native flow, first authorization only: 0 unsupported, 1 unknown, 2 likely real. */\n real_user_status?: number;\n nonce?: string;\n nonce_supported?: boolean;\n}\n\n/**\n * `userInfo.data` of an Apple login: the id token's claims, plus the unsigned name the client\n * passed on the first authorization, cleaned (see `nameClaims` for the standard claims made of it).\n */\nexport interface AppleUserInfo extends AppleIdToken {\n /** Web flow: Apple's form_post `user`, as Apple names it. */\n user?: AppleUser;\n /** Native flow: the login body's `fullName`, which alone keeps `namePrefix` / `nameSuffix`. */\n fullName?: PersonNameComponents;\n}\n\n// https://developer.apple.com/documentation/devicemanagement/implementing-the-oauth2-authentication-user-enrollment-flow\n// https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens\nexport interface AppleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n}\n\nexport interface AppleNativeCredential extends NativeCredential {\n state: string;\n code: string;\n id_token: string;\n}\n\n// https://developer.apple.com/documentation/sign_in_with_apple/errorresponse\nexport interface AppleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'invalid_scope';\n}\n"],"mappings":";;;;;;AAcA,MAAM,eAAe;AAGrB,SAAgB,sBAAgC;CAC9C,OAAO;EAEL,kBAAkB;EAClB,UAAU;EACV,WAAW;EACX,mBAAmB;EACnB,cAAc;GAAC;GAAU;GAAQ;EAAO;EACxC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAO,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAM,0BAA0B;I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rC,aAAa,UAAU,cAAc,KAAA;IACrC,UAAU,UAAU,YAAY,KAAA;GAClC,CAAC;GAKD,OAAO;IAAE;IAAO,UAAA;KAHd,MAAM,WAAW;MAAE,GAAI;MAAwB;KAAS,IAAK;KAC7D,QAAQ;MAAE,GAAG;MAAQ,GAAG;KAAK;IAER;GAAE;EAC3B;CACF;AACF;AAEA,MAAa,QAAQ,oBAAoB"}
1
+ {"version":3,"file":"apple.mjs","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n // The web flow's id token echoes the request's nonce; the app's carries the one bound into\n // ASAuthorizationAppleIDRequest, hashed or not (`nonce_supported`).\n nonce: { web: true, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { tokenUri } = this;\n const { code } = credentials;\n const response = await exchangeAuthorizationCode({ code, tokenUri, ...params });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n const token = (await response.json()) as AppleToken;\n const { data, claims } = await this.getUserInfo(token, { clientId: params.clientId });\n // The app gets the name from Apple on the first authorization only and passes it along in\n // the login body as the platform's `fullName`.\n const fullName = cleanPersonName(credentials.fullName);\n const name = nameClaims({\n given_name: fullName?.givenName ?? undefined,\n family_name: fullName?.familyName ?? undefined,\n middle_name: fullName?.middleName ?? undefined,\n nickname: fullName?.nickname ?? undefined,\n });\n const userInfo: UserInfo<AppleUserInfo> = {\n data: fullName ? { ...(data as AppleUserInfo), fullName } : (data as AppleUserInfo),\n claims: { ...claims, ...name },\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const apple = createAppleProvider();\n\n// Claims of Apple's id token. It carries no name or picture, not even on the first authorization.\n// https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\nexport interface AppleIdToken {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n sub: string;\n email: string;\n email_verified: true | 'true';\n is_private_email: boolean;\n /** Native flow, first authorization only: 0 unsupported, 1 unknown, 2 likely real. */\n real_user_status?: number;\n nonce?: string;\n nonce_supported?: boolean;\n}\n\n/**\n * `userInfo.data` of an Apple login: the id token's claims, plus the unsigned name the client\n * passed on the first authorization, cleaned (see `nameClaims` for the standard claims made of it).\n */\nexport interface AppleUserInfo extends AppleIdToken {\n /** Web flow: Apple's form_post `user`, as Apple names it. */\n user?: AppleUser;\n /** Native flow: the login body's `fullName`, which alone keeps `namePrefix` / `nameSuffix`. */\n fullName?: PersonNameComponents;\n}\n\n// https://developer.apple.com/documentation/devicemanagement/implementing-the-oauth2-authentication-user-enrollment-flow\n// https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens\nexport interface AppleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n}\n\nexport interface AppleNativeCredential extends NativeCredential {\n state: string;\n code: string;\n id_token: string;\n}\n\n// https://developer.apple.com/documentation/sign_in_with_apple/errorresponse\nexport interface AppleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'invalid_scope';\n}\n"],"mappings":";;;;;;AAcA,MAAM,eAAe;AAGrB,SAAgB,sBAAgC;CAC9C,OAAO;EAEL,kBAAkB;EAClB,UAAU;EACV,WAAW;EACX,mBAAmB;EACnB,cAAc;GAAC;GAAU;GAAQ;EAAO;EAGxC,OAAO;GAAE,KAAK;GAAM,QAAQ;EAAK;EACjC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAO,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,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,UAAU,cAAc,KAAA;IACrC,aAAa,UAAU,cAAc,KAAA;IACrC,UAAU,UAAU,YAAY,KAAA;GAClC,CAAC;GAKD,OAAO;IAAE;IAAO,UAAA;KAHd,MAAM,WAAW;MAAE,GAAI;MAAwB;KAAS,IAAK;KAC7D,QAAQ;MAAE,GAAG;MAAQ,GAAG;KAAK;IAER;GAAE;EAC3B;CACF;AACF;AAEA,MAAa,QAAQ,oBAAoB"}
@@ -7,6 +7,7 @@ function createAuthorizationUri(options) {
7
7
  url.searchParams.append("response_type", "code");
8
8
  url.searchParams.append("client_id", options.clientId);
9
9
  url.searchParams.append("state", options.state);
10
+ if (options.nonce) url.searchParams.append("nonce", options.nonce);
10
11
  url.searchParams.append("scope", options.scope.join(" "));
11
12
  url.searchParams.append("redirect_uri", options.redirectUri);
12
13
  if (options.pkce) {
@@ -1 +1 @@
1
- {"version":3,"file":"common.cjs","names":["OAuth2Error","createRemoteJWKSet","jwtVerify"],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n /** Extra request headers some providers require, e.g. GitHub's `User-Agent`. */\n headers?: Record<string, string>;\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n ...params.headers,\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n // Public clients (Google's installed-app clients, PKCE-only clients) have no secret.\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret?: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Revoke token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport interface VerifyIdTokenOptions {\n jwkSetUri: string;\n /** The `iss` values the provider signs with; anything else is refused. */\n issuer: string | string[];\n /**\n * The client the token must be issued to. An id token proves who the user is only to the client\n * it names in `aud`: any other app on the same identity provider can obtain a validly signed one\n * for the same user, so a token for a foreign client must never sign anyone in here.\n */\n audience: string;\n}\n\n/**\n * One key set per JWKS endpoint for the life of the process: jose caches the fetched keys,\n * refetches on an unknown `kid` (with a cooldown) and when they go stale, so a set created per\n * call would refetch the keys for every id token.\n */\nconst jwkSets = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\nfunction remoteJWKSet(jwkSetUri: string) {\n let jwks = jwkSets.get(jwkSetUri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(jwkSetUri));\n jwkSets.set(jwkSetUri, jwks);\n }\n return jwks;\n}\n\nexport async function verifyIdToken<T>(idToken: string, options: VerifyIdTokenOptions) {\n const { jwkSetUri, issuer, audience } = options;\n try {\n const jwks = remoteJWKSet(jwkSetUri);\n const { payload } = await jwtVerify(idToken, jwks, { issuer, audience });\n return payload as T;\n } catch (error) {\n console.error('Failed to verify id_token', error);\n // The token is the grant here: one for another audience or issuer is an invalid grant, not a\n // malformed request.\n throw new OAuth2Error(400, 'invalid_grant', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,uBAAuB,SAOpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACx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B,KAAK;EAGhD,MAAM,IAAIF,qBAAAA,YAAY,KAAK,iBAAiB,2BAA2B;CACzE;AACF"}
1
+ {"version":3,"file":"common.cjs","names":["OAuth2Error","createRemoteJWKSet","jwtVerify"],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n nonce?: string;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n if (options.nonce) url.searchParams.append('nonce', options.nonce);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n /** Extra request headers some providers require, e.g. GitHub's `User-Agent`. */\n headers?: Record<string, string>;\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n ...params.headers,\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n // Public clients (Google's installed-app clients, PKCE-only clients) have no secret.\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret?: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Revoke token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport interface VerifyIdTokenOptions {\n jwkSetUri: string;\n /** The `iss` values the provider signs with; anything else is refused. */\n issuer: string | string[];\n /**\n * The client the token must be issued to. An id token proves who the user is only to the client\n * it names in `aud`: any other app on the same identity provider can obtain a validly signed one\n * for the same user, so a token for a foreign client must never sign anyone in here.\n */\n audience: string;\n}\n\n/**\n * One key set per JWKS endpoint for the life of the process: jose caches the fetched keys,\n * refetches on an unknown `kid` (with a cooldown) and when they go stale, so a set created per\n * call would refetch the keys for every id token.\n */\nconst jwkSets = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\nfunction remoteJWKSet(jwkSetUri: string) {\n let jwks = jwkSets.get(jwkSetUri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(jwkSetUri));\n jwkSets.set(jwkSetUri, jwks);\n }\n return jwks;\n}\n\nexport async function verifyIdToken<T>(idToken: string, options: VerifyIdTokenOptions) {\n const { jwkSetUri, issuer, audience } = options;\n try {\n const jwks = remoteJWKSet(jwkSetUri);\n const { payload } = await jwtVerify(idToken, jwks, { issuer, audience });\n return payload as T;\n } catch (error) {\n console.error('Failed to verify id_token', error);\n // The token is the grant here: one for another audience or issuer is an invalid grant, not a\n // malformed request.\n throw new OAuth2Error(400, 'invalid_grant', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,uBAAuB,SAQpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,QAAQ,OAAO,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CACjE,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACxD,IAAI,aAAa,OAAO,gBAAgB,QAAQ,WAAW;CAC3D,IAAI,QAAQ,MAAM;EAChB,IAAI,aAAa,OAAO,yBAAyB,QAAQ,KAAK,qBAAqB;EACnF,IAAI,aAAa,OAAO,kBAAkB,QAAQ,KAAK,cAAc;CACvE;CACA,OAAO;AACT;AAEA,eAAsB,0BACpB,QAMA;CACA,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,QAAQ,OAAO,IAAI;CAC/B,KAAK,OAAO,gBAAgB,OAAO,WAAW;CAC9C,KAAK,O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SAAS,QACjD;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,IAAI,OAAO,cAAc,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAC3E;CAEA,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;CACrF,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,QAAQ,MAAM,SAAS,KAAK;EAClC,QAAQ,MAAM,uBAAuB,KAAK;EAC1C,MAAM,IAAIA,qBAAAA,YAAY,SAAS,QAAQ,mBAAmB,wBAAwB;CACpF;AACF;;;;;;AAmBA,MAAM,0BAAU,IAAI,IAAmD;AAEvE,SAAS,aAAa,WAAmB;CACvC,IAAI,OAAO,QAAQ,IAAI,SAAS;CAChC,IAAI,CAAC,MAAM;EACT,QAAA,GAAOC,KAAAA,mBAAAA,CAAmB,IAAI,IAAI,SAAS,CAAC;EAC5C,QAAQ,IAAI,WAAW,IAAI;CAC7B;CACA,OAAO;AACT;AAEA,eAAsB,cAAiB,SAAiB,SAA+B;CACrF,MAAM,EAAE,WAAW,QAAQ,aAAa;CACxC,IAAI;EACF,MAAM,OAAO,aAAa,SAAS;EACnC,MAAM,EAAE,YAAY,OAAA,GAAMC,KAAAA,UAAAA,CAAU,SAAS,MAAM;GAAE;GAAQ;EAAS,CAAC;EACvE,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,MAAM,6BAA6B,KAAK;EAGhD,MAAM,IAAIF,qBAAAA,YAAY,KAAK,iBAAiB,2BAA2B;CACzE;AACF"}
@@ -6,6 +6,7 @@ export declare function createAuthorizationUri(options: {
6
6
  redirectUri: string;
7
7
  authorizationUri: string;
8
8
  pkce?: Omit<PkceParameters, 'code_verifier'>;
9
+ nonce?: string;
9
10
  }): URL;
10
11
  export declare function exchangeAuthorizationCode(params: ExchangeCodeParams & {
11
12
  tokenUri: string;
@@ -1 +1 @@
1
- {"version":3,"file":"common.d.cts","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"mappings":";wBAIgB,uBAAuB;EACrC;EACA;EACA;EACA;EACA;EACA,OAAO,KAAK;IACb;wBAcqB,0BACpB,QAAQ;EACN;EACA;;EAEA,UAAU;IACX,QAAA;wBAyBmB,mBACpB,QAAQ;EACN;EACA;IACD,QAAA;UAsBO;EACR;EACA;EACA;EACA;EACA;;wBAGoB,YAAY,QAAQ,oBAAiB;iBAwB1C;EACf;;EAEA;;;;;;EAMA;;wBAmBoB,cAAc,GAAG,iBAAiB,SAAS,uBAAoB,QAAA"}
1
+ {"version":3,"file":"common.d.cts","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"mappings":";wBAIgB,uBAAuB;EACrC;EACA;EACA;EACA;EACA;EACA,OAAO,KAAK;EACZ;IACD;wBAeqB,0BACpB,QAAQ;EACN;EACA;;EAEA,UAAU;IACX,QAAA;wBAyBmB,mBACpB,QAAQ;EACN;EACA;IACD,QAAA;UAsBO;EACR;EACA;EACA;EACA;EACA;;wBAGoB,YAAY,QAAQ,oBAAiB;iBAwB1C;EACf;;EAEA;;;;;;EAMA;;wBAmBoB,cAAc,GAAG,iBAAiB,SAAS,uBAAoB,QAAA"}
@@ -6,6 +6,7 @@ export declare function createAuthorizationUri(options: {
6
6
  redirectUri: string;
7
7
  authorizationUri: string;
8
8
  pkce?: Omit<PkceParameters, 'code_verifier'>;
9
+ nonce?: string;
9
10
  }): URL;
10
11
  export declare function exchangeAuthorizationCode(params: ExchangeCodeParams & {
11
12
  tokenUri: string;
@@ -1 +1 @@
1
- {"version":3,"file":"common.d.mts","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"mappings":";wBAIgB,uBAAuB;EACrC;EACA;EACA;EACA;EACA;EACA,OAAO,KAAK;IACb;wBAcqB,0BACpB,QAAQ;EACN;EACA;;EAEA,UAAU;IACX,QAAA;wBAyBmB,mBACpB,QAAQ;EACN;EACA;IACD,QAAA;UAsBO;EACR;EACA;EACA;EACA;EACA;;wBAGoB,YAAY,QAAQ,oBAAiB;iBAwB1C;EACf;;EAEA;;;;;;EAMA;;wBAmBoB,cAAc,GAAG,iBAAiB,SAAS,uBAAoB,QAAA"}
1
+ {"version":3,"file":"common.d.mts","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"mappings":";wBAIgB,uBAAuB;EACrC;EACA;EACA;EACA;EACA;EACA,OAAO,KAAK;EACZ;IACD;wBAeqB,0BACpB,QAAQ;EACN;EACA;;EAEA,UAAU;IACX,QAAA;wBAyBmB,mBACpB,QAAQ;EACN;EACA;IACD,QAAA;UAsBO;EACR;EACA;EACA;EACA;EACA;;wBAGoB,YAAY,QAAQ,oBAAiB;iBAwB1C;EACf;;EAEA;;;;;;EAMA;;wBAmBoB,cAAc,GAAG,iBAAiB,SAAS,uBAAoB,QAAA"}
@@ -6,6 +6,7 @@ function createAuthorizationUri(options) {
6
6
  url.searchParams.append("response_type", "code");
7
7
  url.searchParams.append("client_id", options.clientId);
8
8
  url.searchParams.append("state", options.state);
9
+ if (options.nonce) url.searchParams.append("nonce", options.nonce);
9
10
  url.searchParams.append("scope", options.scope.join(" "));
10
11
  url.searchParams.append("redirect_uri", options.redirectUri);
11
12
  if (options.pkce) {
@@ -1 +1 @@
1
- {"version":3,"file":"common.mjs","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n /** Extra request headers some providers require, e.g. GitHub's `User-Agent`. */\n headers?: Record<string, string>;\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n ...params.headers,\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n // Public clients (Google's installed-app clients, PKCE-only clients) have no secret.\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret?: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Revoke token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport interface VerifyIdTokenOptions {\n jwkSetUri: string;\n /** The `iss` values the provider signs with; anything else is refused. */\n issuer: string | string[];\n /**\n * The client the token must be issued to. An id token proves who the user is only to the client\n * it names in `aud`: any other app on the same identity provider can obtain a validly signed one\n * for the same user, so a token for a foreign client must never sign anyone in here.\n */\n audience: string;\n}\n\n/**\n * One key set per JWKS endpoint for the life of the process: jose caches the fetched keys,\n * refetches on an unknown `kid` (with a cooldown) and when they go stale, so a set created per\n * call would refetch the keys for every id token.\n */\nconst jwkSets = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\nfunction remoteJWKSet(jwkSetUri: string) {\n let jwks = jwkSets.get(jwkSetUri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(jwkSetUri));\n jwkSets.set(jwkSetUri, jwks);\n }\n return jwks;\n}\n\nexport async function verifyIdToken<T>(idToken: string, options: VerifyIdTokenOptions) {\n const { jwkSetUri, issuer, audience } = options;\n try {\n const jwks = remoteJWKSet(jwkSetUri);\n const { payload } = await jwtVerify(idToken, jwks, { issuer, audience });\n return payload as T;\n } catch (error) {\n console.error('Failed to verify id_token', error);\n // The token is the grant here: one for another audience or issuer is an invalid grant, not a\n // malformed request.\n throw new OAuth2Error(400, 'invalid_grant', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;AAIA,SAAgB,uBAAuB,SAOpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBA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AAE,YAAY,MAAM,UAAU,SAAS,MAAM;GAAE;GAAQ;EAAS,CAAC;EACvE,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,MAAM,6BAA6B,KAAK;EAGhD,MAAM,IAAI,YAAY,KAAK,iBAAiB,2BAA2B;CACzE;AACF"}
1
+ {"version":3,"file":"common.mjs","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n nonce?: string;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n if (options.nonce) url.searchParams.append('nonce', options.nonce);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n /** Extra request headers some providers require, e.g. GitHub's `User-Agent`. */\n headers?: Record<string, string>;\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n ...params.headers,\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n // Public clients (Google's installed-app clients, PKCE-only clients) have no secret.\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret?: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret ?? ''}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n if (params.clientSecret) body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Revoke token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport interface VerifyIdTokenOptions {\n jwkSetUri: string;\n /** The `iss` values the provider signs with; anything else is refused. */\n issuer: string | string[];\n /**\n * The client the token must be issued to. An id token proves who the user is only to the client\n * it names in `aud`: any other app on the same identity provider can obtain a validly signed one\n * for the same user, so a token for a foreign client must never sign anyone in here.\n */\n audience: string;\n}\n\n/**\n * One key set per JWKS endpoint for the life of the process: jose caches the fetched keys,\n * refetches on an unknown `kid` (with a cooldown) and when they go stale, so a set created per\n * call would refetch the keys for every id token.\n */\nconst jwkSets = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\nfunction remoteJWKSet(jwkSetUri: string) {\n let jwks = jwkSets.get(jwkSetUri);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(jwkSetUri));\n jwkSets.set(jwkSetUri, jwks);\n }\n return jwks;\n}\n\nexport async function verifyIdToken<T>(idToken: string, options: VerifyIdTokenOptions) {\n const { jwkSetUri, issuer, audience } = options;\n try {\n const jwks = remoteJWKSet(jwkSetUri);\n const { payload } = await jwtVerify(idToken, jwks, { issuer, audience });\n return payload as T;\n } catch (error) {\n console.error('Failed to verify id_token', error);\n // The token is the grant here: one for another audience or issuer is an invalid grant, not a\n // malformed request.\n throw new OAuth2Error(400, 'invalid_grant', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;AAIA,SAAgB,uBAAuB,SAQpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,QAAQ,OAAO,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CACjE,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACxD,IAAI,aAAa,OAAO,gBAAgB,QAAQ,WAAW;CAC3D,IAAI,QAAQ,MAAM;EAChB,IAAI,aAAa,OAAO,yBAAyB,QAAQ,KAAK,qBAAqB;EACnF,IAAI,aAAa,OAAO,kBAAkB,QAAQ,KAAK,cAAc;CACvE;CACA,OAAO;AACT;AAEA,eAAsB,0BACpB,QAMA;CACA,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,QA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V,OAAO,KAAK,GAAG,OAAO,SAAS,GAAG,OAAO,gBAAgB,IAAI,CAAC,CAAC,SAAS,QACjD;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,IAAI,OAAO,cAAc,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAC3E;CAEA,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;CACrF,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,QAAQ,MAAM,SAAS,KAAK;EAClC,QAAQ,MAAM,uBAAuB,KAAK;EAC1C,MAAM,IAAI,YAAY,SAAS,QAAQ,mBAAmB,wBAAwB;CACpF;AACF;;;;;;AAmBA,MAAM,0BAAU,IAAI,IAAmD;AAEvE,SAAS,aAAa,WAAmB;CACvC,IAAI,OAAO,QAAQ,IAAI,SAAS;CAChC,IAAI,CAAC,MAAM;EACT,OAAO,mBAAmB,IAAI,IAAI,SAAS,CAAC;EAC5C,QAAQ,IAAI,WAAW,IAAI;CAC7B;CACA,OAAO;AACT;AAEA,eAAsB,cAAiB,SAAiB,SAA+B;CACrF,MAAM,EAAE,WAAW,QAAQ,aAAa;CACxC,IAAI;EACF,MAAM,OAAO,aAAa,SAAS;EACnC,MAAM,EAAE,YAAY,MAAM,UAAU,SAAS,MAAM;GAAE;GAAQ;EAAS,CAAC;EACvE,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,MAAM,6BAA6B,KAAK;EAGhD,MAAM,IAAI,YAAY,KAAK,iBAAiB,2BAA2B;CACzE;AACF"}
@@ -21,6 +21,10 @@ function createFacebookProvider() {
21
21
  jwkSetUri: "https://limited.facebook.com/.well-known/oauth/openid/jwks/",
22
22
  userNameAttribute: "id",
23
23
  defaultScope: ["profile", "email"],
24
+ nonce: {
25
+ web: false,
26
+ native: true
27
+ },
24
28
  createAuthorizationUri({ pkce: _, ...params }) {
25
29
  return require_oauth2_provider_common.createAuthorizationUri({
26
30
  ...params,
@@ -1 +1 @@
1
- {"version":3,"file":"facebook.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken","createHmac"],"sources":["../../../src/oauth2/provider/facebook.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { LoginOAuth2NativeParams, OAuth2Token, Provider, UserInfo } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/**\n * `iss` of Limited Login id tokens, per https://limited.facebook.com/.well-known/openid-configuration/\n * (their `aud` is the app id).\n */\nconst FACEBOOK_ISSUER = 'https://www.facebook.com';\n\n/**\n * ref: https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow/\n * ref: https://developers.facebook.com/tools/explorer\n * */\nexport function createFacebookProvider(): Provider {\n return {\n authorizationUri: 'https://www.facebook.com/v21.0/dialog/oauth',\n tokenUri: 'https://graph.facebook.com/v19.0/oauth/access_token',\n userInfoUri: 'https://graph.facebook.com/me',\n jwkSetUri: 'https://limited.facebook.com/.well-known/oauth/openid/jwks/',\n userNameAttribute: 'id',\n defaultScope: ['profile', 'email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as FacebookErrorResponse;\n throw new OAuth2Error(response.status, 'invalid_request', error.message);\n }\n return (await response.json()) as FacebookToken;\n },\n async getUserInfo({ id_token, access_token }, { clientId }) {\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n if (id_token) {\n const data = await verifyIdToken<FacebookDecodedIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: FACEBOOK_ISSUER,\n audience: clientId,\n });\n return {\n data,\n claims: {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n // Facebook does not say whether the address is verified: left unset, so a host that\n // trusts only `email_verified === true` treats it as unverified.\n },\n };\n }\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n return fetchUserInfo(this.userInfoUri, access_token);\n },\n async loginOAuth2Native({ clientId, clientSecret, credentials }: LoginOAuth2NativeParams) {\n const { id_token, access_token } = credentials;\n let userInfo: UserInfo;\n if (id_token) {\n // Limited Login: the id token's `aud` must be this app.\n userInfo = await this.getUserInfo(\n { token_type: 'bearer', access_token: '', id_token },\n {\n clientId,\n }\n );\n } else if (access_token) {\n // The Graph API serves any app's user access token, so `/me` alone would accept a token a\n // foreign app obtained for the same user. With `appsecret_proof` Facebook refuses tokens\n // not issued to the app whose secret signed the proof, binding the token to this client.\n if (!clientSecret) {\n throw new OAuth2Error(400, 'invalid_client', 'access_token login needs the app secret');\n }\n invariant(this.userInfoUri, 'userInfoUri is required');\n const proof = createHmac('sha256', clientSecret).update(access_token).digest('hex');\n userInfo = await fetchUserInfo(this.userInfoUri, access_token, proof);\n } else {\n throw new OAuth2Error(400, 'invalid_request', 'id_token or access_token is required');\n }\n const token: OAuth2Token = {\n token_type: 'bearer',\n access_token: access_token ?? '',\n id_token,\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const facebook = createFacebookProvider();\n\nasync function fetchUserInfo(\n userInfoUri: string,\n accessToken: string,\n appSecretProof?: string\n): Promise<UserInfo<FacebookUserInfo>> {\n const url = new URL(userInfoUri);\n const fields = ['id', 'name', 'email', 'picture.width(320).height(320)'];\n url.searchParams.append('access_token', accessToken);\n url.searchParams.append('fields', fields.join(','));\n if (appSecretProof) url.searchParams.append('appsecret_proof', appSecretProof);\n const headers = { Accept: 'application/json' };\n const response = await fetch(url.href, { headers });\n if (!response.ok) {\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to fetch user info');\n }\n const data = (await response.json()) as FacebookUserInfo;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name,\n email: data.email,\n picture: data.picture.data.url,\n // Not stated by the Graph API either; see the Limited Login path above.\n },\n };\n}\n\nexport interface FacebookDecodedIdToken {\n sub: string;\n name: string;\n email: string;\n picture: string;\n nonce?: string;\n}\n\nexport interface FacebookUserInfo {\n id: string;\n name: string;\n email: string;\n picture: {\n data: {\n url: string;\n width: number;\n height: number;\n is_silhouette: boolean;\n };\n };\n}\n\nexport interface FacebookToken extends OAuth2Token {\n access_token: string;\n token_type: 'bearer';\n expires_in: number;\n id_token?: string;\n}\n\nexport type FacebookAppCredential =\n | { state: string; id_token: string } // platform=ios and tracking=limited\n | { state: string; access_token: string }; // tracking=enabled\n\ninterface FacebookErrorResponse {\n error: {\n message: string;\n type: 'OAuthException';\n code: number;\n error_subcode: number;\n fbtrace_id: string;\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,yBAAmC;CACjD,OAAO;EACL,kBAAkB;EAClB,UAAU;EACV,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,cAAc,CAAC,WAAW,OAAO;EACjC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAOA,+BAAAA,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAMC,+BAAAA,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,mBAAmB,MAAM,OAAO;GACzE;GACA,OAAQ,MAAM,SAAS,KAAK;EAC9B;EACA,MAAM,YAAY,EAAE,UAAU,gBAAgB,EAAE,YAAY;GAC1D,CAAA,GAAA,cAAA,UAAA,CAAU,K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W;CACnD,IAAI,aAAa,OAAO,UAAU,OAAO,KAAK,GAAG,CAAC;CAClD,IAAI,gBAAgB,IAAI,aAAa,OAAO,mBAAmB,cAAc;CAE7E,MAAM,WAAW,MAAM,MAAM,IAAI,MAAM,EAAE,SAAA,EADvB,QAAQ,mBACqB,EAAE,CAAC;CAClD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAIA,qBAAAA,YAAY,SAAS,QAAQ,mBAAmB,2BAA2B;CAEvF,MAAM,OAAQ,MAAM,SAAS,KAAK;CAClC,OAAO;EACL;EACA,QAAQ;GACN,KAAK,KAAK;GACV,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,SAAS,KAAK,QAAQ,KAAK;EAE7B;CACF;AACF"}
1
+ {"version":3,"file":"facebook.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken","createHmac"],"sources":["../../../src/oauth2/provider/facebook.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { LoginOAuth2NativeParams, OAuth2Token, Provider, UserInfo } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/**\n * `iss` of Limited Login id tokens, per https://limited.facebook.com/.well-known/openid-configuration/\n * (their `aud` is the app id).\n */\nconst FACEBOOK_ISSUER = 'https://www.facebook.com';\n\n/**\n * ref: https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow/\n * ref: https://developers.facebook.com/tools/explorer\n * */\nexport function createFacebookProvider(): Provider {\n return {\n authorizationUri: 'https://www.facebook.com/v21.0/dialog/oauth',\n tokenUri: 'https://graph.facebook.com/v19.0/oauth/access_token',\n userInfoUri: 'https://graph.facebook.com/me',\n jwkSetUri: 'https://limited.facebook.com/.well-known/oauth/openid/jwks/',\n userNameAttribute: 'id',\n defaultScope: ['profile', 'email'],\n // The web flow reads the Graph API, no id token; Limited Login's id token must carry the\n // nonce the app set (an `access_token` login has no id token and is exempt).\n nonce: { web: false, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as FacebookErrorResponse;\n throw new OAuth2Error(response.status, 'invalid_request', error.message);\n }\n return (await response.json()) as FacebookToken;\n },\n async getUserInfo({ id_token, access_token }, { clientId }) {\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n if (id_token) {\n const data = await verifyIdToken<FacebookDecodedIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: FACEBOOK_ISSUER,\n audience: clientId,\n });\n return {\n data,\n claims: {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n // Facebook does not say whether the address is verified: left unset, so a host that\n // trusts only `email_verified === true` treats it as unverified.\n },\n };\n }\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n return fetchUserInfo(this.userInfoUri, access_token);\n },\n async loginOAuth2Native({ clientId, clientSecret, credentials }: LoginOAuth2NativeParams) {\n const { id_token, access_token } = credentials;\n let userInfo: UserInfo;\n if (id_token) {\n // Limited Login: the id token's `aud` must be this app.\n userInfo = await this.getUserInfo(\n { token_type: 'bearer', access_token: '', id_token },\n {\n clientId,\n }\n );\n } else if (access_token) {\n // The Graph API serves any app's user access token, so `/me` alone would accept a token a\n // foreign app obtained for the same user. With `appsecret_proof` Facebook refuses tokens\n // not issued to the app whose secret signed the proof, binding the token to this client.\n if (!clientSecret) {\n throw new OAuth2Error(400, 'invalid_client', 'access_token login needs the app secret');\n }\n invariant(this.userInfoUri, 'userInfoUri is required');\n const proof = createHmac('sha256', clientSecret).update(access_token).digest('hex');\n userInfo = await fetchUserInfo(this.userInfoUri, access_token, proof);\n } else {\n throw new OAuth2Error(400, 'invalid_request', 'id_token or access_token is required');\n }\n const token: OAuth2Token = {\n token_type: 'bearer',\n access_token: access_token ?? '',\n id_token,\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const facebook = createFacebookProvider();\n\nasync function fetchUserInfo(\n userInfoUri: string,\n accessToken: string,\n appSecretProof?: string\n): Promise<UserInfo<FacebookUserInfo>> {\n const url = new URL(userInfoUri);\n const fields = ['id', 'name', 'email', 'picture.width(320).height(320)'];\n url.searchParams.append('access_token', accessToken);\n url.searchParams.append('fields', fields.join(','));\n if (appSecretProof) url.searchParams.append('appsecret_proof', appSecretProof);\n const headers = { Accept: 'application/json' };\n const response = await fetch(url.href, { headers });\n if (!response.ok) {\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to fetch user info');\n }\n const data = (await response.json()) as FacebookUserInfo;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name,\n email: data.email,\n picture: data.picture.data.url,\n // Not stated by the Graph API either; see the Limited Login path above.\n },\n };\n}\n\nexport interface FacebookDecodedIdToken {\n sub: string;\n name: string;\n email: string;\n picture: string;\n nonce?: string;\n}\n\nexport interface FacebookUserInfo {\n id: string;\n name: string;\n email: string;\n picture: {\n data: {\n url: string;\n width: number;\n height: number;\n is_silhouette: boolean;\n };\n };\n}\n\nexport interface FacebookToken extends OAuth2Token {\n access_token: string;\n token_type: 'bearer';\n expires_in: number;\n id_token?: string;\n}\n\nexport type FacebookAppCredential =\n | { state: string; id_token: string } // platform=ios and tracking=limited\n | { state: string; access_token: string }; // tracking=enabled\n\ninterface FacebookErrorResponse {\n error: {\n message: string;\n type: 'OAuthException';\n code: number;\n error_subcode: number;\n fbtrace_id: string;\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,yBAAmC;CACjD,OAAO;EACL,kBAAkB;EAClB,UAAU;EACV,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,cAAc,CAAC,WAAW,OAAO;EAGjC,OAAO;GAAE,KAAK;GAA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ACA;MACA;;;;iBAKW,sBAAsB;EACrC;EACA;EACA;EACA;;YAGU;EACN;EAAe;;EACf;EAAe"}
1
+ {"version":3,"file":"facebook.d.cts","names":[],"sources":["../../../src/oauth2/provider/facebook.ts"],"mappings":";;;;;wBAgBgB,0BAA0B;qBAoF7B,UAAQ;iBA8BJ;EACf;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;IACE;MACE;MACA;MACA;MACA;;;;iBAKW,sBAAsB;EACrC;EACA;EACA;EACA;;YAGU;EACN;EAAe;;EACf;EAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"facebook.d.mts","names":[],"sources":["../../../src/oauth2/provider/facebook.ts"],"mappings":";;;;;wBAgBgB,0BAA0B;qBAiF7B,UAAQ;iBA8BJ;EACf;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;IACE;MACE;MACA;MACA;MACA;;;;iBAKW,sBAAsB;EACrC;EACA;EACA;EACA;;YAGU;EACN;EAAe;;EACf;EAAe"}
1
+ {"version":3,"file":"facebook.d.mts","names":[],"sources":["../../../src/oauth2/provider/facebook.ts"],"mappings":";;;;;wBAgBgB,0BAA0B;qBAoF7B,UAAQ;iBA8BJ;EACf;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;IACE;MACE;MACA;MACA;MACA;;;;iBAKW,sBAAsB;EACrC;EACA;EACA;EACA;;YAGU;EACN;EAAe;;EACf;EAAe"}
@@ -20,6 +20,10 @@ function createFacebookProvider() {
20
20
  jwkSetUri: "https://limited.facebook.com/.well-known/oauth/openid/jwks/",
21
21
  userNameAttribute: "id",
22
22
  defaultScope: ["profile", "email"],
23
+ nonce: {
24
+ web: false,
25
+ native: true
26
+ },
23
27
  createAuthorizationUri({ pkce: _, ...params }) {
24
28
  return createAuthorizationUri({
25
29
  ...params,
@@ -1 +1 @@
1
- {"version":3,"file":"facebook.mjs","names":[],"sources":["../../../src/oauth2/provider/facebook.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { LoginOAuth2NativeParams, OAuth2Token, Provider, UserInfo } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/**\n * `iss` of Limited Login id tokens, per https://limited.facebook.com/.well-known/openid-configuration/\n * (their `aud` is the app id).\n */\nconst FACEBOOK_ISSUER = 'https://www.facebook.com';\n\n/**\n * ref: https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow/\n * ref: https://developers.facebook.com/tools/explorer\n * */\nexport function createFacebookProvider(): Provider {\n return {\n authorizationUri: 'https://www.facebook.com/v21.0/dialog/oauth',\n tokenUri: 'https://graph.facebook.com/v19.0/oauth/access_token',\n userInfoUri: 'https://graph.facebook.com/me',\n jwkSetUri: 'https://limited.facebook.com/.well-known/oauth/openid/jwks/',\n userNameAttribute: 'id',\n defaultScope: ['profile', 'email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as FacebookErrorResponse;\n throw new OAuth2Error(response.status, 'invalid_request', error.message);\n }\n return (await response.json()) as FacebookToken;\n },\n async getUserInfo({ id_token, access_token }, { clientId }) {\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n if (id_token) {\n const data = await verifyIdToken<FacebookDecodedIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: FACEBOOK_ISSUER,\n audience: clientId,\n });\n return {\n data,\n claims: {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n // Facebook does not say whether the address is verified: left unset, so a host that\n // trusts only `email_verified === true` treats it as unverified.\n },\n };\n }\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n return fetchUserInfo(this.userInfoUri, access_token);\n },\n async loginOAuth2Native({ clientId, clientSecret, credentials }: LoginOAuth2NativeParams) {\n const { id_token, access_token } = credentials;\n let userInfo: UserInfo;\n if (id_token) {\n // Limited Login: the id token's `aud` must be this app.\n userInfo = await this.getUserInfo(\n { token_type: 'bearer', access_token: '', id_token },\n {\n clientId,\n }\n );\n } else if (access_token) {\n // The Graph API serves any app's user access token, so `/me` alone would accept a token a\n // foreign app obtained for the same user. With `appsecret_proof` Facebook refuses tokens\n // not issued to the app whose secret signed the proof, binding the token to this client.\n if (!clientSecret) {\n throw new OAuth2Error(400, 'invalid_client', 'access_token login needs the app secret');\n }\n invariant(this.userInfoUri, 'userInfoUri is required');\n const proof = createHmac('sha256', clientSecret).update(access_token).digest('hex');\n userInfo = await fetchUserInfo(this.userInfoUri, access_token, proof);\n } else {\n throw new OAuth2Error(400, 'invalid_request', 'id_token or access_token is required');\n }\n const token: OAuth2Token = {\n token_type: 'bearer',\n access_token: access_token ?? '',\n id_token,\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const facebook = createFacebookProvider();\n\nasync function fetchUserInfo(\n userInfoUri: string,\n accessToken: string,\n appSecretProof?: string\n): Promise<UserInfo<FacebookUserInfo>> {\n const url = new URL(userInfoUri);\n const fields = ['id', 'name', 'email', 'picture.width(320).height(320)'];\n url.searchParams.append('access_token', accessToken);\n url.searchParams.append('fields', fields.join(','));\n if (appSecretProof) url.searchParams.append('appsecret_proof', appSecretProof);\n const headers = { Accept: 'application/json' };\n const response = await fetch(url.href, { headers });\n if (!response.ok) {\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to fetch user info');\n }\n const data = (await response.json()) as FacebookUserInfo;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name,\n email: data.email,\n picture: data.picture.data.url,\n // Not stated by the Graph API either; see the Limited Login path above.\n },\n };\n}\n\nexport interface FacebookDecodedIdToken {\n sub: string;\n name: string;\n email: string;\n picture: string;\n nonce?: string;\n}\n\nexport interface FacebookUserInfo {\n id: string;\n name: string;\n email: string;\n picture: {\n data: {\n url: string;\n width: number;\n height: number;\n is_silhouette: boolean;\n };\n };\n}\n\nexport interface FacebookToken extends OAuth2Token {\n access_token: string;\n token_type: 'bearer';\n expires_in: number;\n id_token?: string;\n}\n\nexport type FacebookAppCredential =\n | { state: string; id_token: string } // platform=ios and tracking=limited\n | { state: string; access_token: string }; // tracking=enabled\n\ninterface FacebookErrorResponse {\n error: {\n message: string;\n type: 'OAuthException';\n code: number;\n error_subcode: number;\n fbtrace_id: string;\n };\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,yBAAmC;CACjD,OAAO;EACL,kBAAkB;EAClB,UAAU;EACV,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,cAAc,CAAC,WAAW,OAAO;EACjC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAO,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAM,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAI,YAAY,SAAS,QAAQ,mBAAmB,MAAM,OAAO;GACzE;GACA,OAAQ,MAAM,SAAS,KAAK;EAC9B;EACA,MAAM,YAAY,EAAE,UAAU,gBAAgB,EAAE,YAAY;GAC1D,UAAU,KAAK,WAAW,uBAAuB;GACjD,IAAI,UAAU;IACZ,MAAM,OAAO,MAAM,cAAsC,UAAU;KACjE,WAAW,KAAK;KAChB,QAAQ;KACR,UAAU;IACZ,CAAC;IACD,OAAO;KACL;KACA,QAAQ;MACN,KAAK,KAAK;MACV,MAAM,KAAK;MACX,SA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C,OAAO;EACL;EACA,QAAQ;GACN,KAAK,KAAK;GACV,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,SAAS,KAAK,QAAQ,KAAK;EAE7B;CACF;AACF"}
1
+ {"version":3,"file":"facebook.mjs","names":[],"sources":["../../../src/oauth2/provider/facebook.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { LoginOAuth2NativeParams, OAuth2Token, Provider, UserInfo } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/**\n * `iss` of Limited Login id tokens, per https://limited.facebook.com/.well-known/openid-configuration/\n * (their `aud` is the app id).\n */\nconst FACEBOOK_ISSUER = 'https://www.facebook.com';\n\n/**\n * ref: https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow/\n * ref: https://developers.facebook.com/tools/explorer\n * */\nexport function createFacebookProvider(): Provider {\n return {\n authorizationUri: 'https://www.facebook.com/v21.0/dialog/oauth',\n tokenUri: 'https://graph.facebook.com/v19.0/oauth/access_token',\n userInfoUri: 'https://graph.facebook.com/me',\n jwkSetUri: 'https://limited.facebook.com/.well-known/oauth/openid/jwks/',\n userNameAttribute: 'id',\n defaultScope: ['profile', 'email'],\n // The web flow reads the Graph API, no id token; Limited Login's id token must carry the\n // nonce the app set (an `access_token` login has no id token and is exempt).\n nonce: { web: false, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as FacebookErrorResponse;\n throw new OAuth2Error(response.status, 'invalid_request', error.message);\n }\n return (await response.json()) as FacebookToken;\n },\n async getUserInfo({ id_token, access_token }, { clientId }) {\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n if (id_token) {\n const data = await verifyIdToken<FacebookDecodedIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: FACEBOOK_ISSUER,\n audience: clientId,\n });\n return {\n data,\n claims: {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n // Facebook does not say whether the address is verified: left unset, so a host that\n // trusts only `email_verified === true` treats it as unverified.\n },\n };\n }\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n return fetchUserInfo(this.userInfoUri, access_token);\n },\n async loginOAuth2Native({ clientId, clientSecret, credentials }: LoginOAuth2NativeParams) {\n const { id_token, access_token } = credentials;\n let userInfo: UserInfo;\n if (id_token) {\n // Limited Login: the id token's `aud` must be this app.\n userInfo = await this.getUserInfo(\n { token_type: 'bearer', access_token: '', id_token },\n {\n clientId,\n }\n );\n } else if (access_token) {\n // The Graph API serves any app's user access token, so `/me` alone would accept a token a\n // foreign app obtained for the same user. With `appsecret_proof` Facebook refuses tokens\n // not issued to the app whose secret signed the proof, binding the token to this client.\n if (!clientSecret) {\n throw new OAuth2Error(400, 'invalid_client', 'access_token login needs the app secret');\n }\n invariant(this.userInfoUri, 'userInfoUri is required');\n const proof = createHmac('sha256', clientSecret).update(access_token).digest('hex');\n userInfo = await fetchUserInfo(this.userInfoUri, access_token, proof);\n } else {\n throw new OAuth2Error(400, 'invalid_request', 'id_token or access_token is required');\n }\n const token: OAuth2Token = {\n token_type: 'bearer',\n access_token: access_token ?? '',\n id_token,\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const facebook = createFacebookProvider();\n\nasync function fetchUserInfo(\n userInfoUri: string,\n accessToken: string,\n appSecretProof?: string\n): Promise<UserInfo<FacebookUserInfo>> {\n const url = new URL(userInfoUri);\n const fields = ['id', 'name', 'email', 'picture.width(320).height(320)'];\n url.searchParams.append('access_token', accessToken);\n url.searchParams.append('fields', fields.join(','));\n if (appSecretProof) url.searchParams.append('appsecret_proof', appSecretProof);\n const headers = { Accept: 'application/json' };\n const response = await fetch(url.href, { headers });\n if (!response.ok) {\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to fetch user info');\n }\n const data = (await response.json()) as FacebookUserInfo;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name,\n email: data.email,\n picture: data.picture.data.url,\n // Not stated by the Graph API either; see the Limited Login path above.\n },\n };\n}\n\nexport interface FacebookDecodedIdToken {\n sub: string;\n name: string;\n email: string;\n picture: string;\n nonce?: string;\n}\n\nexport interface FacebookUserInfo {\n id: string;\n name: string;\n email: string;\n picture: {\n data: {\n url: string;\n width: number;\n height: number;\n is_silhouette: boolean;\n };\n };\n}\n\nexport interface FacebookToken extends OAuth2Token {\n access_token: string;\n token_type: 'bearer';\n expires_in: number;\n id_token?: string;\n}\n\nexport type FacebookAppCredential =\n | { state: string; id_token: string } // platform=ios and tracking=limited\n | { state: string; access_token: string }; // tracking=enabled\n\ninterface FacebookErrorResponse {\n error: {\n message: string;\n type: 'OAuthException';\n code: number;\n error_subcode: number;\n fbtrace_id: string;\n };\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,yBAAmC;CACjD,OAAO;EACL,kBAAkB;EAClB,UAAU;EACV,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,cAAc,CAAC,WAAW,OAAO;EAGjC,OAAO;GAAE,KAAK;GAAO,QAAQ;EAAK;EAClC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAO,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAM,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAI,YAA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AAa,OAAO,gBAAgB,WAAW;CACnD,IAAI,aAAa,OAAO,UAAU,OAAO,KAAK,GAAG,CAAC;CAClD,IAAI,gBAAgB,IAAI,aAAa,OAAO,mBAAmB,cAAc;CAE7E,MAAM,WAAW,MAAM,MAAM,IAAI,MAAM,EAAE,SAAA,EADvB,QAAQ,mBACqB,EAAE,CAAC;CAClD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,YAAY,SAAS,QAAQ,mBAAmB,2BAA2B;CAEvF,MAAM,OAAQ,MAAM,SAAS,KAAK;CAClC,OAAO;EACL;EACA,QAAQ;GACN,KAAK,KAAK;GACV,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,SAAS,KAAK,QAAQ,KAAK;EAE7B;CACF;AACF"}
@@ -29,6 +29,10 @@ function createGoogleProvider() {
29
29
  "https://www.googleapis.com/auth/userinfo.profile",
30
30
  "openid"
31
31
  ],
32
+ nonce: {
33
+ web: true,
34
+ native: false
35
+ },
32
36
  createAuthorizationUri(params) {
33
37
  return require_oauth2_provider_common.createAuthorizationUri({
34
38
  ...params,
@@ -1 +1 @@
1
- {"version":3,"file":"google.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken"],"sources":["../../../src/oauth2/provider/google.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n OneTapProvider,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** Google signs id tokens with either `iss`, the URL or the bare host. */\nconst GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com'];\n\nfunction claims(data: GoogleUserInfo) {\n return {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n email_verified: data.email_verified,\n given_name: data.given_name,\n family_name: data.family_name,\n locale: data.locale,\n };\n}\n\nexport function createGoogleProvider(): OneTapProvider {\n return {\n authorizationUri: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUri: 'https://oauth2.googleapis.com/token',\n userInfoUri: 'https://www.googleapis.com/oauth2/v3/userinfo',\n userNameAttribute: 'sub',\n jwkSetUri: 'https://www.googleapis.com/oauth2/v3/certs',\n // https://developers.google.com/identity/protocols/oauth2/scopes#oauth2\n defaultScope: [\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'openid',\n ],\n createAuthorizationUri(params) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode(params) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GoogleErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n return (await response.json()) as GoogleToken;\n },\n async getUserInfo({ id_token }, { clientId }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n const data = await verifyIdToken<GoogleUserInfo>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: GOOGLE_ISSUERS,\n audience: clientId,\n });\n return { data, claims: claims(data) };\n },\n async loginOAuth2Native({ pkce, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { code } = credentials;\n const { tokenUri } = this;\n // An app signs in as its own installed-app client (the iOS / Android client id, custom-scheme\n // redirect), and Google only exchanges a code for the client it was issued to, so the exchange\n // runs as the client the app names, which the OAuth2 client has already checked is one of this\n // provider's configured clients. Installed-app clients have no secret. The redirect URI is the\n // one the app used, which only the app knows. So is the PKCE verifier, when the app sent a\n // challenge: Google then refuses the code without it.\n const { redirect_uri = params.redirectUri } = credentials;\n const response = await exchangeAuthorizationCode({\n code,\n pkce,\n tokenUri,\n clientId: params.clientId,\n clientSecret: params.clientSecret,\n redirectUri: redirect_uri,\n });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GoogleErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n const token = (await response.json()) as GoogleToken;\n const userInfo = await this.getUserInfo(token, { clientId: params.clientId });\n return { token, userInfo };\n },\n async getTokenInfo(id_token: string, clientId: string) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // One Tap and FedCM issue the credential to the web client.\n const data = await verifyIdToken<GoogleUserInfo>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: GOOGLE_ISSUERS,\n audience: clientId,\n });\n return {\n token: {\n id_token,\n access_token: '',\n token_type: '',\n expires_in: 0,\n refresh_token: '',\n scope: '',\n },\n userInfo: { data, claims: claims(data) },\n };\n },\n };\n}\n\nexport const google = createGoogleProvider();\n\nexport interface GoogleUserInfo {\n aud: string;\n azp: string;\n email: string;\n email_verified: boolean;\n exp: number;\n family_name: string;\n given_name: string;\n hd?: string;\n iat: number;\n iss: string;\n jti?: string;\n locale?: string;\n name: string;\n nbf?: number;\n picture: string;\n sub: string;\n nonce?: string;\n}\n\nexport interface GoogleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n scope: string;\n}\n\n// android,ios has different client_id and redirect_uri\nexport interface GoogleAppCredential extends NativeCredential {\n state: string;\n code: string;\n client_id: string;\n redirect_uri: string;\n}\n\nexport interface GoogleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'invalid_token'\n | 'invalid_scope'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'access_denied'\n | 'server_error';\n error_description: string;\n}\n"],"mappings":";;;;;;AAWA,MAAM,iBAAiB,CAAC,+BAA+B,qBAAqB;AAE5E,SAAS,OAAO,MAAsB;CACpC,OAAO;EACL,KAAK,KAAK;EACV,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACZ,gBAAgB,KAAK;EACrB,YAAY,KAAK;EACjB,aAAa,KAAK;EAClB,QAAQ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AM,EAAE,OAAO,sBAAuB,MAAM,SAAS,KAAK;IAC1D,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,OAAO,iBAAiB;GACjE;GACA,MAAM,QAAS,MAAM,SAAS,KAAK;GAEnC,OAAO;IAAE;IAAO,UAAA,MADO,KAAK,YAAY,OAAO,EAAE,UAAU,OAAO,SAAS,CAAC;GACnD;EAC3B;EACA,MAAM,aAAa,UAAkB,UAAkB;GACrD,CAAA,GAAA,cAAA,UAAA,CAAU,UAAU,sBAAsB;GAC1C,CAAA,GAAA,cAAA,UAAA,CAAU,KAAK,WAAW,uBAAuB;GAEjD,MAAM,OAAO,MAAMC,+BAAAA,cAA8B,UAAU;IACzD,WAAW,KAAK;IAChB,QAAQ;IACR,UAAU;GACZ,CAAC;GACD,OAAO;IACL,OAAO;KACL;KACA,cAAc;KACd,YAAY;KACZ,YAAY;KACZ,eAAe;KACf,OAAO;IACT;IACA,UAAU;KAAE;KAAM,QAAQ,OAAO,IAAI;IAAE;GACzC;EACF;CACF;AACF;AAEA,MAAa,SAAS,qBAAqB"}
1
+ {"version":3,"file":"google.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken"],"sources":["../../../src/oauth2/provider/google.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n OneTapProvider,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** Google signs id tokens with either `iss`, the URL or the bare host. */\nconst GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com'];\n\nfunction claims(data: GoogleUserInfo) {\n return {\n sub: data.sub,\n name: data.name,\n picture: data.picture,\n email: data.email,\n email_verified: data.email_verified,\n given_name: data.given_name,\n family_name: data.family_name,\n locale: data.locale,\n };\n}\n\nexport function createGoogleProvider(): OneTapProvider {\n return {\n authorizationUri: 'https://accounts.google.com/o/oauth2/v2/auth',\n tokenUri: 'https://oauth2.googleapis.com/token',\n userInfoUri: 'https://www.googleapis.com/oauth2/v3/userinfo',\n userNameAttribute: 'sub',\n jwkSetUri: 'https://www.googleapis.com/oauth2/v3/certs',\n // https://developers.google.com/identity/protocols/oauth2/scopes#oauth2\n defaultScope: [\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'openid',\n ],\n // The web flow and One Tap echo the nonce; an app signs in with a code it exchanges here,\n // bound by PKCE, and Google's native SDKs put no nonce in that id token.\n nonce: { web: true, native: false },\n createAuthorizationUri(params) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode(params) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GoogleErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n return (await response.json()) as GoogleToken;\n },\n async getUserInfo({ id_token }, { clientId }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n const data = await verifyIdToken<GoogleUserInfo>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: GOOGLE_ISSUERS,\n audience: clientId,\n });\n return { data, claims: claims(data) };\n },\n async loginOAuth2Native({ pkce, credentials, ...params }: LoginOAuth2NativeParams) {\n invariant(credentials.code, 'code is required');\n const { code } = credentials;\n const { tokenUri } = this;\n // An app signs in as its own installed-app client (the iOS / Android client id, custom-scheme\n // redirect), and Google only exchanges a code for the client it was issued to, so the exchange\n // runs as the client the app names, which the OAuth2 client has already checked is one of this\n // provider's configured clients. Installed-app clients have no secret. The redirect URI is the\n // one the app used, which only the app knows. So is the PKCE verifier, when the app sent a\n // challenge: Google then refuses the code without it.\n const { redirect_uri = params.redirectUri } = credentials;\n const response = await exchangeAuthorizationCode({\n code,\n pkce,\n tokenUri,\n clientId: params.clientId,\n clientSecret: params.clientSecret,\n redirectUri: redirect_uri,\n });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GoogleErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n const token = (await response.json()) as GoogleToken;\n const userInfo = await this.getUserInfo(token, { clientId: params.clientId });\n return { token, userInfo };\n },\n async getTokenInfo(id_token: string, clientId: string) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // One Tap and FedCM issue the credential to the web client.\n const data = await verifyIdToken<GoogleUserInfo>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: GOOGLE_ISSUERS,\n audience: clientId,\n });\n return {\n token: {\n id_token,\n access_token: '',\n token_type: '',\n expires_in: 0,\n refresh_token: '',\n scope: '',\n },\n userInfo: { data, claims: claims(data) },\n };\n },\n };\n}\n\nexport const google = createGoogleProvider();\n\nexport interface GoogleUserInfo {\n aud: string;\n azp: string;\n email: string;\n email_verified: boolean;\n exp: number;\n family_name: string;\n given_name: string;\n hd?: string;\n iat: number;\n iss: string;\n jti?: string;\n locale?: string;\n name: string;\n nbf?: number;\n picture: string;\n sub: string;\n nonce?: string;\n}\n\nexport interface GoogleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n scope: string;\n}\n\n// android,ios has different client_id and redirect_uri\nexport interface GoogleAppCredential extends NativeCredential {\n state: string;\n code: string;\n client_id: string;\n redirect_uri: string;\n}\n\nexport interface GoogleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'invalid_token'\n | 'invalid_scope'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'access_denied'\n | 'server_error';\n error_description: string;\n}\n"],"mappings":";;;;;;AAWA,MAAM,iBAAiB,CAAC,+BAA+B,qBAAqB;AAE5E,SAAS,OAAO,MAAsB;CACpC,OAAO;EACL,KAAK,KAAK;EACV,MAAM,KAAK;EACX,SAAS,KAAK;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,+BAAAA,0BAA0B;IAC/C;IACA;IACA;IACA,UAAU,OAAO;IACjB,cAAc,OAAO;IACrB,aAAa;GACf,CAAC;GACD,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,OAAO,sBAAuB,MAAM,SAAS,KAAK;IAC1D,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,OAAO,iBAAiB;GACjE;GACA,MAAM,QAAS,MAAM,SAAS,KAAK;GAEnC,OAAO;IAAE;IAAO,UAAA,MADO,KAAK,YAAY,OAAO,EAAE,UAAU,OAAO,SAAS,CAAC;GACnD;EAC3B;EACA,MAAM,aAAa,UAAkB,UAAkB;GACrD,CAAA,GAAA,cAAA,UAAA,CAAU,UAAU,sBAAsB;GAC1C,CAAA,GAAA,cAAA,UAAA,CAAU,KAAK,WAAW,uBAAuB;GAEjD,MAAM,OAAO,MAAMC,+BAAAA,cAA8B,UAAU;IACzD,WAAW,KAAK;IAChB,QAAQ;IACR,UAAU;GACZ,CAAC;GACD,OAAO;IACL,OAAO;KACL;KACA,cAAc;KACd,YAAY;KACZ,YAAY;KACZ,eAAe;KACf,OAAO;IACT;IACA,UAAU;KAAE;KAAM,QAAQ,OAAO,IAAI;IAAE;GACzC;EACF;CACF;AACF;AAEA,MAAa,SAAS,qBAAqB"}
@@ -1 +1 @@
1
- {"version":3,"file":"google.d.cts","names":[],"sources":["../../../src/oauth2/provider/google.ts"],"mappings":";wBA0BgB,wBAAwB;qBAyF3B,QAAM;iBAEF;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,oBAAoB;EACnC;EACA;EACA;EACA;EACA;EACA;;iBAIe,4BAA4B;EAC3C;EACA;EACA;EACA;;iBAGe;EACf;EAUA"}
1
+ {"version":3,"file":"google.d.cts","names":[],"sources":["../../../src/oauth2/provider/google.ts"],"mappings":";wBA0BgB,wBAAwB;qBA4F3B,QAAM;iBAEF;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,oBAAoB;EACnC;EACA;EACA;EACA;EACA;EACA;;iBAIe,4BAA4B;EAC3C;EACA;EACA;EACA;;iBAGe;EACf;EAUA"}