@sekyro/connect-firebase 0.0.0-stage → 0.1.0-rc.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # @sekyro/connect-firebase
2
+
3
+ ## 0.1.0-rc.1
4
+
5
+ ### Patch Changes
6
+
7
+ - bb24ac2: First release candidate of the Firebase connector: `firebase({ auth })` stores the Sekyro claim as the custom claim `sekyro` through any `firebase-admin` `Auth` (project or tenant), reading the user's other claims first, serialising writes per user and refusing a write over the 1000-byte budget before it reaches Firebase; the opt-in `revokeRefreshTokensOnRevoked` revokes the user's refresh tokens before a write that newly carries `revoked`; `rtdbRefreshSignal` and `firestoreRefreshSignal` write the `metadata/{uid}` refresh signal; `firebaseUserDeleted` turns `onUserDeleted` (2nd or 1st gen) into the connector's deletion policy; `SekyroFirebaseError` carries a code and never a provider message. Proven against the Firebase Auth emulator; Next.js and Cloud Functions samples ship in the repository.
8
+ - Updated dependencies [1e450dc]
9
+ - Updated dependencies [3ea3d33]
10
+ - @sekyro/node@0.1.0-rc.7
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ Sekyro AI SDK License (proprietary)
2
+
3
+ Copyright (c) 2026 Ibtikar Technologies, Inc. All rights reserved.
4
+
5
+ This SDK is proprietary software of Ibtikar Technologies, Inc., licensed
6
+ only under the Sekyro AI SDK License:
7
+ https://sekyro.ai/en/legal/sdk-license
8
+ (in French: https://sekyro.ai/fr/legal/sdk-license,
9
+ in Arabic: https://sekyro.ai/ar/legal/sdk-license).
10
+
11
+ In short, and subject to the full license:
12
+
13
+ - You may use the SDK only with a Sekyro AI account, a customer agreement
14
+ with Ibtikar Technologies, Inc. and valid API keys, to integrate the
15
+ Sekyro AI services into your own applications. You may distribute it to
16
+ your end users only as embedded in those applications.
17
+ - You may not use it with another identity verification provider, modify it
18
+ beyond the configuration and theming it exposes, reverse engineer,
19
+ decompile or disassemble it (except where the law expressly allows it),
20
+ circumvent its security, attestation, license checks or usage metering,
21
+ or distribute or sublicense it on its own.
22
+ - Open-source components keep their own licenses. See the third-party
23
+ notices shipped with this SDK.
24
+ - The SDK is provided "as is", without warranty, except as your customer
25
+ agreement provides. The license is governed by the laws of the State of
26
+ Delaware, USA. If this license and your customer agreement conflict,
27
+ the customer agreement prevails.
28
+
29
+ Questions: contact@sekyro.ai
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # @sekyro/connect-firebase
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
+ Release candidate on npm. The Sekyro AI connector for Firebase Authentication and Identity
4
+ Platform: it writes the verified-human claim as the custom claim `sekyro` through the Admin SDK, keeping the
5
+ user's other custom claims and the 1000-byte budget, so your server and your security rules gate on the ID token,
6
+ and your `onUserDeleted` Cloud Function runs the connector's deletion policy.
7
+ The claim and the trust rules: `docs/partner/connectors/overview.md`.
8
+
9
+ ## What you get
10
+
11
+ - `firebase({ auth })`: a `ProviderAdapter` for `createConnector` from `@sekyro/node/connect`. It reads the claim
12
+ with `auth.getUser(uid).customClaims.sekyro` and writes it with `auth.setCustomUserClaims(uid, { ...others,
13
+ sekyro: claim })`, one write per user at a time, refused before the call when the claims would exceed 1000 bytes.
14
+ - `firebase({ auth, revokeRefreshTokensOnRevoked: true })` (opt-in): a write that newly carries the `revoked`
15
+ flag first calls `auth.revokeRefreshTokens(uid)`, so `verifySessionCookie(cookie, true)` and
16
+ `verifyIdToken(token, true)` refuse the user's existing tokens and the user signs in again. A failed revocation
17
+ fails the write (nothing is stored), so Sekyro's retry revokes again.
18
+ - `rtdbRefreshSignal(db)` and `firestoreRefreshSignal(db)`: the optional `metadata/{uid}` refresh signal, so the
19
+ signed-in client refreshes its ID token as soon as the claim changes.
20
+ - `firebaseUserDeleted(connector)`: the handler for your `onUserDeleted` Cloud Function (2nd gen) or
21
+ `functions.auth.user().onDelete` (1st gen).
22
+ - `examples/next`: a Next.js App Router sample (start, return, webhook, a gate helper and the sign-in check in
23
+ middleware). `examples/functions/user-deleted.ts`: the deletion function.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ npm install @sekyro/node @sekyro/connect-firebase firebase-admin
29
+ ```
30
+
31
+ `firebase-admin` is an optional peer (`^12`, `^13` or `^14`): the adapter never imports it, it takes the `Auth`
32
+ instance you already have. `firebase-admin` 14 needs Node.js 22; 13 runs on Node.js 18 and later. The package
33
+ itself has no runtime dependency and runs on Node.js 20.
34
+
35
+ ## Configure Firebase
36
+
37
+ - Run the Admin SDK with a service account limited to the Firebase Authentication Admin role. Keep its key
38
+ server-side only, never in a browser or an app.
39
+ - Identity Platform tenants: pass `getAuth().tenantManager().authForTenant(tenantId)` as `auth`.
40
+ - The refresh signal (optional) writes `{ refreshTime }` to `metadata/{uid}` in the Realtime Database or Firestore.
41
+ Make that node readable by its own user only and not writable by clients, for example on the Realtime Database:
42
+
43
+ ```json
44
+ {
45
+ "rules": {
46
+ "metadata": {
47
+ "$uid": { ".read": "auth != null && auth.uid === $uid", ".write": false }
48
+ }
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## Configure Sekyro
54
+
55
+ An app, its API key (`sessions:create`, `sessions:read`, `subjects:read`, plus `subjects:write` when
56
+ `onUserDeleted` is `revoke` or `delete`) and a webhook endpoint for `session.completed`, `session.failed`,
57
+ `subject.updated` and `subject.deleted`, limited to the app's id (`appIds`).
58
+
59
+ ## Wire your app
60
+
61
+ ```ts
62
+ import { getAuth } from "firebase-admin/auth";
63
+ import { Sekyro } from "@sekyro/node";
64
+ import { createConnector } from "@sekyro/node/connect";
65
+ import { firebase } from "@sekyro/connect-firebase";
66
+
67
+ export const connector = createConnector({
68
+ sekyro: new Sekyro({ apiKey: process.env.SEKYRO_API_KEY! }),
69
+ appId: process.env.SEKYRO_APP_ID!,
70
+ env: "live",
71
+ webhookSecret: process.env.SEKYRO_WEBHOOK_SECRET!,
72
+ provider: firebase({ auth: getAuth() }),
73
+ });
74
+ ```
75
+
76
+ The user id is the Firebase `uid`. In `examples/next`:
77
+
78
+ | Route | What it does |
79
+ |---|---|
80
+ | `POST /api/sekyro/start` | Starts a verification for the user of the `Authorization: Bearer <ID token>` header. |
81
+ | `GET /sekyro/return` | Checks the `state` and the session id, takes the user from the `__session` cookie, then `connector.sync` writes the claim. |
82
+ | `POST /api/sekyro/webhooks` | The Sekyro webhook: verifies the signature and writes the claim. |
83
+ | `app/payouts/gate.ts` | `requireVerified()`, the gate for a server component. |
84
+ | `middleware.ts` | Sends a request without a `__session` cookie to `/sign-in`. |
85
+
86
+ ## Refresh the token after the return
87
+
88
+ The claim is in the next ID token. After the return, call `currentUser.getIdToken(true)` in the browser (on the
89
+ `/verified` page); otherwise it appears at the next hourly refresh. With a refresh signal, the client listens to
90
+ `metadata/{uid}/refreshTime` and calls `getIdToken(true)` when it changes, so a claim written by a webhook later
91
+ reaches the token at once too. If your app keeps a session cookie, mint it again from the refreshed ID token.
92
+
93
+ ## Gate
94
+
95
+ On the server, `sekyroGate(connector, decoded, { level: 2 })` from `@sekyro/node/connect/next`, where `decoded`
96
+ is the result of `auth.verifyIdToken(token)` or `auth.verifySessionCookie(cookie, true)`; never a token the server
97
+ did not verify. Next.js middleware runs on the edge, where `firebase-admin` does not, so the sample gates in a
98
+ server component helper (`app/payouts/gate.ts`). Security rules read the claim too:
99
+ `request.auth.token.sekyro.level >= 2` (Firestore and Storage) or `auth.token.sekyro.level >= 2` (Realtime
100
+ Database).
101
+
102
+ Revocation window: an ID token carries the claim as it was when Firebase issued it, for up to one hour, and a
103
+ session cookie keeps its copy for as long as the cookie lives (up to two weeks). The refresh signal shortens that
104
+ only for a client that cooperates. To close it:
105
+
106
+ - pass `revokeRefreshTokensOnRevoked: true` and always verify with the revocation check
107
+ (`verifySessionCookie(cookie, true)`, `verifyIdToken(token, true)`): a revoked user's tokens are refused at once;
108
+ - for payouts and other high-value routes, gate on the stored claim: `evaluateGate(await connector.claimOf(uid),
109
+ policy)` reads it with one `getUser` and no lag (`examples/next/app/payouts/gate.ts`).
110
+
111
+ Security rules read only the token, so they keep the old claim until the client refreshes it.
112
+
113
+ ## Deletion signal
114
+
115
+ ```ts
116
+ import { onUserDeleted } from "firebase-functions/v2/identity";
117
+ import { firebaseUserDeleted } from "@sekyro/connect-firebase";
118
+
119
+ const handle = firebaseUserDeleted(connector);
120
+ export const sekyroUserDeleted = onUserDeleted(async (event) => {
121
+ await handle(event);
122
+ });
123
+ ```
124
+
125
+ `onUserDeleted` (`firebase-functions/v2/identity`) is in Preview; the 1st gen
126
+ `functions.auth.user().onDelete((user) => handle(user))` works the same. The function runs inside your project, so
127
+ there is no transport to verify. The handler takes the uid and runs `connector.userDeleted`, which applies
128
+ `onUserDeleted` (`ignore` by default); a failure of Sekyro rejects, so the function can be retried. Bulk deletes
129
+ (`deleteUsers()`) emit no event: call `connector.userDeleted(uid)` for each uid yourself.
130
+
131
+ ## Limits
132
+
133
+ - All custom claims of a user share 1000 bytes. The claim takes about 200 bytes. The adapter measures the UTF-8
134
+ length of the serialised claims before each write and refuses with `claims_budget_exceeded` (with `bytes` and
135
+ `budget`) instead of letting Firebase refuse it; nothing is written then. `maxClaimsBytes` lowers the ceiling.
136
+ - `setCustomUserClaims` replaces all custom claims, so each write reads the user's claims first, keeps the others
137
+ and replaces `sekyro` whole. The adapter's `update` does the connector's read, merge and write under one
138
+ per-user lock with a single `getUser`, so a revocation and a concurrent result for the same user never
139
+ interleave in this process. Another process writing the same user's claims at the same moment can still
140
+ overwrite them, so keep claim writes in one service (or queue the Sekyro webhook deliveries per uid).
141
+ - Reserved names (`acr`, `amr`, `at_hash`, `aud`, `auth_time`, `azp`, `cnf`, `c_hash`, `exp`, `iat`, `iss`, `jti`,
142
+ `nbf`, `nonce`, `sub`, `firebase`, `user_id`) cannot be custom claims; `sekyro` is not one of them.
143
+ - Firebase allows 10 account configuration updates per second per project: one read and at most one write per
144
+ webhook.
145
+
146
+ ## Errors
147
+
148
+ `SekyroFirebaseError` has a `code` (`config`, `not_found`, `claims_budget_exceeded`, `reserved_claim`,
149
+ `unauthorized`, `unavailable`, `upstream`), the `firebase-admin` code as `firebaseCode` when there was one, and
150
+ `bytes` and `budget` for a refused write. It never carries the Firebase message, which can contain an e-mail
151
+ address. A missing user reads as `null`; a write to a missing user is `not_found`.
152
+
153
+ ## Security
154
+
155
+ - Secrets (Sekyro API key and webhook secret, the service account key) stay in server environment.
156
+ - The claim is written only from a signed Sekyro webhook or a session your server reads with its API key; the
157
+ return route never reads a level from the URL.
158
+ - Custom claims are set by the Admin SDK only; users cannot edit them.
159
+ - The deletion handler accepts nothing but a uid and only ever runs the deletion policy. It trusts that uid, so
160
+ never wire it to an HTTP function (`onRequest`) or a callable (`onCall`): only the Auth deletion trigger.
161
+
162
+ ## Development
163
+
164
+ ```bash
165
+ npm test && npm run typecheck && npm run build && npm run api:check
166
+ npm run check:emulator # firebase-tools: the Auth emulator and the real firebase-admin (also in CI)
167
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{FIREBASE_CLAIM_KEY:()=>FIREBASE_CLAIM_KEY,SekyroFirebaseError:()=>SekyroFirebaseError,claimsByteLength:()=>claimsByteLength,firebase:()=>firebase,firebaseUserDeleted:()=>firebaseUserDeleted,firestoreRefreshSignal:()=>firestoreRefreshSignal,rtdbRefreshSignal:()=>rtdbRefreshSignal});module.exports=__toCommonJS(src_exports);var import_connect=require("@sekyro/node/connect");var MESSAGES={config:"The Firebase connector is not configured",not_found:"The Firebase user does not exist",claims_budget_exceeded:"The custom claims would exceed the Firebase size budget",reserved_claim:"The user's custom claims use a name Firebase reserves",unauthorized:"Firebase refused the service account",unavailable:"Firebase Authentication is unavailable",upstream:"Firebase Authentication answered with an unexpected error"},SekyroFirebaseError=class extends Error{name="SekyroFirebaseError";code;firebaseCode;bytes;budget;constructor(code,opts={}){super(opts.message??MESSAGES[code]),this.code=code,opts.firebaseCode!==void 0&&(this.firebaseCode=opts.firebaseCode),opts.bytes!==void 0&&(this.bytes=opts.bytes),opts.budget!==void 0&&(this.budget=opts.budget)}},BY_CODE={"auth/user-not-found":"not_found","auth/claims-too-large":"claims_budget_exceeded","auth/reserved-claim":"reserved_claim","auth/reserved-claims":"reserved_claim","auth/insufficient-permission":"unauthorized","auth/invalid-credential":"unauthorized","app/invalid-credential":"unauthorized","auth/internal-error":"unavailable","app/internal-error":"unavailable","app/network-error":"unavailable","app/network-timeout":"unavailable","auth/quota-exceeded":"unavailable","auth/too-many-requests":"unavailable"};function codeOf(err){if(err===null||typeof err!="object")return;let code=err.code;return typeof code=="string"&&code.length>0?code:void 0}function fromFirebaseError(err){if(err instanceof SekyroFirebaseError)return err;let firebaseCode=codeOf(err);if(firebaseCode===void 0)return new SekyroFirebaseError("unavailable");let mapped=BY_CODE[firebaseCode]??(firebaseCode.startsWith("auth/")?"upstream":"unavailable");return new SekyroFirebaseError(mapped,{firebaseCode})}function isUserNotFound(err){return codeOf(err)==="auth/user-not-found"}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}var FIREBASE_CLAIM_KEY="sekyro",DEFAULT_MAX_CLAIMS_BYTES=1e3,encoder=new TextEncoder;function claimsByteLength(claims){return encoder.encode(JSON.stringify(claims)).byteLength}function firebase(opts){let auth=opts?.auth;if(auth===null||typeof auth!="object"||typeof auth.getUser!="function"||typeof auth.setCustomUserClaims!="function")throw new SekyroFirebaseError("config",{message:"`auth` must be a firebase-admin Auth instance"});let maxClaimsBytes=opts.maxClaimsBytes??DEFAULT_MAX_CLAIMS_BYTES;if(!Number.isInteger(maxClaimsBytes)||maxClaimsBytes<1)throw new SekyroFirebaseError("config",{message:"`maxClaimsBytes` must be a positive integer"});let{refreshSignal,onSignalError}=opts,revokeOnRevoked=opts.revokeRefreshTokensOnRevoked===!0;if(revokeOnRevoked&&typeof auth.revokeRefreshTokens!="function")throw new SekyroFirebaseError("config",{message:"`revokeRefreshTokensOnRevoked` needs an `auth` with revokeRefreshTokens"});let now=opts.now??Date.now,lock=perKeyLock(),revokedIn=value=>(0,import_connect.parseClaim)(value)?.flags?.includes("revoked")===!0;async function claimsOf(uid,missingOk){try{return(await auth.getUser(uid)).customClaims??{}}catch(err){if(missingOk&&isUserNotFound(err))return null;throw fromFirebaseError(err)}}async function commit(uid,existing,claim){let next={...existing,[FIREBASE_CLAIM_KEY]:claim},bytes=claimsByteLength(next);if(bytes>maxClaimsBytes)throw new SekyroFirebaseError("claims_budget_exceeded",{bytes,budget:maxClaimsBytes});if(revokeOnRevoked&&revokedIn(claim)&&!revokedIn(existing[FIREBASE_CLAIM_KEY]))try{await auth.revokeRefreshTokens(uid)}catch(err){throw fromFirebaseError(err)}try{await auth.setCustomUserClaims(uid,next)}catch(err){throw fromFirebaseError(err)}if(refreshSignal)try{await refreshSignal.set(uid,now())}catch(err){onSignalError?.(err,uid)}}return{name:"firebase",maxClaimsBytes,async readUser(uid){let user;try{user=await auth.getUser(uid)}catch(err){if(isUserNotFound(err))return null;throw fromFirebaseError(err)}return user.customClaims?.[FIREBASE_CLAIM_KEY]??null},writeUser(uid,claim){return lock(uid,async()=>{await commit(uid,await claimsOf(uid,!1),claim)})},update(uid,fn){return lock(uid,async()=>{let existing=await claimsOf(uid,!0),out=fn(existing?.[FIREBASE_CLAIM_KEY]??null);if(out.changed&&out.claim){if(existing===null)throw new SekyroFirebaseError("not_found",{firebaseCode:"auth/user-not-found"});await commit(uid,existing,out.claim)}return out})},readClaimFromToken(tokenClaims){return tokenClaims[FIREBASE_CLAIM_KEY]??null}}}var MAX_UID_LENGTH=128;function assertUid(uid,what){if(typeof uid!="string"||uid.length===0||uid.length>MAX_UID_LENGTH||uid.includes("/"))throw new SekyroFirebaseError("config",{message:`${what} needs a uid of 1 to ${MAX_UID_LENGTH} characters without "/"`})}function rtdbRefreshSignal(db,opts={}){let path=opts.path??"metadata";return{async set(uid,refreshTimeMs){assertUid(uid,"rtdbRefreshSignal"),await db.ref(`${path}/${uid}`).set({refreshTime:refreshTimeMs})}}}function firestoreRefreshSignal(db,opts={}){let collection=opts.collection??"metadata";return{async set(uid,refreshTimeMs){assertUid(uid,"firestoreRefreshSignal"),await db.doc(`${collection}/${uid}`).set({refreshTime:refreshTimeMs},{merge:!0})}}}function firebaseUserDeleted(connector){return async input=>{let uid=uidOf(input);if(uid===void 0)throw new SekyroFirebaseError("config",{message:"firebaseUserDeleted needs a uid, a user record or an onUserDeleted event"});let{policy,subjects}=await connector.userDeleted(uid);return{policy,subjects,uid}}}function uidOf(input){let uid;if(typeof input=="string")uid=input;else if(input!==null&&typeof input=="object"){let record=input;record.uid!==void 0?uid=record.uid:record.data!==null&&typeof record.data=="object"&&(uid=record.data.uid)}return typeof uid=="string"&&uid.length>0&&uid.length<=MAX_UID_LENGTH?uid:void 0}0&&(module.exports={FIREBASE_CLAIM_KEY,SekyroFirebaseError,claimsByteLength,firebase,firebaseUserDeleted,firestoreRefreshSignal,rtdbRefreshSignal});
@@ -0,0 +1,223 @@
1
+ import { ProviderAdapter, Connector } from '@sekyro/node/connect';
2
+
3
+ /**
4
+ * Tells an active client to refresh its ID token (`getIdToken(true)`) after a claim write: the adapter calls
5
+ * `set(uid, Date.now())` once the claim is stored, and the client listens to the value.
6
+ * @public
7
+ */
8
+ interface RefreshSignal {
9
+ /** Record that `uid` should refresh its ID token; `refreshTimeMs` is milliseconds since the epoch. */
10
+ set(uid: string, refreshTimeMs: number): Promise<void>;
11
+ }
12
+ /**
13
+ * The part of `firebase-admin/database` the Realtime Database helper uses.
14
+ * @public
15
+ */
16
+ interface RtdbLike {
17
+ /** `getDatabase().ref(path)`. */
18
+ ref(path: string): {
19
+ set(value: unknown): Promise<void>;
20
+ };
21
+ }
22
+ /**
23
+ * The part of `firebase-admin/firestore` the Firestore helper uses.
24
+ * @public
25
+ */
26
+ interface FirestoreLike {
27
+ /** `getFirestore().doc(path)`. */
28
+ doc(path: string): {
29
+ set(data: Record<string, unknown>, options?: {
30
+ merge?: boolean;
31
+ }): Promise<unknown>;
32
+ };
33
+ }
34
+ /**
35
+ * The refresh signal of the Firebase custom-claims guide on the Realtime Database: writes `{ refreshTime }` at
36
+ * `metadata/{uid}` (or `{path}/{uid}`). Make the node readable by that user only and not writable by clients.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import { getDatabase } from "firebase-admin/database";
41
+ * import { firebase, rtdbRefreshSignal } from "@sekyro/connect-firebase";
42
+ *
43
+ * const provider = firebase({ auth: getAuth(), refreshSignal: rtdbRefreshSignal(getDatabase()) });
44
+ * ```
45
+ * @public
46
+ */
47
+ declare function rtdbRefreshSignal(db: RtdbLike, opts?: {
48
+ path?: string;
49
+ }): RefreshSignal;
50
+ /**
51
+ * The same signal on Cloud Firestore: merges `{ refreshTime }` into the document `metadata/{uid}` (or
52
+ * `{collection}/{uid}`). Make the document readable by that user only and not writable by clients.
53
+ * @public
54
+ */
55
+ declare function firestoreRefreshSignal(db: FirestoreLike, opts?: {
56
+ collection?: string;
57
+ }): RefreshSignal;
58
+
59
+ /**
60
+ * The Admin SDK methods the adapter calls. It is structural, so `getAuth()` and
61
+ * `getAuth().tenantManager().authForTenant(tenantId)` both fit it and no `firebase-admin` type leaks into this
62
+ * package's public surface.
63
+ * @public
64
+ */
65
+ interface FirebaseAuthLike {
66
+ /** Read the user record; its `customClaims` hold the claim. */
67
+ getUser(uid: string): Promise<{
68
+ uid: string;
69
+ customClaims?: Record<string, unknown> | null | undefined;
70
+ }>;
71
+ /** Replace every custom claim of the user (`null` clears them). */
72
+ setCustomUserClaims(uid: string, customClaims: Record<string, unknown> | null): Promise<void>;
73
+ /** Revoke the user's refresh tokens; called only with `revokeRefreshTokensOnRevoked: true`. */
74
+ revokeRefreshTokens?(uid: string): Promise<void>;
75
+ }
76
+ /**
77
+ * Options of {@link firebase}.
78
+ * @public
79
+ */
80
+ interface FirebaseAdapterOptions {
81
+ /** `getAuth(app)`, or `getAuth(app).tenantManager().authForTenant(tenantId)` for Identity Platform tenants. */
82
+ auth: FirebaseAuthLike;
83
+ /** The ceiling for the serialised custom claims object, in UTF-8 bytes. Default 1000 (Firebase's limit). */
84
+ maxClaimsBytes?: number;
85
+ /** Written after every successful claim write, so an active client refreshes its ID token at once. Optional. */
86
+ refreshSignal?: RefreshSignal;
87
+ /** Receives a refresh-signal failure; the claim write has already succeeded. Default: ignored. */
88
+ onSignalError?: (err: unknown, uid: string) => void;
89
+ /** Milliseconds since the epoch, for the refresh signal. Default `Date.now`. */
90
+ now?: () => number;
91
+ /**
92
+ * Call `auth.revokeRefreshTokens(uid)` before a write that newly carries the `revoked` flag, so
93
+ * `verifySessionCookie(cookie, true)` and `verifyIdToken(token, true)` refuse the user's existing tokens at once
94
+ * and the user signs in again. A revocation failure fails the write (nothing is stored; Sekyro retries the
95
+ * webhook). Default `false`.
96
+ */
97
+ revokeRefreshTokensOnRevoked?: boolean;
98
+ }
99
+ /**
100
+ * The custom claim that holds the Sekyro claim.
101
+ * @public
102
+ */
103
+ declare const FIREBASE_CLAIM_KEY = "sekyro";
104
+ /**
105
+ * The UTF-8 byte length of `JSON.stringify(claims)`: the size Firebase limits to 1000 bytes.
106
+ * @public
107
+ */
108
+ declare function claimsByteLength(claims: Record<string, unknown>): number;
109
+ /**
110
+ * The adapter {@link firebase} returns: a `ProviderAdapter` with its byte budget.
111
+ * @public
112
+ */
113
+ interface FirebaseAdapter extends ProviderAdapter {
114
+ /** The ceiling for the serialised custom claims, in UTF-8 bytes. */
115
+ readonly maxClaimsBytes: number;
116
+ }
117
+ /**
118
+ * A `ProviderAdapter` (from `@sekyro/node/connect`) over Firebase Authentication: the claim lives in the user's
119
+ * custom claim `sekyro`, which only the Admin SDK can set and every ID token carries at its top level.
120
+ *
121
+ * `setCustomUserClaims` replaces every custom claim of the user, so each write reads the user's claims first,
122
+ * keeps the others and replaces `sekyro` whole. Writes for one user are serialised in this process, and a write
123
+ * whose claims would exceed `maxClaimsBytes` is refused with `claims_budget_exceeded` before it reaches Firebase.
124
+ * With a `refreshSignal`, the user's active client is told to refresh its ID token after each write; a signal
125
+ * failure goes to `onSignalError` and never fails the write. Server-side only.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * import { getAuth } from "firebase-admin/auth";
130
+ * import { firebase } from "@sekyro/connect-firebase";
131
+ *
132
+ * const provider = firebase({ auth: getAuth() });
133
+ * ```
134
+ * @public
135
+ */
136
+ declare function firebase(opts: FirebaseAdapterOptions): FirebaseAdapter;
137
+
138
+ /**
139
+ * What the handler accepts: a 2nd gen identity event (`event.data.uid`), a 1st gen user record (`user.uid`), or a
140
+ * uid.
141
+ * @public
142
+ */
143
+ type FirebaseDeletedUserInput = string | {
144
+ uid: string;
145
+ } | {
146
+ data: {
147
+ uid: string;
148
+ };
149
+ };
150
+ /**
151
+ * What the handler returns: the connector's deletion policy, how many subjects it touched, and the uid.
152
+ * @public
153
+ */
154
+ interface FirebaseUserDeletedResult {
155
+ /** The connector's `onUserDeleted` policy that ran. */
156
+ policy: "ignore" | "revoke" | "delete";
157
+ /** How many Sekyro subjects the policy touched. */
158
+ subjects: number;
159
+ /** The deleted user's uid. */
160
+ uid: string;
161
+ }
162
+ /**
163
+ * Turns your `onUserDeleted` Cloud Function (2nd gen, `firebase-functions/v2/identity`) or
164
+ * `functions.auth.user().onDelete` (1st gen) into `connector.userDeleted(uid)`. It runs inside your project, so
165
+ * there is no transport to verify. Advisory and idempotent: it only runs the connector's `onUserDeleted` policy.
166
+ * Bulk `deleteUsers()` emits no event: call `connector.userDeleted` yourself then. A failure of the connector
167
+ * propagates, so the function fails and can be retried.
168
+ *
169
+ * Never wire it to an HTTP function (`onRequest`) or a callable (`onCall`): it trusts the uid it is given, so any
170
+ * caller could then run your deletion policy for any user. Only the Auth deletion trigger may call it.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * import { onUserDeleted } from "firebase-functions/v2/identity";
175
+ * import { firebaseUserDeleted } from "@sekyro/connect-firebase";
176
+ *
177
+ * const handle = firebaseUserDeleted(connector);
178
+ * export const sekyroUserDeleted = onUserDeleted(async (event) => {
179
+ * await handle(event);
180
+ * });
181
+ * ```
182
+ * @public
183
+ */
184
+ declare function firebaseUserDeleted(connector: Pick<Connector, "userDeleted">): (input: FirebaseDeletedUserInput) => Promise<FirebaseUserDeletedResult>;
185
+
186
+ /**
187
+ * Why a Firebase call failed:
188
+ * - `config`: `auth` is not an Auth-like object, or the options are invalid;
189
+ * - `not_found`: the user does not exist on a write (a read answers `null` instead);
190
+ * - `claims_budget_exceeded`: the serialised custom claims would exceed `maxClaimsBytes` (checked before the
191
+ * write), or Firebase refused them as too large;
192
+ * - `reserved_claim`: the user's other custom claims use a name Firebase reserves;
193
+ * - `unauthorized`: the service account may not manage users, or its credential was refused;
194
+ * - `unavailable`: Firebase could not be reached, answered an internal error or a quota error, or the call threw
195
+ * something that is not a Firebase error;
196
+ * - `upstream`: any other Firebase Authentication error.
197
+ * @public
198
+ */
199
+ type SekyroFirebaseErrorCode = "config" | "not_found" | "claims_budget_exceeded" | "reserved_claim" | "unauthorized" | "unavailable" | "upstream";
200
+ /**
201
+ * Thrown by the Firebase adapter and helpers. It carries a `code` and the `firebase-admin` error code when there
202
+ * was one; it never carries the Firebase error message, which can contain an e-mail address.
203
+ * @public
204
+ */
205
+ declare class SekyroFirebaseError extends Error {
206
+ readonly name = "SekyroFirebaseError";
207
+ /** Why the call failed. */
208
+ readonly code: SekyroFirebaseErrorCode;
209
+ /** The `firebase-admin` error code (`auth/...`) when there was one; never its message. */
210
+ readonly firebaseCode?: string;
211
+ /** For `claims_budget_exceeded` before the write: the byte length the custom claims would have had. */
212
+ readonly bytes?: number;
213
+ /** For `claims_budget_exceeded` before the write: the budget in bytes. */
214
+ readonly budget?: number;
215
+ constructor(code: SekyroFirebaseErrorCode, opts?: {
216
+ firebaseCode?: string;
217
+ bytes?: number;
218
+ budget?: number;
219
+ message?: string;
220
+ });
221
+ }
222
+
223
+ export { FIREBASE_CLAIM_KEY, type FirebaseAdapter, type FirebaseAdapterOptions, type FirebaseAuthLike, type FirebaseDeletedUserInput, type FirebaseUserDeletedResult, type FirestoreLike, type RefreshSignal, type RtdbLike, SekyroFirebaseError, type SekyroFirebaseErrorCode, claimsByteLength, firebase, firebaseUserDeleted, firestoreRefreshSignal, rtdbRefreshSignal };
@@ -0,0 +1,223 @@
1
+ import { ProviderAdapter, Connector } from '@sekyro/node/connect';
2
+
3
+ /**
4
+ * Tells an active client to refresh its ID token (`getIdToken(true)`) after a claim write: the adapter calls
5
+ * `set(uid, Date.now())` once the claim is stored, and the client listens to the value.
6
+ * @public
7
+ */
8
+ interface RefreshSignal {
9
+ /** Record that `uid` should refresh its ID token; `refreshTimeMs` is milliseconds since the epoch. */
10
+ set(uid: string, refreshTimeMs: number): Promise<void>;
11
+ }
12
+ /**
13
+ * The part of `firebase-admin/database` the Realtime Database helper uses.
14
+ * @public
15
+ */
16
+ interface RtdbLike {
17
+ /** `getDatabase().ref(path)`. */
18
+ ref(path: string): {
19
+ set(value: unknown): Promise<void>;
20
+ };
21
+ }
22
+ /**
23
+ * The part of `firebase-admin/firestore` the Firestore helper uses.
24
+ * @public
25
+ */
26
+ interface FirestoreLike {
27
+ /** `getFirestore().doc(path)`. */
28
+ doc(path: string): {
29
+ set(data: Record<string, unknown>, options?: {
30
+ merge?: boolean;
31
+ }): Promise<unknown>;
32
+ };
33
+ }
34
+ /**
35
+ * The refresh signal of the Firebase custom-claims guide on the Realtime Database: writes `{ refreshTime }` at
36
+ * `metadata/{uid}` (or `{path}/{uid}`). Make the node readable by that user only and not writable by clients.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import { getDatabase } from "firebase-admin/database";
41
+ * import { firebase, rtdbRefreshSignal } from "@sekyro/connect-firebase";
42
+ *
43
+ * const provider = firebase({ auth: getAuth(), refreshSignal: rtdbRefreshSignal(getDatabase()) });
44
+ * ```
45
+ * @public
46
+ */
47
+ declare function rtdbRefreshSignal(db: RtdbLike, opts?: {
48
+ path?: string;
49
+ }): RefreshSignal;
50
+ /**
51
+ * The same signal on Cloud Firestore: merges `{ refreshTime }` into the document `metadata/{uid}` (or
52
+ * `{collection}/{uid}`). Make the document readable by that user only and not writable by clients.
53
+ * @public
54
+ */
55
+ declare function firestoreRefreshSignal(db: FirestoreLike, opts?: {
56
+ collection?: string;
57
+ }): RefreshSignal;
58
+
59
+ /**
60
+ * The Admin SDK methods the adapter calls. It is structural, so `getAuth()` and
61
+ * `getAuth().tenantManager().authForTenant(tenantId)` both fit it and no `firebase-admin` type leaks into this
62
+ * package's public surface.
63
+ * @public
64
+ */
65
+ interface FirebaseAuthLike {
66
+ /** Read the user record; its `customClaims` hold the claim. */
67
+ getUser(uid: string): Promise<{
68
+ uid: string;
69
+ customClaims?: Record<string, unknown> | null | undefined;
70
+ }>;
71
+ /** Replace every custom claim of the user (`null` clears them). */
72
+ setCustomUserClaims(uid: string, customClaims: Record<string, unknown> | null): Promise<void>;
73
+ /** Revoke the user's refresh tokens; called only with `revokeRefreshTokensOnRevoked: true`. */
74
+ revokeRefreshTokens?(uid: string): Promise<void>;
75
+ }
76
+ /**
77
+ * Options of {@link firebase}.
78
+ * @public
79
+ */
80
+ interface FirebaseAdapterOptions {
81
+ /** `getAuth(app)`, or `getAuth(app).tenantManager().authForTenant(tenantId)` for Identity Platform tenants. */
82
+ auth: FirebaseAuthLike;
83
+ /** The ceiling for the serialised custom claims object, in UTF-8 bytes. Default 1000 (Firebase's limit). */
84
+ maxClaimsBytes?: number;
85
+ /** Written after every successful claim write, so an active client refreshes its ID token at once. Optional. */
86
+ refreshSignal?: RefreshSignal;
87
+ /** Receives a refresh-signal failure; the claim write has already succeeded. Default: ignored. */
88
+ onSignalError?: (err: unknown, uid: string) => void;
89
+ /** Milliseconds since the epoch, for the refresh signal. Default `Date.now`. */
90
+ now?: () => number;
91
+ /**
92
+ * Call `auth.revokeRefreshTokens(uid)` before a write that newly carries the `revoked` flag, so
93
+ * `verifySessionCookie(cookie, true)` and `verifyIdToken(token, true)` refuse the user's existing tokens at once
94
+ * and the user signs in again. A revocation failure fails the write (nothing is stored; Sekyro retries the
95
+ * webhook). Default `false`.
96
+ */
97
+ revokeRefreshTokensOnRevoked?: boolean;
98
+ }
99
+ /**
100
+ * The custom claim that holds the Sekyro claim.
101
+ * @public
102
+ */
103
+ declare const FIREBASE_CLAIM_KEY = "sekyro";
104
+ /**
105
+ * The UTF-8 byte length of `JSON.stringify(claims)`: the size Firebase limits to 1000 bytes.
106
+ * @public
107
+ */
108
+ declare function claimsByteLength(claims: Record<string, unknown>): number;
109
+ /**
110
+ * The adapter {@link firebase} returns: a `ProviderAdapter` with its byte budget.
111
+ * @public
112
+ */
113
+ interface FirebaseAdapter extends ProviderAdapter {
114
+ /** The ceiling for the serialised custom claims, in UTF-8 bytes. */
115
+ readonly maxClaimsBytes: number;
116
+ }
117
+ /**
118
+ * A `ProviderAdapter` (from `@sekyro/node/connect`) over Firebase Authentication: the claim lives in the user's
119
+ * custom claim `sekyro`, which only the Admin SDK can set and every ID token carries at its top level.
120
+ *
121
+ * `setCustomUserClaims` replaces every custom claim of the user, so each write reads the user's claims first,
122
+ * keeps the others and replaces `sekyro` whole. Writes for one user are serialised in this process, and a write
123
+ * whose claims would exceed `maxClaimsBytes` is refused with `claims_budget_exceeded` before it reaches Firebase.
124
+ * With a `refreshSignal`, the user's active client is told to refresh its ID token after each write; a signal
125
+ * failure goes to `onSignalError` and never fails the write. Server-side only.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * import { getAuth } from "firebase-admin/auth";
130
+ * import { firebase } from "@sekyro/connect-firebase";
131
+ *
132
+ * const provider = firebase({ auth: getAuth() });
133
+ * ```
134
+ * @public
135
+ */
136
+ declare function firebase(opts: FirebaseAdapterOptions): FirebaseAdapter;
137
+
138
+ /**
139
+ * What the handler accepts: a 2nd gen identity event (`event.data.uid`), a 1st gen user record (`user.uid`), or a
140
+ * uid.
141
+ * @public
142
+ */
143
+ type FirebaseDeletedUserInput = string | {
144
+ uid: string;
145
+ } | {
146
+ data: {
147
+ uid: string;
148
+ };
149
+ };
150
+ /**
151
+ * What the handler returns: the connector's deletion policy, how many subjects it touched, and the uid.
152
+ * @public
153
+ */
154
+ interface FirebaseUserDeletedResult {
155
+ /** The connector's `onUserDeleted` policy that ran. */
156
+ policy: "ignore" | "revoke" | "delete";
157
+ /** How many Sekyro subjects the policy touched. */
158
+ subjects: number;
159
+ /** The deleted user's uid. */
160
+ uid: string;
161
+ }
162
+ /**
163
+ * Turns your `onUserDeleted` Cloud Function (2nd gen, `firebase-functions/v2/identity`) or
164
+ * `functions.auth.user().onDelete` (1st gen) into `connector.userDeleted(uid)`. It runs inside your project, so
165
+ * there is no transport to verify. Advisory and idempotent: it only runs the connector's `onUserDeleted` policy.
166
+ * Bulk `deleteUsers()` emits no event: call `connector.userDeleted` yourself then. A failure of the connector
167
+ * propagates, so the function fails and can be retried.
168
+ *
169
+ * Never wire it to an HTTP function (`onRequest`) or a callable (`onCall`): it trusts the uid it is given, so any
170
+ * caller could then run your deletion policy for any user. Only the Auth deletion trigger may call it.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * import { onUserDeleted } from "firebase-functions/v2/identity";
175
+ * import { firebaseUserDeleted } from "@sekyro/connect-firebase";
176
+ *
177
+ * const handle = firebaseUserDeleted(connector);
178
+ * export const sekyroUserDeleted = onUserDeleted(async (event) => {
179
+ * await handle(event);
180
+ * });
181
+ * ```
182
+ * @public
183
+ */
184
+ declare function firebaseUserDeleted(connector: Pick<Connector, "userDeleted">): (input: FirebaseDeletedUserInput) => Promise<FirebaseUserDeletedResult>;
185
+
186
+ /**
187
+ * Why a Firebase call failed:
188
+ * - `config`: `auth` is not an Auth-like object, or the options are invalid;
189
+ * - `not_found`: the user does not exist on a write (a read answers `null` instead);
190
+ * - `claims_budget_exceeded`: the serialised custom claims would exceed `maxClaimsBytes` (checked before the
191
+ * write), or Firebase refused them as too large;
192
+ * - `reserved_claim`: the user's other custom claims use a name Firebase reserves;
193
+ * - `unauthorized`: the service account may not manage users, or its credential was refused;
194
+ * - `unavailable`: Firebase could not be reached, answered an internal error or a quota error, or the call threw
195
+ * something that is not a Firebase error;
196
+ * - `upstream`: any other Firebase Authentication error.
197
+ * @public
198
+ */
199
+ type SekyroFirebaseErrorCode = "config" | "not_found" | "claims_budget_exceeded" | "reserved_claim" | "unauthorized" | "unavailable" | "upstream";
200
+ /**
201
+ * Thrown by the Firebase adapter and helpers. It carries a `code` and the `firebase-admin` error code when there
202
+ * was one; it never carries the Firebase error message, which can contain an e-mail address.
203
+ * @public
204
+ */
205
+ declare class SekyroFirebaseError extends Error {
206
+ readonly name = "SekyroFirebaseError";
207
+ /** Why the call failed. */
208
+ readonly code: SekyroFirebaseErrorCode;
209
+ /** The `firebase-admin` error code (`auth/...`) when there was one; never its message. */
210
+ readonly firebaseCode?: string;
211
+ /** For `claims_budget_exceeded` before the write: the byte length the custom claims would have had. */
212
+ readonly bytes?: number;
213
+ /** For `claims_budget_exceeded` before the write: the budget in bytes. */
214
+ readonly budget?: number;
215
+ constructor(code: SekyroFirebaseErrorCode, opts?: {
216
+ firebaseCode?: string;
217
+ bytes?: number;
218
+ budget?: number;
219
+ message?: string;
220
+ });
221
+ }
222
+
223
+ export { FIREBASE_CLAIM_KEY, type FirebaseAdapter, type FirebaseAdapterOptions, type FirebaseAuthLike, type FirebaseDeletedUserInput, type FirebaseUserDeletedResult, type FirestoreLike, type RefreshSignal, type RtdbLike, SekyroFirebaseError, type SekyroFirebaseErrorCode, claimsByteLength, firebase, firebaseUserDeleted, firestoreRefreshSignal, rtdbRefreshSignal };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{parseClaim}from"@sekyro/node/connect";var MESSAGES={config:"The Firebase connector is not configured",not_found:"The Firebase user does not exist",claims_budget_exceeded:"The custom claims would exceed the Firebase size budget",reserved_claim:"The user's custom claims use a name Firebase reserves",unauthorized:"Firebase refused the service account",unavailable:"Firebase Authentication is unavailable",upstream:"Firebase Authentication answered with an unexpected error"},SekyroFirebaseError=class extends Error{name="SekyroFirebaseError";code;firebaseCode;bytes;budget;constructor(code,opts={}){super(opts.message??MESSAGES[code]),this.code=code,opts.firebaseCode!==void 0&&(this.firebaseCode=opts.firebaseCode),opts.bytes!==void 0&&(this.bytes=opts.bytes),opts.budget!==void 0&&(this.budget=opts.budget)}},BY_CODE={"auth/user-not-found":"not_found","auth/claims-too-large":"claims_budget_exceeded","auth/reserved-claim":"reserved_claim","auth/reserved-claims":"reserved_claim","auth/insufficient-permission":"unauthorized","auth/invalid-credential":"unauthorized","app/invalid-credential":"unauthorized","auth/internal-error":"unavailable","app/internal-error":"unavailable","app/network-error":"unavailable","app/network-timeout":"unavailable","auth/quota-exceeded":"unavailable","auth/too-many-requests":"unavailable"};function codeOf(err){if(err===null||typeof err!="object")return;let code=err.code;return typeof code=="string"&&code.length>0?code:void 0}function fromFirebaseError(err){if(err instanceof SekyroFirebaseError)return err;let firebaseCode=codeOf(err);if(firebaseCode===void 0)return new SekyroFirebaseError("unavailable");let mapped=BY_CODE[firebaseCode]??(firebaseCode.startsWith("auth/")?"upstream":"unavailable");return new SekyroFirebaseError(mapped,{firebaseCode})}function isUserNotFound(err){return codeOf(err)==="auth/user-not-found"}function perKeyLock(){let tails=new Map;return(key,fn)=>{let run=(tails.get(key)??Promise.resolve()).then(fn,fn),tail=run.then(()=>{},()=>{});return tails.set(key,tail),tail.then(()=>{tails.get(key)===tail&&tails.delete(key)}),run}}var FIREBASE_CLAIM_KEY="sekyro",DEFAULT_MAX_CLAIMS_BYTES=1e3,encoder=new TextEncoder;function claimsByteLength(claims){return encoder.encode(JSON.stringify(claims)).byteLength}function firebase(opts){let auth=opts?.auth;if(auth===null||typeof auth!="object"||typeof auth.getUser!="function"||typeof auth.setCustomUserClaims!="function")throw new SekyroFirebaseError("config",{message:"`auth` must be a firebase-admin Auth instance"});let maxClaimsBytes=opts.maxClaimsBytes??DEFAULT_MAX_CLAIMS_BYTES;if(!Number.isInteger(maxClaimsBytes)||maxClaimsBytes<1)throw new SekyroFirebaseError("config",{message:"`maxClaimsBytes` must be a positive integer"});let{refreshSignal,onSignalError}=opts,revokeOnRevoked=opts.revokeRefreshTokensOnRevoked===!0;if(revokeOnRevoked&&typeof auth.revokeRefreshTokens!="function")throw new SekyroFirebaseError("config",{message:"`revokeRefreshTokensOnRevoked` needs an `auth` with revokeRefreshTokens"});let now=opts.now??Date.now,lock=perKeyLock(),revokedIn=value=>parseClaim(value)?.flags?.includes("revoked")===!0;async function claimsOf(uid,missingOk){try{return(await auth.getUser(uid)).customClaims??{}}catch(err){if(missingOk&&isUserNotFound(err))return null;throw fromFirebaseError(err)}}async function commit(uid,existing,claim){let next={...existing,[FIREBASE_CLAIM_KEY]:claim},bytes=claimsByteLength(next);if(bytes>maxClaimsBytes)throw new SekyroFirebaseError("claims_budget_exceeded",{bytes,budget:maxClaimsBytes});if(revokeOnRevoked&&revokedIn(claim)&&!revokedIn(existing[FIREBASE_CLAIM_KEY]))try{await auth.revokeRefreshTokens(uid)}catch(err){throw fromFirebaseError(err)}try{await auth.setCustomUserClaims(uid,next)}catch(err){throw fromFirebaseError(err)}if(refreshSignal)try{await refreshSignal.set(uid,now())}catch(err){onSignalError?.(err,uid)}}return{name:"firebase",maxClaimsBytes,async readUser(uid){let user;try{user=await auth.getUser(uid)}catch(err){if(isUserNotFound(err))return null;throw fromFirebaseError(err)}return user.customClaims?.[FIREBASE_CLAIM_KEY]??null},writeUser(uid,claim){return lock(uid,async()=>{await commit(uid,await claimsOf(uid,!1),claim)})},update(uid,fn){return lock(uid,async()=>{let existing=await claimsOf(uid,!0),out=fn(existing?.[FIREBASE_CLAIM_KEY]??null);if(out.changed&&out.claim){if(existing===null)throw new SekyroFirebaseError("not_found",{firebaseCode:"auth/user-not-found"});await commit(uid,existing,out.claim)}return out})},readClaimFromToken(tokenClaims){return tokenClaims[FIREBASE_CLAIM_KEY]??null}}}var MAX_UID_LENGTH=128;function assertUid(uid,what){if(typeof uid!="string"||uid.length===0||uid.length>MAX_UID_LENGTH||uid.includes("/"))throw new SekyroFirebaseError("config",{message:`${what} needs a uid of 1 to ${MAX_UID_LENGTH} characters without "/"`})}function rtdbRefreshSignal(db,opts={}){let path=opts.path??"metadata";return{async set(uid,refreshTimeMs){assertUid(uid,"rtdbRefreshSignal"),await db.ref(`${path}/${uid}`).set({refreshTime:refreshTimeMs})}}}function firestoreRefreshSignal(db,opts={}){let collection=opts.collection??"metadata";return{async set(uid,refreshTimeMs){assertUid(uid,"firestoreRefreshSignal"),await db.doc(`${collection}/${uid}`).set({refreshTime:refreshTimeMs},{merge:!0})}}}function firebaseUserDeleted(connector){return async input=>{let uid=uidOf(input);if(uid===void 0)throw new SekyroFirebaseError("config",{message:"firebaseUserDeleted needs a uid, a user record or an onUserDeleted event"});let{policy,subjects}=await connector.userDeleted(uid);return{policy,subjects,uid}}}function uidOf(input){let uid;if(typeof input=="string")uid=input;else if(input!==null&&typeof input=="object"){let record=input;record.uid!==void 0?uid=record.uid:record.data!==null&&typeof record.data=="object"&&(uid=record.data.uid)}return typeof uid=="string"&&uid.length>0&&uid.length<=MAX_UID_LENGTH?uid:void 0}export{FIREBASE_CLAIM_KEY,SekyroFirebaseError,claimsByteLength,firebase,firebaseUserDeleted,firestoreRefreshSignal,rtdbRefreshSignal};
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@sekyro/connect-firebase",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-rc.1",
4
+ "private": false,
5
+ "description": "Sekyro AI connector for Firebase Authentication: writes the verified-human claim as the custom claim sekyro through the Admin SDK, within the 1000-byte budget, and turns onUserDeleted into the connector's deletion policy.",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "import": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "require": {
19
+ "types": "./dist/index.d.cts",
20
+ "default": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE",
30
+ "sbom.cdx.json"
31
+ ],
32
+ "engines": {
33
+ "node": ">=20"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/IBTIKAR-Technologies/ibtikar-identity.git",
41
+ "directory": "packages/sekyro-connect-firebase"
42
+ },
43
+ "keywords": [
44
+ "sekyro",
45
+ "firebase",
46
+ "identity-platform",
47
+ "identity-verification",
48
+ "connector",
49
+ "sdk"
50
+ ],
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "test": "vitest run --exclude 'test/integration/**'",
54
+ "test:integration": "vitest run test/integration",
55
+ "typecheck": "tsc --noEmit",
56
+ "api:report": "api-extractor run --local",
57
+ "api:check": "api-extractor run",
58
+ "check:emulator": "node scripts/check-emulator.mjs"
59
+ },
60
+ "peerDependencies": {
61
+ "@sekyro/node": "^0.1.0-rc.8 || ^0.2.0-rc.0",
62
+ "firebase-admin": "^12.0.0 || ^13.0.0 || ^14.0.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "firebase-admin": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "devDependencies": {
70
+ "@microsoft/api-extractor": "^7",
71
+ "@sekyro/node": "file:../sekyro-node",
72
+ "@types/node": "^20",
73
+ "firebase-admin": "^13.6.0",
74
+ "tsup": "^8",
75
+ "typescript": "^5.7",
76
+ "vitest": "^3"
77
+ }
78
+ }
package/sbom.cdx.json ADDED
@@ -0,0 +1,131 @@
1
+ {
2
+ "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json",
3
+ "bomFormat": "CycloneDX",
4
+ "specVersion": "1.6",
5
+ "version": 1,
6
+ "metadata": {
7
+ "tools": {
8
+ "components": [
9
+ {
10
+ "type": "application",
11
+ "name": "npm",
12
+ "version": "11.12.1"
13
+ },
14
+ {
15
+ "type": "library",
16
+ "name": "cyclonedx-library",
17
+ "group": "@cyclonedx",
18
+ "version": "10.3.0",
19
+ "author": "Jan Kowalleck",
20
+ "description": "Core functionality of CycloneDX for JavaScript (Node.js or WebBrowser).",
21
+ "licenses": [
22
+ {
23
+ "license": {
24
+ "id": "Apache-2.0"
25
+ }
26
+ }
27
+ ],
28
+ "externalReferences": [
29
+ {
30
+ "url": "https://github.com/CycloneDX/cyclonedx-javascript-library/issues",
31
+ "type": "issue-tracker",
32
+ "comment": "as detected from PackageJson property \"bugs.url\""
33
+ },
34
+ {
35
+ "url": "git+https://github.com/CycloneDX/cyclonedx-javascript-library.git",
36
+ "type": "vcs",
37
+ "comment": "as detected from PackageJson property \"repository.url\""
38
+ },
39
+ {
40
+ "url": "https://github.com/CycloneDX/cyclonedx-javascript-library#readme",
41
+ "type": "website",
42
+ "comment": "as detected from PackageJson property \"homepage\""
43
+ }
44
+ ],
45
+ "properties": [
46
+ {
47
+ "name": "cdx:npm:package:constraint:engine:node",
48
+ "value": ">=20.18.0"
49
+ }
50
+ ]
51
+ },
52
+ {
53
+ "type": "application",
54
+ "name": "cyclonedx-npm",
55
+ "group": "@cyclonedx",
56
+ "version": "6.0.1",
57
+ "author": "Jan Kowalleck",
58
+ "description": "Create CycloneDX Software Bill of Materials (SBOM) from NPM projects.",
59
+ "licenses": [
60
+ {
61
+ "license": {
62
+ "id": "Apache-2.0"
63
+ }
64
+ }
65
+ ],
66
+ "externalReferences": [
67
+ {
68
+ "url": "https://github.com/CycloneDX/cyclonedx-node-npm/issues",
69
+ "type": "issue-tracker",
70
+ "comment": "as detected from PackageJson property \"bugs.url\""
71
+ },
72
+ {
73
+ "url": "git+https://github.com/CycloneDX/cyclonedx-node-npm.git",
74
+ "type": "vcs",
75
+ "comment": "as detected from PackageJson property \"repository.url\""
76
+ },
77
+ {
78
+ "url": "https://github.com/CycloneDX/cyclonedx-node-npm#readme",
79
+ "type": "website",
80
+ "comment": "as detected from PackageJson property \"homepage\""
81
+ }
82
+ ],
83
+ "properties": [
84
+ {
85
+ "name": "cdx:npm:package:constraint:engine:node",
86
+ "value": ">=20.18.0"
87
+ },
88
+ {
89
+ "name": "cdx:npm:package:constraint:engine:npm",
90
+ "value": ">=9"
91
+ }
92
+ ]
93
+ }
94
+ ]
95
+ },
96
+ "component": {
97
+ "type": "application",
98
+ "name": "connect-firebase",
99
+ "group": "@sekyro",
100
+ "version": "0.1.0-rc.1",
101
+ "bom-ref": "@sekyro/connect-firebase@0.1.0-rc.1",
102
+ "licenses": [
103
+ {
104
+ "license": {
105
+ "name": "SEE LICENSE IN LICENSE",
106
+ "acknowledgement": "declared"
107
+ }
108
+ }
109
+ ],
110
+ "purl": "pkg:npm/%40sekyro/connect-firebase@0.1.0-rc.1",
111
+ "properties": [
112
+ {
113
+ "name": "cdx:npm:package:path",
114
+ "value": ""
115
+ }
116
+ ]
117
+ },
118
+ "properties": [
119
+ {
120
+ "name": "cdx:reproducible",
121
+ "value": "true"
122
+ }
123
+ ]
124
+ },
125
+ "components": [],
126
+ "dependencies": [
127
+ {
128
+ "ref": "@sekyro/connect-firebase@0.1.0-rc.1"
129
+ }
130
+ ]
131
+ }