@mayurajs/auth-facebook 0.0.0-stage → 1.2.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Mayura
2
+ Copyright 2026 The Mayura Authors
3
+
4
+ This product includes software developed by the Mayura contributors.
5
+
6
+ Third-party dependencies retain their own copyright and license terms. Exact
7
+ resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
8
+ artifact and dependency qualification procedures.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/auth-facebook
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Facebook sign-in for Mayura, on any runtime, with no dependency:
4
+
5
+ - `facebookAuthenticator`: Facebook Login user access tokens sent straight to Mayura's server, checked with Facebook,
6
+ and iOS Limited Login tokens, checked with Facebook's keys;
7
+ - `facebookSignIn`: Facebook as a better-auth social login (with `mayura/auth/better-auth`), reading no more of the
8
+ profile than signing in needs.
9
+
10
+ ```bash
11
+ npm install mayura @mayurajs/auth-facebook
12
+ ```
13
+
14
+ ```ts
15
+ import { principalId } from 'mayura/auth';
16
+ import { facebookAuthenticator, facebookSignIn } from '@mayurajs/auth-facebook';
17
+
18
+ const authenticate = facebookAuthenticator({
19
+ appId: process.env.FACEBOOK_APP_ID!,
20
+ appSecret: process.env.FACEBOOK_APP_SECRET!,
21
+ requiredScopes: ['email'],
22
+ identity: session => ({
23
+ principalId: principalId('facebook', session.userId),
24
+ projectId: 'acme',
25
+ agentIds: ['support'],
26
+ capabilities: ['runs:submit', 'runs:read'],
27
+ }),
28
+ });
29
+
30
+ // Or sign people in with better-auth:
31
+ // betterAuth({ socialProviders: { facebook: facebookSignIn({ clientId, clientSecret }) }, ... })
32
+ ```
33
+
34
+ - **Access tokens are opaque**, so each one is checked with Facebook's `debug_token` (Graph API `v26.0` unless
35
+ `graphVersion`), using your app's token (`appId|appSecret`, which never leaves your server and never appears in an
36
+ error). A token passes only when Facebook says it is valid, a user's, for your app, unexpired, and holds every
37
+ `requiredScopes` permission. That is a call to Facebook per request: `cacheTtlMs` (up to 5 minutes, 0 by default)
38
+ keeps Facebook's answer for that long, so a token the user revokes then works for that long more. A call takes at
39
+ most `timeoutMs` (5 s); when Facebook cannot answer, the server answers that authentication is unavailable.
40
+ - **Limited Login** (with `limitedLogin: true`): iOS Limited Login tokens are OIDC JWTs, checked with no call per
41
+ request: RS256 with Facebook's keys, issued by `https://www.facebook.com`, for your app. Check the token's `nonce`
42
+ in your app, which made it.
43
+ - **What you get.** `identity` receives `kind` (`access_token` or `limited_login`), `userId` (app-scoped: the same
44
+ person has a different id in each of your apps), `scopes`, `email` and `name` (Limited Login), and `expiresAtMs`.
45
+ Nothing is granted unless `identity` grants it.
46
+ - **`facebookSignIn`** gives better-auth's `socialProviders.facebook` reading only `id`, `name` and `email` (`picture`
47
+ if asked), with no permissions beyond better-auth's `email` and `public_profile` unless you add `scopes`.
48
+ - Options: `facebookAuthenticator({ appId, appSecret, identity, requiredScopes, limitedLogin, cacheTtlMs, timeoutMs,
49
+ graphVersion, clockSkewMs, maxIdentityMs, fetch })`, `facebookSignIn({ clientId, clientSecret, picture, scopes })`.
50
+
51
+ See [Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
@@ -0,0 +1,67 @@
1
+ import { type Authenticator, type IdentityGrant } from 'mayura/auth';
2
+ /** A verified Facebook user: from a Login access token (checked with Facebook) or a Limited Login token. */
3
+ export interface FacebookSession {
4
+ /** `access_token` for a Facebook Login user access token; `limited_login` for an iOS Limited Login token. */
5
+ readonly kind: 'access_token' | 'limited_login';
6
+ /** The app-scoped user id: the same user has a different id in each of your apps. */
7
+ readonly userId: string;
8
+ /** The permissions the user granted your app (access tokens). */
9
+ readonly scopes: readonly string[];
10
+ readonly email: string | null;
11
+ readonly name: string | null;
12
+ /** When the token expires, in milliseconds since the epoch; null where Facebook gives none. */
13
+ readonly expiresAtMs: number | null;
14
+ }
15
+ export interface FacebookAuthenticatorOptions {
16
+ /** Your Facebook app's ID. */
17
+ readonly appId: string;
18
+ /** Your app's secret, to ask Facebook about access tokens; it stays on your server. */
19
+ readonly appSecret: string;
20
+ /** What a Facebook user may do, or null to refuse. */
21
+ readonly identity: (session: FacebookSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
22
+ /** Permissions the user must have granted your app, such as `email`. */
23
+ readonly requiredScopes?: readonly string[];
24
+ /** Also accept iOS Limited Login tokens (OIDC JWTs, checked with Facebook's keys, with no call per request). */
25
+ readonly limitedLogin?: boolean;
26
+ /**
27
+ * Keep what Facebook said about an access token for this long; 0 by default, so each request asks Facebook and a
28
+ * token the user revoked stops at once. At most 5 minutes.
29
+ */
30
+ readonly cacheTtlMs?: number;
31
+ /** The longest wait for Facebook; 5 s by default (1 s to 30 s). */
32
+ readonly timeoutMs?: number;
33
+ /** The Graph API version; `v26.0` by default. */
34
+ readonly graphVersion?: string;
35
+ /** Clock difference allowed for Limited Login tokens; 5 s by default. */
36
+ readonly clockSkewMs?: number;
37
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
38
+ readonly maxIdentityMs?: number;
39
+ /** For tests and proxies: the fetch to use. */
40
+ readonly fetch?: typeof fetch;
41
+ }
42
+ /**
43
+ * A server `authenticate` for Facebook users. Login access tokens are opaque, so each is checked with Facebook's
44
+ * `debug_token` (a call per request unless `cacheTtlMs`): it must be valid, a user's, for your app, and hold the
45
+ * permissions you require. With `limitedLogin`, iOS Limited Login tokens are checked as JWTs: RS256 with Facebook's
46
+ * keys, from `https://www.facebook.com`, for your app. `identity` decides what the user may do.
47
+ */
48
+ export declare function facebookAuthenticator(options: FacebookAuthenticatorOptions): Authenticator;
49
+ /** Facebook sign-in for better-auth's `socialProviders.facebook`, as `facebookSignIn` makes it. */
50
+ export interface FacebookSignInOptions {
51
+ readonly clientId: string;
52
+ readonly clientSecret: string;
53
+ readonly fields: string[];
54
+ readonly scope?: string[];
55
+ }
56
+ /**
57
+ * Facebook sign-in for better-auth (`socialProviders: { facebook: facebookSignIn({ clientId, clientSecret }) }`), reading
58
+ * no more of the profile than signing in needs (`id`, `name`, `email`; `picture` only if asked), and asking for no
59
+ * permissions beyond better-auth's `email` and `public_profile` unless given.
60
+ */
61
+ export declare function facebookSignIn(options: {
62
+ readonly clientId: string;
63
+ readonly clientSecret: string;
64
+ readonly picture?: boolean;
65
+ readonly scopes?: readonly string[];
66
+ }): FacebookSignInOptions;
67
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,aAAa,EAAE,KAAK,aAAa,EACvC,MAAM,aAAa,CAAC;AAErB,4GAA4G;AAC5G,MAAM,WAAW,eAAe;IAC9B,6GAA6G;IAC7G,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,eAAe,CAAC;IAChD,qFAAqF;IACrF,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iEAAiE;IACjE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,+FAA+F;IAC/F,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CACrC;AAED,MAAM,WAAW,4BAA4B;IAC3C,8BAA8B;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,uFAAuF;IACvF,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,QAAQ,EAAE,CAAC,OAAO,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}
package/dist/index.js ADDED
@@ -0,0 +1,123 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { sha256Hex } from 'mayura/core/host';
3
+ import { jwtVerifier, peekIssuer, remoteJwks, serverIdentity, } from 'mayura/auth';
4
+ /** Facebook Login user access tokens: opaque, starting `EA`. */
5
+ const accessToken = /^EA[A-Za-z0-9]{20,1024}$/u;
6
+ const limitedIssuer = 'https://www.facebook.com';
7
+ const text = (value) => typeof value === 'string' && value !== '' ? value : null;
8
+ function bounded(value, name, fallback, min, max) {
9
+ const result = value ?? fallback;
10
+ if (!Number.isSafeInteger(result) || result < min || result > max)
11
+ throw new MayuraError('INVALID_CONFIG', `facebookAuthenticator(): ${name} is ${min.toLocaleString('en-US')} to ${max.toLocaleString('en-US')}.`);
12
+ return result;
13
+ }
14
+ /**
15
+ * A server `authenticate` for Facebook users. Login access tokens are opaque, so each is checked with Facebook's
16
+ * `debug_token` (a call per request unless `cacheTtlMs`): it must be valid, a user's, for your app, and hold the
17
+ * permissions you require. With `limitedLogin`, iOS Limited Login tokens are checked as JWTs: RS256 with Facebook's
18
+ * keys, from `https://www.facebook.com`, for your app. `identity` decides what the user may do.
19
+ */
20
+ export function facebookAuthenticator(options) {
21
+ if (!options || typeof options.identity !== 'function')
22
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): identity decides what a Facebook user may do.');
23
+ if (typeof options.appId !== 'string' || !/^\d{5,20}$/u.test(options.appId))
24
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appId is your Facebook app\'s ID.');
25
+ if (typeof options.appSecret !== 'string' || !/^[A-Za-z0-9]{16,128}$/u.test(options.appSecret))
26
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appSecret is your app\'s secret.');
27
+ const required = options.requiredScopes ?? [];
28
+ if (!Array.isArray(required) || required.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope)))
29
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): requiredScopes are permissions such as email or public_profile.');
30
+ if (options.limitedLogin !== undefined && typeof options.limitedLogin !== 'boolean')
31
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): limitedLogin must be a boolean.');
32
+ const cacheTtlMs = bounded(options.cacheTtlMs, 'cacheTtlMs', 0, 0, 300_000);
33
+ const timeoutMs = bounded(options.timeoutMs, 'timeoutMs', 5_000, 1_000, 30_000);
34
+ const maxIdentityMs = bounded(options.maxIdentityMs, 'maxIdentityMs', 60_000, 1_000, 3_600_000);
35
+ const version = options.graphVersion ?? 'v26.0';
36
+ if (typeof version !== 'string' || !/^v\d{1,3}\.\d{1,2}$/u.test(version))
37
+ throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): graphVersion is a Graph API version such as v26.0.');
38
+ const fetcher = options.fetch ?? globalThis.fetch;
39
+ const appToken = `${options.appId}|${options.appSecret}`;
40
+ const cache = new Map();
41
+ const limited = options.limitedLogin === true ? jwtVerifier({
42
+ issuer: limitedIssuer, audience: options.appId, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,
43
+ keys: remoteJwks({ url: 'https://www.facebook.com/.well-known/oauth/openid/jwks/', ...(options.fetch ? { fetch: options.fetch } : {}) }),
44
+ }) : undefined;
45
+ /** What Facebook says about an access token; null when it is not a valid user token for this app. */
46
+ const inspect = async (token, signal) => {
47
+ const url = `https://graph.facebook.com/${version}/debug_token?${new URLSearchParams({ input_token: token, access_token: appToken })}`;
48
+ let response;
49
+ try {
50
+ response = await fetcher(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]), headers: { accept: 'application/json' }, redirect: 'error' });
51
+ }
52
+ // The URL holds the app secret: no error may carry it.
53
+ catch {
54
+ throw signal.aborted ? new MayuraError('CANCELLED', 'Authentication was cancelled.') : new MayuraError('TOOL_FAILED', 'Facebook could not be reached to check the token.');
55
+ }
56
+ if (!response.ok) {
57
+ void response.body?.cancel().catch(() => undefined);
58
+ throw new MayuraError('TOOL_FAILED', `Facebook answered HTTP ${response.status} when checking the token.`);
59
+ }
60
+ const body = await response.json().catch(() => undefined);
61
+ const data = body?.data;
62
+ if (!data || typeof data !== 'object')
63
+ throw new MayuraError('TOOL_FAILED', 'Facebook\'s answer about the token is not one Mayura knows.');
64
+ if (data['is_valid'] !== true || data['app_id'] !== options.appId || data['type'] !== 'USER' || typeof data['user_id'] !== 'string' || data['user_id'] === '')
65
+ return null;
66
+ const scopes = Array.isArray(data['scopes']) ? data['scopes'].filter((scope) => typeof scope === 'string') : [];
67
+ if (required.some(scope => !scopes.includes(scope)))
68
+ return null;
69
+ const expires = data['expires_at'];
70
+ // 0 is Facebook's "does not expire".
71
+ const expiresAtMs = typeof expires === 'number' && expires > 0 ? expires * 1_000 : null;
72
+ return Object.freeze({ kind: 'access_token', userId: data['user_id'], scopes: Object.freeze(scopes), email: null, name: null, expiresAtMs });
73
+ };
74
+ const accepts = (token) => typeof token === 'string' && (accessToken.test(token) || (limited !== undefined && peekIssuer(token) === limitedIssuer));
75
+ const authenticate = async ({ token, signal }) => {
76
+ if (typeof token !== 'string')
77
+ return null;
78
+ let session = null;
79
+ if (accessToken.test(token)) {
80
+ const key = sha256Hex(token);
81
+ const cached = cache.get(key);
82
+ if (cached && cached.until > Date.now())
83
+ session = cached.session;
84
+ else {
85
+ session = await inspect(token, signal);
86
+ // Without cacheTtlMs an answer is out of date the moment it is kept.
87
+ if (cache.size >= 10_000)
88
+ cache.delete(cache.keys().next().value);
89
+ cache.set(key, { session, until: Date.now() + cacheTtlMs });
90
+ }
91
+ }
92
+ else if (limited !== undefined && peekIssuer(token) === limitedIssuer) {
93
+ const result = await limited.verify(token, { signal });
94
+ if (result.ok && typeof result.claims.sub === 'string' && result.claims.sub !== '') {
95
+ session = Object.freeze({ kind: 'limited_login', userId: result.claims.sub, scopes: Object.freeze([]), email: text(result.claims['email']), name: text(result.claims['name']), expiresAtMs: result.claims.exp * 1_000 });
96
+ }
97
+ }
98
+ if (!session)
99
+ return null;
100
+ return serverIdentity(await options.identity(session), { credentialExpiresAtMs: session.expiresAtMs ?? Number.MAX_SAFE_INTEGER, maxIdentityMs });
101
+ };
102
+ return Object.assign(authenticate, { accepts });
103
+ }
104
+ /**
105
+ * Facebook sign-in for better-auth (`socialProviders: { facebook: facebookSignIn({ clientId, clientSecret }) }`), reading
106
+ * no more of the profile than signing in needs (`id`, `name`, `email`; `picture` only if asked), and asking for no
107
+ * permissions beyond better-auth's `email` and `public_profile` unless given.
108
+ */
109
+ export function facebookSignIn(options) {
110
+ if (!options || typeof options.clientId !== 'string' || !/^\d{5,20}$/u.test(options.clientId))
111
+ throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientId is your Facebook app\'s ID.');
112
+ if (typeof options.clientSecret !== 'string' || options.clientSecret === '')
113
+ throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientSecret is your app\'s secret.');
114
+ if (options.picture !== undefined && typeof options.picture !== 'boolean')
115
+ throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): picture must be a boolean.');
116
+ if (options.scopes !== undefined && (!Array.isArray(options.scopes) || options.scopes.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope))))
117
+ throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): scopes are extra permissions such as user_birthday.');
118
+ return Object.freeze({
119
+ clientId: options.clientId, clientSecret: options.clientSecret, fields: ['id', 'name', 'email', ...(options.picture === true ? ['picture'] : [])],
120
+ ...(options.scopes?.length ? { scope: [...options.scopes] } : {}),
121
+ });
122
+ }
123
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EACL,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,GAEpD,MAAM,aAAa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C,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport { sha256Hex } from 'mayura/core/host';\nimport {\n jwtVerifier, peekIssuer, remoteJwks, serverIdentity,\n type Authenticator, type IdentityGrant,\n} from 'mayura/auth';\n\n/** A verified Facebook user: from a Login access token (checked with Facebook) or a Limited Login token. */\nexport interface FacebookSession {\n /** `access_token` for a Facebook Login user access token; `limited_login` for an iOS Limited Login token. */\n readonly kind: 'access_token' | 'limited_login';\n /** The app-scoped user id: the same user has a different id in each of your apps. */\n readonly userId: string;\n /** The permissions the user granted your app (access tokens). */\n readonly scopes: readonly string[];\n readonly email: string | null;\n readonly name: string | null;\n /** When the token expires, in milliseconds since the epoch; null where Facebook gives none. */\n readonly expiresAtMs: number | null;\n}\n\nexport interface FacebookAuthenticatorOptions {\n /** Your Facebook app's ID. */\n readonly appId: string;\n /** Your app's secret, to ask Facebook about access tokens; it stays on your server. */\n readonly appSecret: string;\n /** What a Facebook user may do, or null to refuse. */\n readonly identity: (session: FacebookSession) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** Permissions the user must have granted your app, such as `email`. */\n readonly requiredScopes?: readonly string[];\n /** Also accept iOS Limited Login tokens (OIDC JWTs, checked with Facebook's keys, with no call per request). */\n readonly limitedLogin?: boolean;\n /**\n * Keep what Facebook said about an access token for this long; 0 by default, so each request asks Facebook and a\n * token the user revoked stops at once. At most 5 minutes.\n */\n readonly cacheTtlMs?: number;\n /** The longest wait for Facebook; 5 s by default (1 s to 30 s). */\n readonly timeoutMs?: number;\n /** The Graph API version; `v26.0` by default. */\n readonly graphVersion?: string;\n /** Clock difference allowed for Limited Login tokens; 5 s by default. */\n readonly clockSkewMs?: number;\n /** The longest an identity lasts before the token is checked again; 60 s by default. */\n readonly maxIdentityMs?: number;\n /** For tests and proxies: the fetch to use. */\n readonly fetch?: typeof fetch;\n}\n\n/** Facebook Login user access tokens: opaque, starting `EA`. */\nconst accessToken = /^EA[A-Za-z0-9]{20,1024}$/u;\nconst limitedIssuer = 'https://www.facebook.com';\nconst text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\n\nfunction bounded(value: number | undefined, name: string, fallback: number, min: number, max: number): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result < min || result > max) throw new MayuraError('INVALID_CONFIG', `facebookAuthenticator(): ${name} is ${min.toLocaleString('en-US')} to ${max.toLocaleString('en-US')}.`);\n return result;\n}\n\n/**\n * A server `authenticate` for Facebook users. Login access tokens are opaque, so each is checked with Facebook's\n * `debug_token` (a call per request unless `cacheTtlMs`): it must be valid, a user's, for your app, and hold the\n * permissions you require. With `limitedLogin`, iOS Limited Login tokens are checked as JWTs: RS256 with Facebook's\n * keys, from `https://www.facebook.com`, for your app. `identity` decides what the user may do.\n */\nexport function facebookAuthenticator(options: FacebookAuthenticatorOptions): Authenticator {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): identity decides what a Facebook user may do.');\n if (typeof options.appId !== 'string' || !/^\\d{5,20}$/u.test(options.appId)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appId is your Facebook app\\'s ID.');\n if (typeof options.appSecret !== 'string' || !/^[A-Za-z0-9]{16,128}$/u.test(options.appSecret)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appSecret is your app\\'s secret.');\n const required = options.requiredScopes ?? [];\n if (!Array.isArray(required) || required.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope))) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): requiredScopes are permissions such as email or public_profile.');\n if (options.limitedLogin !== undefined && typeof options.limitedLogin !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): limitedLogin must be a boolean.');\n const cacheTtlMs = bounded(options.cacheTtlMs, 'cacheTtlMs', 0, 0, 300_000);\n const timeoutMs = bounded(options.timeoutMs, 'timeoutMs', 5_000, 1_000, 30_000);\n const maxIdentityMs = bounded(options.maxIdentityMs, 'maxIdentityMs', 60_000, 1_000, 3_600_000);\n const version = options.graphVersion ?? 'v26.0';\n if (typeof version !== 'string' || !/^v\\d{1,3}\\.\\d{1,2}$/u.test(version)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): graphVersion is a Graph API version such as v26.0.');\n const fetcher = options.fetch ?? globalThis.fetch;\n const appToken = `${options.appId}|${options.appSecret}`;\n const cache = new Map<string, { readonly session: FacebookSession | null; readonly until: number }>();\n const limited = options.limitedLogin === true ? jwtVerifier({\n issuer: limitedIssuer, audience: options.appId, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,\n keys: remoteJwks({ url: 'https://www.facebook.com/.well-known/oauth/openid/jwks/', ...(options.fetch ? { fetch: options.fetch } : {}) }),\n }) : undefined;\n\n /** What Facebook says about an access token; null when it is not a valid user token for this app. */\n const inspect = async (token: string, signal: AbortSignal): Promise<FacebookSession | null> => {\n const url = `https://graph.facebook.com/${version}/debug_token?${new URLSearchParams({ input_token: token, access_token: appToken })}`;\n let response: Response;\n try { response = await fetcher(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]), headers: { accept: 'application/json' }, redirect: 'error' }); }\n // The URL holds the app secret: no error may carry it.\n catch { throw signal.aborted ? new MayuraError('CANCELLED', 'Authentication was cancelled.') : new MayuraError('TOOL_FAILED', 'Facebook could not be reached to check the token.'); }\n if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new MayuraError('TOOL_FAILED', `Facebook answered HTTP ${response.status} when checking the token.`); }\n const body = await response.json().catch(() => undefined) as { data?: Record<string, unknown> } | undefined;\n const data = body?.data;\n if (!data || typeof data !== 'object') throw new MayuraError('TOOL_FAILED', 'Facebook\\'s answer about the token is not one Mayura knows.');\n if (data['is_valid'] !== true || data['app_id'] !== options.appId || data['type'] !== 'USER' || typeof data['user_id'] !== 'string' || data['user_id'] === '') return null;\n const scopes = Array.isArray(data['scopes']) ? data['scopes'].filter((scope): scope is string => typeof scope === 'string') : [];\n if (required.some(scope => !scopes.includes(scope))) return null;\n const expires = data['expires_at'];\n // 0 is Facebook's \"does not expire\".\n const expiresAtMs = typeof expires === 'number' && expires > 0 ? expires * 1_000 : null;\n return Object.freeze({ kind: 'access_token' as const, userId: data['user_id'], scopes: Object.freeze(scopes), email: null, name: null, expiresAtMs });\n };\n\n const accepts = (token: string) => typeof token === 'string' && (accessToken.test(token) || (limited !== undefined && peekIssuer(token) === limitedIssuer));\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }) => {\n if (typeof token !== 'string') return null;\n let session: FacebookSession | null = null;\n if (accessToken.test(token)) {\n const key = sha256Hex(token); const cached = cache.get(key);\n if (cached && cached.until > Date.now()) session = cached.session;\n else {\n session = await inspect(token, signal);\n // Without cacheTtlMs an answer is out of date the moment it is kept.\n if (cache.size >= 10_000) cache.delete(cache.keys().next().value!);\n cache.set(key, { session, until: Date.now() + cacheTtlMs });\n }\n } else if (limited !== undefined && peekIssuer(token) === limitedIssuer) {\n const result = await limited.verify(token, { signal });\n if (result.ok && typeof result.claims.sub === 'string' && result.claims.sub !== '') {\n session = Object.freeze({ kind: 'limited_login' as const, userId: result.claims.sub, scopes: Object.freeze([]), email: text(result.claims['email']), name: text(result.claims['name']), expiresAtMs: result.claims.exp * 1_000 });\n }\n }\n if (!session) return null;\n return serverIdentity(await options.identity(session), { credentialExpiresAtMs: session.expiresAtMs ?? Number.MAX_SAFE_INTEGER, maxIdentityMs });\n };\n return Object.assign(authenticate, { accepts });\n}\n\n/** Facebook sign-in for better-auth's `socialProviders.facebook`, as `facebookSignIn` makes it. */\nexport interface FacebookSignInOptions {\n readonly clientId: string;\n readonly clientSecret: string;\n readonly fields: string[];\n readonly scope?: string[];\n}\n\n/**\n * Facebook sign-in for better-auth (`socialProviders: { facebook: facebookSignIn({ clientId, clientSecret }) }`), reading\n * no more of the profile than signing in needs (`id`, `name`, `email`; `picture` only if asked), and asking for no\n * permissions beyond better-auth's `email` and `public_profile` unless given.\n */\nexport function facebookSignIn(options: { readonly clientId: string; readonly clientSecret: string; readonly picture?: boolean; readonly scopes?: readonly string[] }): FacebookSignInOptions {\n if (!options || typeof options.clientId !== 'string' || !/^\\d{5,20}$/u.test(options.clientId)) throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientId is your Facebook app\\'s ID.');\n if (typeof options.clientSecret !== 'string' || options.clientSecret === '') throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientSecret is your app\\'s secret.');\n if (options.picture !== undefined && typeof options.picture !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): picture must be a boolean.');\n if (options.scopes !== undefined && (!Array.isArray(options.scopes) || options.scopes.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope)))) throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): scopes are extra permissions such as user_birthday.');\n return Object.freeze({\n clientId: options.clientId, clientSecret: options.clientSecret, fields: ['id', 'name', 'email', ...(options.picture === true ? ['picture'] : [])],\n ...(options.scopes?.length ? { scope: [...options.scopes] } : {}),\n });\n}\n\n"]}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@mayurajs/auth-facebook",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Facebook Login access tokens (checked with Facebook) and Limited Login tokens as Mayura server identities, and a preset for better-auth's Facebook sign-in.",
5
+ "author": {
6
+ "name": "Aryabh",
7
+ "email": "dev@rokad.co"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/KartikeyAI/mayura.git",
13
+ "directory": "extensions/auth-facebook"
14
+ },
15
+ "homepage": "https://github.com/KartikeyAI/mayura#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/KartikeyAI/mayura/issues"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=22.12.0 <23 || >=24.14.1 <25"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src/**/*.ts",
33
+ "README.md",
34
+ "LICENSE",
35
+ "NOTICE"
36
+ ],
37
+ "dependencies": {},
38
+ "peerDependencies": {
39
+ "mayura": "^1.2.0"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,155 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { sha256Hex } from 'mayura/core/host';
3
+ import {
4
+ jwtVerifier, peekIssuer, remoteJwks, serverIdentity,
5
+ type Authenticator, type IdentityGrant,
6
+ } from 'mayura/auth';
7
+
8
+ /** A verified Facebook user: from a Login access token (checked with Facebook) or a Limited Login token. */
9
+ export interface FacebookSession {
10
+ /** `access_token` for a Facebook Login user access token; `limited_login` for an iOS Limited Login token. */
11
+ readonly kind: 'access_token' | 'limited_login';
12
+ /** The app-scoped user id: the same user has a different id in each of your apps. */
13
+ readonly userId: string;
14
+ /** The permissions the user granted your app (access tokens). */
15
+ readonly scopes: readonly string[];
16
+ readonly email: string | null;
17
+ readonly name: string | null;
18
+ /** When the token expires, in milliseconds since the epoch; null where Facebook gives none. */
19
+ readonly expiresAtMs: number | null;
20
+ }
21
+
22
+ export interface FacebookAuthenticatorOptions {
23
+ /** Your Facebook app's ID. */
24
+ readonly appId: string;
25
+ /** Your app's secret, to ask Facebook about access tokens; it stays on your server. */
26
+ readonly appSecret: string;
27
+ /** What a Facebook user may do, or null to refuse. */
28
+ readonly identity: (session: FacebookSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
29
+ /** Permissions the user must have granted your app, such as `email`. */
30
+ readonly requiredScopes?: readonly string[];
31
+ /** Also accept iOS Limited Login tokens (OIDC JWTs, checked with Facebook's keys, with no call per request). */
32
+ readonly limitedLogin?: boolean;
33
+ /**
34
+ * Keep what Facebook said about an access token for this long; 0 by default, so each request asks Facebook and a
35
+ * token the user revoked stops at once. At most 5 minutes.
36
+ */
37
+ readonly cacheTtlMs?: number;
38
+ /** The longest wait for Facebook; 5 s by default (1 s to 30 s). */
39
+ readonly timeoutMs?: number;
40
+ /** The Graph API version; `v26.0` by default. */
41
+ readonly graphVersion?: string;
42
+ /** Clock difference allowed for Limited Login tokens; 5 s by default. */
43
+ readonly clockSkewMs?: number;
44
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
45
+ readonly maxIdentityMs?: number;
46
+ /** For tests and proxies: the fetch to use. */
47
+ readonly fetch?: typeof fetch;
48
+ }
49
+
50
+ /** Facebook Login user access tokens: opaque, starting `EA`. */
51
+ const accessToken = /^EA[A-Za-z0-9]{20,1024}$/u;
52
+ const limitedIssuer = 'https://www.facebook.com';
53
+ const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
54
+
55
+ function bounded(value: number | undefined, name: string, fallback: number, min: number, max: number): number {
56
+ const result = value ?? fallback;
57
+ if (!Number.isSafeInteger(result) || result < min || result > max) throw new MayuraError('INVALID_CONFIG', `facebookAuthenticator(): ${name} is ${min.toLocaleString('en-US')} to ${max.toLocaleString('en-US')}.`);
58
+ return result;
59
+ }
60
+
61
+ /**
62
+ * A server `authenticate` for Facebook users. Login access tokens are opaque, so each is checked with Facebook's
63
+ * `debug_token` (a call per request unless `cacheTtlMs`): it must be valid, a user's, for your app, and hold the
64
+ * permissions you require. With `limitedLogin`, iOS Limited Login tokens are checked as JWTs: RS256 with Facebook's
65
+ * keys, from `https://www.facebook.com`, for your app. `identity` decides what the user may do.
66
+ */
67
+ export function facebookAuthenticator(options: FacebookAuthenticatorOptions): Authenticator {
68
+ if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): identity decides what a Facebook user may do.');
69
+ if (typeof options.appId !== 'string' || !/^\d{5,20}$/u.test(options.appId)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appId is your Facebook app\'s ID.');
70
+ if (typeof options.appSecret !== 'string' || !/^[A-Za-z0-9]{16,128}$/u.test(options.appSecret)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): appSecret is your app\'s secret.');
71
+ const required = options.requiredScopes ?? [];
72
+ if (!Array.isArray(required) || required.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope))) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): requiredScopes are permissions such as email or public_profile.');
73
+ if (options.limitedLogin !== undefined && typeof options.limitedLogin !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): limitedLogin must be a boolean.');
74
+ const cacheTtlMs = bounded(options.cacheTtlMs, 'cacheTtlMs', 0, 0, 300_000);
75
+ const timeoutMs = bounded(options.timeoutMs, 'timeoutMs', 5_000, 1_000, 30_000);
76
+ const maxIdentityMs = bounded(options.maxIdentityMs, 'maxIdentityMs', 60_000, 1_000, 3_600_000);
77
+ const version = options.graphVersion ?? 'v26.0';
78
+ if (typeof version !== 'string' || !/^v\d{1,3}\.\d{1,2}$/u.test(version)) throw new MayuraError('INVALID_CONFIG', 'facebookAuthenticator(): graphVersion is a Graph API version such as v26.0.');
79
+ const fetcher = options.fetch ?? globalThis.fetch;
80
+ const appToken = `${options.appId}|${options.appSecret}`;
81
+ const cache = new Map<string, { readonly session: FacebookSession | null; readonly until: number }>();
82
+ const limited = options.limitedLogin === true ? jwtVerifier({
83
+ issuer: limitedIssuer, audience: options.appId, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,
84
+ keys: remoteJwks({ url: 'https://www.facebook.com/.well-known/oauth/openid/jwks/', ...(options.fetch ? { fetch: options.fetch } : {}) }),
85
+ }) : undefined;
86
+
87
+ /** What Facebook says about an access token; null when it is not a valid user token for this app. */
88
+ const inspect = async (token: string, signal: AbortSignal): Promise<FacebookSession | null> => {
89
+ const url = `https://graph.facebook.com/${version}/debug_token?${new URLSearchParams({ input_token: token, access_token: appToken })}`;
90
+ let response: Response;
91
+ try { response = await fetcher(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]), headers: { accept: 'application/json' }, redirect: 'error' }); }
92
+ // The URL holds the app secret: no error may carry it.
93
+ catch { throw signal.aborted ? new MayuraError('CANCELLED', 'Authentication was cancelled.') : new MayuraError('TOOL_FAILED', 'Facebook could not be reached to check the token.'); }
94
+ if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new MayuraError('TOOL_FAILED', `Facebook answered HTTP ${response.status} when checking the token.`); }
95
+ const body = await response.json().catch(() => undefined) as { data?: Record<string, unknown> } | undefined;
96
+ const data = body?.data;
97
+ if (!data || typeof data !== 'object') throw new MayuraError('TOOL_FAILED', 'Facebook\'s answer about the token is not one Mayura knows.');
98
+ if (data['is_valid'] !== true || data['app_id'] !== options.appId || data['type'] !== 'USER' || typeof data['user_id'] !== 'string' || data['user_id'] === '') return null;
99
+ const scopes = Array.isArray(data['scopes']) ? data['scopes'].filter((scope): scope is string => typeof scope === 'string') : [];
100
+ if (required.some(scope => !scopes.includes(scope))) return null;
101
+ const expires = data['expires_at'];
102
+ // 0 is Facebook's "does not expire".
103
+ const expiresAtMs = typeof expires === 'number' && expires > 0 ? expires * 1_000 : null;
104
+ return Object.freeze({ kind: 'access_token' as const, userId: data['user_id'], scopes: Object.freeze(scopes), email: null, name: null, expiresAtMs });
105
+ };
106
+
107
+ const accepts = (token: string) => typeof token === 'string' && (accessToken.test(token) || (limited !== undefined && peekIssuer(token) === limitedIssuer));
108
+ const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }) => {
109
+ if (typeof token !== 'string') return null;
110
+ let session: FacebookSession | null = null;
111
+ if (accessToken.test(token)) {
112
+ const key = sha256Hex(token); const cached = cache.get(key);
113
+ if (cached && cached.until > Date.now()) session = cached.session;
114
+ else {
115
+ session = await inspect(token, signal);
116
+ // Without cacheTtlMs an answer is out of date the moment it is kept.
117
+ if (cache.size >= 10_000) cache.delete(cache.keys().next().value!);
118
+ cache.set(key, { session, until: Date.now() + cacheTtlMs });
119
+ }
120
+ } else if (limited !== undefined && peekIssuer(token) === limitedIssuer) {
121
+ const result = await limited.verify(token, { signal });
122
+ if (result.ok && typeof result.claims.sub === 'string' && result.claims.sub !== '') {
123
+ session = Object.freeze({ kind: 'limited_login' as const, userId: result.claims.sub, scopes: Object.freeze([]), email: text(result.claims['email']), name: text(result.claims['name']), expiresAtMs: result.claims.exp * 1_000 });
124
+ }
125
+ }
126
+ if (!session) return null;
127
+ return serverIdentity(await options.identity(session), { credentialExpiresAtMs: session.expiresAtMs ?? Number.MAX_SAFE_INTEGER, maxIdentityMs });
128
+ };
129
+ return Object.assign(authenticate, { accepts });
130
+ }
131
+
132
+ /** Facebook sign-in for better-auth's `socialProviders.facebook`, as `facebookSignIn` makes it. */
133
+ export interface FacebookSignInOptions {
134
+ readonly clientId: string;
135
+ readonly clientSecret: string;
136
+ readonly fields: string[];
137
+ readonly scope?: string[];
138
+ }
139
+
140
+ /**
141
+ * Facebook sign-in for better-auth (`socialProviders: { facebook: facebookSignIn({ clientId, clientSecret }) }`), reading
142
+ * no more of the profile than signing in needs (`id`, `name`, `email`; `picture` only if asked), and asking for no
143
+ * permissions beyond better-auth's `email` and `public_profile` unless given.
144
+ */
145
+ export function facebookSignIn(options: { readonly clientId: string; readonly clientSecret: string; readonly picture?: boolean; readonly scopes?: readonly string[] }): FacebookSignInOptions {
146
+ if (!options || typeof options.clientId !== 'string' || !/^\d{5,20}$/u.test(options.clientId)) throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientId is your Facebook app\'s ID.');
147
+ if (typeof options.clientSecret !== 'string' || options.clientSecret === '') throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): clientSecret is your app\'s secret.');
148
+ if (options.picture !== undefined && typeof options.picture !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): picture must be a boolean.');
149
+ if (options.scopes !== undefined && (!Array.isArray(options.scopes) || options.scopes.some(scope => typeof scope !== 'string' || !/^[a-z_]{1,64}$/u.test(scope)))) throw new MayuraError('INVALID_CONFIG', 'facebookSignIn(): scopes are extra permissions such as user_birthday.');
150
+ return Object.freeze({
151
+ clientId: options.clientId, clientSecret: options.clientSecret, fields: ['id', 'name', 'email', ...(options.picture === true ? ['picture'] : [])],
152
+ ...(options.scopes?.length ? { scope: [...options.scopes] } : {}),
153
+ });
154
+ }
155
+