cloudfire-auth 0.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +13 -0
  3. package/README.md +94 -0
  4. package/dist/CloudFireAuth.d.ts +291 -0
  5. package/dist/CloudFireAuth.js +346 -0
  6. package/dist/google-auth/get-oauth-2-token.d.ts +15 -0
  7. package/dist/google-auth/get-oauth-2-token.js +66 -0
  8. package/dist/index.d.ts +2 -0
  9. package/dist/index.js +2 -0
  10. package/dist/rest-api/create-user.d.ts +2 -0
  11. package/dist/rest-api/create-user.js +3 -0
  12. package/dist/rest-api/delete-user.d.ts +175 -0
  13. package/dist/rest-api/delete-user.js +207 -0
  14. package/dist/rest-api/delete-users.d.ts +2 -0
  15. package/dist/rest-api/delete-users.js +3 -0
  16. package/dist/rest-api/get-user-by-email.d.ts +2 -0
  17. package/dist/rest-api/get-user-by-email.js +3 -0
  18. package/dist/rest-api/get-user-by-phone-number.d.ts +2 -0
  19. package/dist/rest-api/get-user-by-phone-number.js +3 -0
  20. package/dist/rest-api/get-user-by-provider-uid.d.ts +2 -0
  21. package/dist/rest-api/get-user-by-provider-uid.js +3 -0
  22. package/dist/rest-api/get-user.d.ts +99 -0
  23. package/dist/rest-api/get-user.js +177 -0
  24. package/dist/rest-api/get-users.d.ts +2 -0
  25. package/dist/rest-api/get-users.js +3 -0
  26. package/dist/rest-api/list-users.d.ts +2 -0
  27. package/dist/rest-api/list-users.js +3 -0
  28. package/dist/rest-api/revoke-refresh-tokens.d.ts +116 -0
  29. package/dist/rest-api/revoke-refresh-tokens.js +151 -0
  30. package/dist/rest-api/set-custom-user-claims.d.ts +173 -0
  31. package/dist/rest-api/set-custom-user-claims.js +261 -0
  32. package/dist/rest-api/standard-request.d.ts +12 -0
  33. package/dist/rest-api/standard-request.js +20 -0
  34. package/dist/rest-api/update-user.d.ts +175 -0
  35. package/dist/rest-api/update-user.js +375 -0
  36. package/dist/rest-api/verify-id-token.d.ts +127 -0
  37. package/dist/rest-api/verify-id-token.js +273 -0
  38. package/dist/rest-api/verify-session-cookie.d.ts +2 -0
  39. package/dist/rest-api/verify-session-cookie.js +3 -0
  40. package/dist/types/firebase-admin/auth-config.d.ts +851 -0
  41. package/dist/types/firebase-admin/auth-config.js +1 -0
  42. package/dist/types/firebase-admin/identifier.d.ts +57 -0
  43. package/dist/types/firebase-admin/identifier.js +1 -0
  44. package/dist/types/firebase-admin/index.d.ts +153 -0
  45. package/dist/types/firebase-admin/index.js +1 -0
  46. package/dist/types/firebase-admin/token-verifier.d.ts +219 -0
  47. package/dist/types/firebase-admin/token-verifier.js +1 -0
  48. package/dist/types/firebase-admin/user-record.d.ts +289 -0
  49. package/dist/types/firebase-admin/user-record.js +1 -0
  50. package/dist/types/google-auth.d.ts +25 -0
  51. package/dist/types/google-auth.js +1 -0
  52. package/dist/types/service-account-key.d.ts +13 -0
  53. package/dist/types/service-account-key.js +1 -0
  54. package/dist/types.d.ts +6 -0
  55. package/dist/types.js +1 -0
  56. package/package.json +56 -0
  57. package/third_party/firebase-admin-license.txt +201 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-Present Connor Skelland
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ This software incorporates code from the following third-party components:
2
+
3
+ -------------------------------------------------------------------------
4
+
5
+ 1. Component: firebase-admin
6
+ Copyright 2021 Google Inc.
7
+
8
+ This component is licensed under the Apache License, Version 2.0.
9
+ The full text of the license can be found in the LICENSE file
10
+ distributed with this software.
11
+
12
+ The original source code can be found at:
13
+ https://github.com/firebase/firebase-admin-node
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # Cloudfire Auth
2
+
3
+ A library to make Firebase Auth work in Cloudflare Workers, using native Cloudflare APIs for caching and persistence. The library handles OAuth2 token generation and interactions with the Firebase Auth REST API.
4
+
5
+ ## Features
6
+
7
+ - 🔥 Firebase Auth compatibility for Cloudflare Workers
8
+ - ⚡ Native Cloudflare KV integration for token caching
9
+ - 🛡️ Full TypeScript support
10
+ - 📦 One dependency, jose for JWT handling
11
+ - 🌐 ESM-only for modern JavaScript environments
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install cloudfire-auth
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```typescript
22
+ import { CloudFireAuth, ServiceAccountKey } from "cloudfire-auth";
23
+
24
+ // Initialize with your Firebase project credentials
25
+ const auth = new CloudFireAuth(
26
+ "your-firebase-project-id",
27
+ {
28
+ // Your Firebase service account key
29
+ private_key: "-----BEGIN PRIVATE KEY-----\n...",
30
+ client_email: "firebase-adminsdk-...@your-project.iam.gserviceaccount.com",
31
+ // ... other service account fields
32
+ },
33
+ env.YOUR_KV_NAMESPACE // Optional: KV namespace for token caching
34
+ );
35
+
36
+ // Verify an ID token
37
+ try {
38
+ const decodedToken = await auth.verifyIdToken(idToken);
39
+ console.log("User ID:", decodedToken.uid);
40
+ } catch (error) {
41
+ console.error("Token verification failed:", error);
42
+ }
43
+
44
+ // Get user data
45
+ const user = await auth.getUser("user-uid");
46
+ console.log("User email:", user.email);
47
+ ```
48
+
49
+ ## API Reference
50
+
51
+ ### Constructor
52
+
53
+ ```typescript
54
+ new CloudFireAuth(projectId: string, serviceAccountKey: ServiceAccountKey, kvNamespace?: KVNamespace)
55
+ ```
56
+
57
+ - `projectId`: Your Firebase project ID
58
+ - `serviceAccountKey`: Firebase service account credentials
59
+ - `kvNamespace`: Optional KV namespace for OAuth2 token caching
60
+
61
+ ### Methods
62
+
63
+ | Category | Method | Status | Description |
64
+ | -------------------- | -------------------------------------------------------------------- | ------ | ------------------------------------ |
65
+ | **Authentication** | `verifyIdToken(idToken: string, checkRevoked?: boolean)` | ✅ | Verify Firebase ID tokens |
66
+ | | `verifySessionCookie(sessionCookie: string, checkRevoked?: boolean)` | ✅ | Verify session cookies |
67
+ | **User Management** | `getUser(uid: string)` | ✅ | Get user by UID |
68
+ | | `getUserByEmail(email: string)` | ❌ | Get user by email |
69
+ | | `getUserByPhoneNumber(phoneNumber: string)` | ❌ | Get user by phone number |
70
+ | | `getUserByProviderUid(providerId: string, uid: string)` | ❌ | Get user by provider UID |
71
+ | | `getUsers(identifiers: UserIdentifier[])` | ❌ | Get users by identifiers |
72
+ | | `createUser(properties: CreateRequest)` | ❌ | Create a new user |
73
+ | | `updateUser(uid: string, properties: UpdateRequest)` | ✅ | Update existing user |
74
+ | | `deleteUser(uid: string)` | ✅ | Delete a user |
75
+ | | `deleteUsers(uids: string[])` | ❌ | Delete multiple users |
76
+ | | `listUsers(maxResults?: number, pageToken?: string)` | ❌ | List users with pagination |
77
+ | **Token Management** | `revokeRefreshTokens(uid: string)` | ✅ | Revoke all refresh tokens for a user |
78
+ | | `setCustomUserClaims(uid: string, customUserClaims: object \| null)` | ✅ | Set custom claims |
79
+
80
+ ## Environment Setup
81
+
82
+ Your Cloudflare Worker needs these environment variables:
83
+
84
+ - `FIREBASE_PROJECT_ID`: Your Firebase project ID
85
+ - `FIREBASE_SERVICE_ACCOUNT_KEY`: JSON string of your service account key
86
+ - `AUTH_KV_NAMESPACE`: (Optional) KV namespace for token caching
87
+
88
+ ## License
89
+
90
+ MIT © Connor Skelland
91
+
92
+ ## Contributing
93
+
94
+ Issues and pull requests are welcome!
@@ -0,0 +1,291 @@
1
+ /*! firebase-admin v13.4.0 */
2
+ /*!
3
+ * Copyright 2021 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Alterations to Firebase Admin SDK Code
19
+ *
20
+ * The code covered by the above notice in this file are the method names inside of
21
+ * the CloudFireAuth class and their corresponding doc headers. The code inside each
22
+ * of the methods is under the MIT License attached to this project.
23
+ *
24
+ * Furthermore the following class methods and their doc headers are also under the MIT
25
+ * license:
26
+ *
27
+ * - getOauth2AccessToken
28
+ *
29
+ */
30
+ import type { DecodedIdToken, UserRecord, UserIdentifier, GetUsersResult, ListUsersResult, CreateRequest, UpdateRequest, DeleteUsersResult, ServiceAccountKey } from "./types.js";
31
+ export declare class CloudFireAuth {
32
+ private projectId;
33
+ private serviceAccountKey;
34
+ private oauth2Token?;
35
+ private kvNamespace?;
36
+ constructor(serviceAccountKey: ServiceAccountKey, kvNamespace?: KVNamespace);
37
+ /**
38
+ * Verifies a Firebase ID token (JWT). If the token is valid, the promise is
39
+ * fulfilled with the token's decoded claims; otherwise, the promise is
40
+ * rejected.
41
+ *
42
+ * If `checkRevoked` is set to true, first verifies whether the corresponding
43
+ * user is disabled. If yes, an `auth/user-disabled` error is thrown. If no,
44
+ * verifies if the session corresponding to the ID token was revoked. If the
45
+ * corresponding user's session was invalidated, an `auth/id-token-revoked`
46
+ * error is thrown. If not specified the check is not applied.
47
+ *
48
+ * See {@link https://firebase.google.com/docs/auth/admin/verify-id-tokens | Verify ID Tokens}
49
+ * for code samples and detailed documentation.
50
+ *
51
+ * @param idToken - The ID token to verify.
52
+ * @param checkRevoked - Whether to check if the ID token was revoked.
53
+ * This requires an extra request to the Firebase Auth backend to check
54
+ * the `tokensValidAfterTime` time for the corresponding user.
55
+ * When not specified, this additional check is not applied.
56
+ *
57
+ * @returns A promise fulfilled with the
58
+ * token's decoded claims if the ID token is valid; otherwise, a rejected
59
+ * promise.
60
+ */
61
+ verifyIdToken(idToken: string, checkRevoked?: boolean): Promise<DecodedIdToken>;
62
+ /**
63
+ * Gets the user data for the user corresponding to a given `uid`.
64
+ *
65
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data}
66
+ * for code samples and detailed documentation.
67
+ *
68
+ * @param uid - The `uid` corresponding to the user whose data to fetch.
69
+ *
70
+ * @returns A promise fulfilled with the user
71
+ * data corresponding to the provided `uid`.
72
+ */
73
+ getUser(uid: string): Promise<UserRecord>;
74
+ /**
75
+ * Gets the user data for the user corresponding to a given email.
76
+ *
77
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data}
78
+ * for code samples and detailed documentation.
79
+ *
80
+ * @param email - The email corresponding to the user whose data to
81
+ * fetch.
82
+ *
83
+ * @returns A promise fulfilled with the user
84
+ * data corresponding to the provided email.
85
+ */
86
+ getUserByEmail(email: string): Promise<UserRecord>;
87
+ /**
88
+ * Gets the user data for the user corresponding to a given phone number. The
89
+ * phone number has to conform to the E.164 specification.
90
+ *
91
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data}
92
+ * for code samples and detailed documentation.
93
+ *
94
+ * @param phoneNumber - The phone number corresponding to the user whose
95
+ * data to fetch.
96
+ *
97
+ * @returns A promise fulfilled with the user
98
+ * data corresponding to the provided phone number.
99
+ */
100
+ getUserByPhoneNumber(phoneNumber: string): Promise<UserRecord>;
101
+ /**
102
+ * Gets the user data for the user corresponding to a given provider id.
103
+ *
104
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data}
105
+ * for code samples and detailed documentation.
106
+ *
107
+ * @param providerId - The provider ID, for example, "google.com" for the
108
+ * Google provider.
109
+ * @param uid - The user identifier for the given provider.
110
+ *
111
+ * @returns A promise fulfilled with the user data corresponding to the
112
+ * given provider id.
113
+ */
114
+ getUserByProviderUid(providerId: string, uid: string): Promise<UserRecord>;
115
+ /**
116
+ * Gets the user data corresponding to the specified identifiers.
117
+ *
118
+ * There are no ordering guarantees; in particular, the nth entry in the result list is not
119
+ * guaranteed to correspond to the nth entry in the input parameters list.
120
+ *
121
+ * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied,
122
+ * this method throws a FirebaseAuthError.
123
+ *
124
+ * @param identifiers - The identifiers used to indicate which user records should be returned.
125
+ * Must not have more than 100 entries.
126
+ * @returns A promise that resolves to the corresponding user records.
127
+ * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100
128
+ * identifiers are specified.
129
+ */
130
+ getUsers(identifiers: UserIdentifier[]): Promise<GetUsersResult>;
131
+ /**
132
+ * Retrieves a list of users (single batch only) with a size of `maxResults`
133
+ * starting from the offset as specified by `pageToken`. This is used to
134
+ * retrieve all the users of a specified project in batches.
135
+ *
136
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#list_all_users | List all users}
137
+ * for code samples and detailed documentation.
138
+ *
139
+ * @param maxResults - The page size, 1000 if undefined. This is also
140
+ * the maximum allowed limit.
141
+ * @param pageToken - The next page token. If not specified, returns
142
+ * users starting without any offset.
143
+ * @returns A promise that resolves with
144
+ * the current batch of downloaded users and the next page token.
145
+ */
146
+ listUsers(maxResults?: number, pageToken?: string): Promise<ListUsersResult>;
147
+ /**
148
+ * Creates a new user.
149
+ *
150
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | Create a user}
151
+ * for code samples and detailed documentation.
152
+ *
153
+ * @param properties - The properties to set on the
154
+ * new user record to be created.
155
+ *
156
+ * @returns A promise fulfilled with the user
157
+ * data corresponding to the newly created user.
158
+ */
159
+ createUser(properties: CreateRequest): Promise<UserRecord>;
160
+ /**
161
+ * Deletes an existing user.
162
+ *
163
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user | Delete a user}
164
+ * for code samples and detailed documentation.
165
+ *
166
+ * @param uid - The `uid` corresponding to the user to delete.
167
+ *
168
+ * @returns An empty promise fulfilled once the user has been
169
+ * deleted.
170
+ */
171
+ deleteUser(uid: string): Promise<void>;
172
+ /**
173
+ * Deletes the users specified by the given uids.
174
+ *
175
+ * Deleting a non-existing user won't generate an error (i.e. this method
176
+ * is idempotent.) Non-existing users are considered to be successfully
177
+ * deleted, and are therefore counted in the
178
+ * `DeleteUsersResult.successCount` value.
179
+ *
180
+ * Only a maximum of 1000 identifiers may be supplied. If more than 1000
181
+ * identifiers are supplied, this method throws a FirebaseAuthError.
182
+ *
183
+ * This API is currently rate limited at the server to 1 QPS. If you exceed
184
+ * this, you may get a quota exceeded error. Therefore, if you want to
185
+ * delete more than 1000 users, you may need to add a delay to ensure you
186
+ * don't go over this limit.
187
+ *
188
+ * @param uids - The `uids` corresponding to the users to delete.
189
+ *
190
+ * @returns A Promise that resolves to the total number of successful/failed
191
+ * deletions, as well as the array of errors that corresponds to the
192
+ * failed deletions.
193
+ */
194
+ deleteUsers(uids: string[]): Promise<DeleteUsersResult>;
195
+ /**
196
+ * Updates an existing user.
197
+ *
198
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-users#update_a_user | Update a user}
199
+ * for code samples and detailed documentation.
200
+ *
201
+ * @param uid - The `uid` corresponding to the user to update.
202
+ * @param properties - The properties to update on
203
+ * the provided user.
204
+ *
205
+ * @returns A promise fulfilled with the
206
+ * updated user data.
207
+ */
208
+ updateUser(uid: string, properties: UpdateRequest): Promise<UserRecord>;
209
+ /**
210
+ * Sets additional developer claims on an existing user identified by the
211
+ * provided `uid`, typically used to define user roles and levels of
212
+ * access. These claims should propagate to all devices where the user is
213
+ * already signed in (after token expiration or when token refresh is forced)
214
+ * and the next time the user signs in. If a reserved OIDC claim name
215
+ * is used (sub, iat, iss, etc), an error is thrown. They are set on the
216
+ * authenticated user's ID token JWT.
217
+ *
218
+ * See {@link https://firebase.google.com/docs/auth/admin/custom-claims |
219
+ * Defining user roles and access levels}
220
+ * for code samples and detailed documentation.
221
+ *
222
+ * @param uid - The `uid` of the user to edit.
223
+ * @param customUserClaims - The developer claims to set. If null is
224
+ * passed, existing custom claims are deleted. Passing a custom claims payload
225
+ * larger than 1000 bytes will throw an error. Custom claims are added to the
226
+ * user's ID token which is transmitted on every authenticated request.
227
+ * For profile non-access related user attributes, use database or other
228
+ * separate storage systems.
229
+ * @returns A promise that resolves when the operation completes
230
+ * successfully.
231
+ */
232
+ setCustomUserClaims(uid: string, customUserClaims: object | null): Promise<void>;
233
+ /**
234
+ * Revokes all refresh tokens for an existing user.
235
+ *
236
+ * This API will update the user's {@link UserRecord.tokensValidAfterTime} to
237
+ * the current UTC. It is important that the server on which this is called has
238
+ * its clock set correctly and synchronized.
239
+ *
240
+ * While this will revoke all sessions for a specified user and disable any
241
+ * new ID tokens for existing sessions from getting minted, existing ID tokens
242
+ * may remain active until their natural expiration (one hour). To verify that
243
+ * ID tokens are revoked, use {@link BaseAuth.verifyIdToken}
244
+ * where `checkRevoked` is set to true.
245
+ *
246
+ * @param uid - The `uid` corresponding to the user whose refresh tokens
247
+ * are to be revoked.
248
+ *
249
+ * @returns An empty promise fulfilled once the user's refresh
250
+ * tokens have been revoked.
251
+ */
252
+ revokeRefreshTokens(uid: string): Promise<void>;
253
+ /**
254
+ * Verifies a Firebase session cookie. Returns a Promise with the cookie claims.
255
+ * Rejects the promise if the cookie could not be verified.
256
+ *
257
+ * If `checkRevoked` is set to true, first verifies whether the corresponding
258
+ * user is disabled: If yes, an `auth/user-disabled` error is thrown. If no,
259
+ * verifies if the session corresponding to the session cookie was revoked.
260
+ * If the corresponding user's session was invalidated, an
261
+ * `auth/session-cookie-revoked` error is thrown. If not specified the check
262
+ * is not performed.
263
+ *
264
+ * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions |
265
+ * Verify Session Cookies}
266
+ * for code samples and detailed documentation
267
+ *
268
+ * @param sessionCookie - The session cookie to verify.
269
+ * @param checkForRevocation - Whether to check if the session cookie was
270
+ * revoked. This requires an extra request to the Firebase Auth backend to
271
+ * check the `tokensValidAfterTime` time for the corresponding user.
272
+ * When not specified, this additional check is not performed.
273
+ *
274
+ * @returns A promise fulfilled with the
275
+ * session cookie's decoded claims if the session cookie is valid; otherwise,
276
+ * a rejected promise.
277
+ */
278
+ verifySessionCookie(sessionCookie: string, checkRevoked?: boolean): Promise<DecodedIdToken>;
279
+ /**
280
+ * Gets an OAuth2 access token from Google's OAuth2 server. This token is
281
+ * required for accessing the Firebase Auth REST API via fetch requests.
282
+ *
283
+ * Checks if a token already exists in the KV namespace. If not, it gets a new
284
+ * token from Google's OAuth2 server, and sets it on the KV namespace.¨
285
+ *
286
+ * This code is under the MIT Licence.
287
+ *
288
+ * @returns The OAuth2 access token
289
+ */
290
+ private getOauth2AccessToken;
291
+ }