@mayurajs/auth-supabase 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 +201 -0
- package/NOTICE +8 -0
- package/README.md +40 -2
- package/dist/index.d.ts +55 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +72 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +110 -0
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,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/auth-supabase
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Supabase Auth](https://supabase.com/docs/guides/auth) access tokens as Mayura server identities: verified with your
|
|
4
|
+
project's published keys, on any runtime, with no dependency.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install mayura @mayurajs/auth-supabase
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { principalId } from 'mayura/auth';
|
|
12
|
+
import { supabaseAuthenticator } from '@mayurajs/auth-supabase';
|
|
13
|
+
|
|
14
|
+
const authenticate = supabaseAuthenticator({
|
|
15
|
+
projectUrl: 'https://abcdefghijklmnopqrst.supabase.co',
|
|
16
|
+
identity: session => session.appMetadata['plan'] === 'pro' ? {
|
|
17
|
+
principalId: principalId('supabase', session.userId),
|
|
18
|
+
projectId: 'acme',
|
|
19
|
+
agentIds: ['support'],
|
|
20
|
+
capabilities: ['runs:submit', 'runs:read'],
|
|
21
|
+
} : null,
|
|
22
|
+
});
|
|
23
|
+
// createAgentServer({ ..., authenticate }); clients send `session.access_token` as the bearer token
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- **What is checked.** Tokens issued by your project (`<projectUrl>/auth/v1`) for signed-in users (audience
|
|
27
|
+
`authenticated`), signed with its asymmetric keys (ES256 or RS256) from `/auth/v1/.well-known/jwks.json`, kept at
|
|
28
|
+
most 10 minutes as Supabase asks. Give `jwtSecret` only while tokens may still be signed with your project's legacy
|
|
29
|
+
secret (HS256); the asymmetric keys keep working alongside it.
|
|
30
|
+
- **Roles.** Only `authenticated` tokens pass by default (`roles`), so the public anon key and `service_role` tokens
|
|
31
|
+
never act as a user. Anonymous users (`is_anonymous`) are refused unless `allowAnonymous`; `requireAal2` accepts only
|
|
32
|
+
users who signed in with a second factor.
|
|
33
|
+
- **What you get.** `identity` receives the user: `userId`, `email`, `phone`, `role`, `aal`, `sessionId`, `anonymous`,
|
|
34
|
+
`appMetadata`, `userMetadata`, and the raw `claims`. Grant from `appMetadata` (set by your server), never from
|
|
35
|
+
`userMetadata`, which users can change themselves. Nothing is granted unless `identity` grants it.
|
|
36
|
+
- **Signing out.** A Supabase access token stays valid until it expires (an hour by default), even after the user signs
|
|
37
|
+
out. Where that matters, check `session.sessionId` against `auth.sessions` in `identity`, or keep tokens short.
|
|
38
|
+
- Options: `projectUrl`, `identity`, `jwtSecret`, `roles`, `audience`, `allowAnonymous`, `requireAal2`, `clockSkewMs`
|
|
39
|
+
(5 s), `maxIdentityMs` (60 s), `fetch`.
|
|
40
|
+
|
|
41
|
+
See [Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';
|
|
2
|
+
/** A verified Supabase Auth user, from the access token's claims. */
|
|
3
|
+
export interface SupabaseSession {
|
|
4
|
+
readonly userId: string;
|
|
5
|
+
readonly email: string | null;
|
|
6
|
+
readonly phone: string | null;
|
|
7
|
+
/** The Postgres role the token stands for: `authenticated` for signed-in users. */
|
|
8
|
+
readonly role: string;
|
|
9
|
+
/** How strongly the user signed in: `aal1`, or `aal2` with a second factor. */
|
|
10
|
+
readonly aal: string | null;
|
|
11
|
+
/** The session, to check against `auth.sessions` where a signed-out session must stop before its token expires. */
|
|
12
|
+
readonly sessionId: string | null;
|
|
13
|
+
readonly anonymous: boolean;
|
|
14
|
+
/** Set only by your server (and Supabase): safe to grant from. */
|
|
15
|
+
readonly appMetadata: Readonly<Record<string, unknown>>;
|
|
16
|
+
/** Editable by the user themselves: never grant from it. */
|
|
17
|
+
readonly userMetadata: Readonly<Record<string, unknown>>;
|
|
18
|
+
/** The token's claims, as verified. */
|
|
19
|
+
readonly claims: JwtClaims;
|
|
20
|
+
}
|
|
21
|
+
export interface SupabaseAuthenticatorOptions {
|
|
22
|
+
/** Your project's URL, such as `https://abcdefghijklmnopqrst.supabase.co` (or its custom domain). */
|
|
23
|
+
readonly projectUrl: string;
|
|
24
|
+
/** What a signed-in user may do, or null to refuse; for example from `session.appMetadata`. */
|
|
25
|
+
readonly identity: (session: SupabaseSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Your project's legacy JWT secret, only while tokens may still be signed with it (HS256). The project's asymmetric
|
|
28
|
+
* keys (ES256, RS256) are always used for the tokens they sign.
|
|
29
|
+
*/
|
|
30
|
+
readonly jwtSecret?: string;
|
|
31
|
+
/** The roles accepted; `['authenticated']` by default, so the public anon key and `service_role` tokens never are. */
|
|
32
|
+
readonly roles?: readonly string[];
|
|
33
|
+
/** The audience tokens must have; `authenticated` by default, as Supabase issues them to signed-in users. */
|
|
34
|
+
readonly audience?: string | readonly string[];
|
|
35
|
+
/** Accept anonymous users (`is_anonymous`); refused by default. */
|
|
36
|
+
readonly allowAnonymous?: boolean;
|
|
37
|
+
/** Accept only users who signed in with a second factor (`aal2`). */
|
|
38
|
+
readonly requireAal2?: boolean;
|
|
39
|
+
/** Clock difference allowed; 5 s by default. */
|
|
40
|
+
readonly clockSkewMs?: number;
|
|
41
|
+
/** The longest an identity lasts before the token is checked again; 60 s by default. */
|
|
42
|
+
readonly maxIdentityMs?: number;
|
|
43
|
+
/** For tests and proxies: the fetch to use for the JWKS. */
|
|
44
|
+
readonly fetch?: typeof fetch;
|
|
45
|
+
}
|
|
46
|
+
/** A Supabase session from verified claims; undefined without a user and role. */
|
|
47
|
+
export declare function supabaseSession(claims: JwtClaims): SupabaseSession | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* A server `authenticate` for Supabase Auth access tokens: issued by your project (`<projectUrl>/auth/v1`) to signed-in
|
|
50
|
+
* users (audience `authenticated`), signed with its asymmetric keys (or, while you still use it, its legacy secret).
|
|
51
|
+
* Only the roles you accept pass (`authenticated` alone by default), anonymous users only if you allow them.
|
|
52
|
+
* `identity` decides what the user may do.
|
|
53
|
+
*/
|
|
54
|
+
export declare function supabaseAuthenticator(options: SupabaseAuthenticatorOptions): Authenticator;
|
|
55
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,aAAa,EAAE,KAAK,aAAa,EAAqB,KAAK,SAAS,EAC1E,MAAM,aAAa,CAAC;AAErB,qEAAqE;AACrE,MAAM,WAAW,eAAe;IA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CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,gDAAgD;IAChD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,wFAAwF;IACxF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,4DAA4D;IAC5D,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CAC/B;AAKD,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,eAAe,GAAG,SAAS,CAO9E;AAWD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,aAAa,CA6B1F"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import { hmacSecret, jwtAuthenticator, jwtVerifier, remoteJwks, } from 'mayura/auth';
|
|
3
|
+
const text = (value) => typeof value === 'string' && value !== '' ? value : null;
|
|
4
|
+
const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? Object.freeze({ ...value }) : Object.freeze({});
|
|
5
|
+
/** A Supabase session from verified claims; undefined without a user and role. */
|
|
6
|
+
export function supabaseSession(claims) {
|
|
7
|
+
if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['role'] !== 'string')
|
|
8
|
+
return undefined;
|
|
9
|
+
return Object.freeze({
|
|
10
|
+
userId: claims.sub, email: text(claims['email']), phone: text(claims['phone']), role: claims['role'], aal: text(claims['aal']),
|
|
11
|
+
sessionId: text(claims['session_id']), anonymous: claims['is_anonymous'] === true,
|
|
12
|
+
appMetadata: record(claims['app_metadata']), userMetadata: record(claims['user_metadata']), claims,
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
/** The project's asymmetric keys for ES256 and RS256 tokens, and the legacy secret for HS256 ones. */
|
|
16
|
+
function keysFor(jwks, secret) {
|
|
17
|
+
return Object.freeze({
|
|
18
|
+
key: (header, options) =>
|
|
19
|
+
// A JWKS never supplies an HMAC secret, so without one HS256 finds no key.
|
|
20
|
+
header.alg === 'HS256' && secret ? secret.key(header, options) : jwks.key(header, options),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A server `authenticate` for Supabase Auth access tokens: issued by your project (`<projectUrl>/auth/v1`) to signed-in
|
|
25
|
+
* users (audience `authenticated`), signed with its asymmetric keys (or, while you still use it, its legacy secret).
|
|
26
|
+
* Only the roles you accept pass (`authenticated` alone by default), anonymous users only if you allow them.
|
|
27
|
+
* `identity` decides what the user may do.
|
|
28
|
+
*/
|
|
29
|
+
export function supabaseAuthenticator(options) {
|
|
30
|
+
if (!options || typeof options.identity !== 'function')
|
|
31
|
+
throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): identity decides what a signed-in user may do.');
|
|
32
|
+
let url;
|
|
33
|
+
try {
|
|
34
|
+
url = new URL(options.projectUrl);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is your project\'s URL, such as https://<ref>.supabase.co.');
|
|
38
|
+
}
|
|
39
|
+
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password)
|
|
40
|
+
throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is an https origin, such as https://<ref>.supabase.co.');
|
|
41
|
+
const roles = options.roles ?? ['authenticated'];
|
|
42
|
+
if (!Array.isArray(roles) || roles.length === 0 || roles.some(role => typeof role !== 'string' || role === ''))
|
|
43
|
+
throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): roles are the Postgres roles accepted, such as authenticated.');
|
|
44
|
+
for (const name of ['allowAnonymous', 'requireAal2']) {
|
|
45
|
+
if (options[name] !== undefined && typeof options[name] !== 'boolean')
|
|
46
|
+
throw new MayuraError('INVALID_CONFIG', `supabaseAuthenticator(): ${name} must be a boolean.`);
|
|
47
|
+
}
|
|
48
|
+
if (options.jwtSecret !== undefined && typeof options.jwtSecret !== 'string')
|
|
49
|
+
throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): jwtSecret is your project\'s legacy JWT secret.');
|
|
50
|
+
const issuer = `${url.origin}/auth/v1`;
|
|
51
|
+
// Supabase caches its JWKS for 10 minutes and asks applications not to keep it longer.
|
|
52
|
+
const jwks = remoteJwks({ url: `${issuer}/.well-known/jwks.json`, maxAgeMs: 600_000, ...(options.fetch ? { fetch: options.fetch } : {}) });
|
|
53
|
+
const secret = options.jwtSecret !== undefined ? hmacSecret(options.jwtSecret) : undefined;
|
|
54
|
+
const verifier = jwtVerifier({
|
|
55
|
+
issuer, audience: options.audience ?? 'authenticated', clockSkewMs: options.clockSkewMs ?? 5_000,
|
|
56
|
+
algorithms: secret ? ['ES256', 'RS256', 'HS256'] : ['ES256', 'RS256'], keys: keysFor(jwks, secret),
|
|
57
|
+
});
|
|
58
|
+
return jwtAuthenticator({
|
|
59
|
+
verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
|
|
60
|
+
identity: claims => {
|
|
61
|
+
const session = supabaseSession(claims);
|
|
62
|
+
if (!session || !roles.includes(session.role))
|
|
63
|
+
return null;
|
|
64
|
+
if (session.anonymous && options.allowAnonymous !== true)
|
|
65
|
+
return null;
|
|
66
|
+
if (options.requireAal2 === true && session.aal !== 'aal2')
|
|
67
|
+
return null;
|
|
68
|
+
return options.identity(session);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
//# 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,EACL,UAAU,EAAE,gBAAgB,EAAE,WAAW,EAAE,UAAU,GAEtD,MAAM,aAAa,CAAC;AAgDrB,MAAM,IAAI,GA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EAAE,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;KACnG,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;QACtB,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClG,QAAQ,EAAE,MAAM,CAAC,EAAE;YACjB,MAAM,OAAO,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;YACxC,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC3D,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,cAAc,KAAK,IAAI;gBAAE,OAAO,IAAI,CAAC;YACtE,IAAI,OAAO,CAAC,WAAW,KAAK,IAAI,IAAI,OAAO,CAAC,GAAG,KAAK,MAAM;gBAAE,OAAO,IAAI,CAAC;YACxE,OAAO,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport {\n hmacSecret, jwtAuthenticator, jwtVerifier, remoteJwks,\n type Authenticator, type IdentityGrant, type JwtAlgorithm, type JwtClaims, type JwtKeySource,\n} from 'mayura/auth';\n\n/** A verified Supabase Auth user, from the access token's claims. */\nexport interface SupabaseSession {\n readonly userId: string;\n readonly email: string | null;\n readonly phone: string | null;\n /** The Postgres role the token stands for: `authenticated` for signed-in users. */\n readonly role: string;\n /** How strongly the user signed in: `aal1`, or `aal2` with a second factor. */\n readonly aal: string | null;\n /** The session, to check against `auth.sessions` where a signed-out session must stop before its token expires. */\n readonly sessionId: string | null;\n readonly anonymous: boolean;\n /** Set only by your server (and Supabase): safe to grant from. */\n readonly appMetadata: Readonly<Record<string, unknown>>;\n /** Editable by the user themselves: never grant from it. */\n readonly userMetadata: Readonly<Record<string, unknown>>;\n /** The token's claims, as verified. */\n readonly claims: JwtClaims;\n}\n\nexport interface SupabaseAuthenticatorOptions {\n /** Your project's URL, such as `https://abcdefghijklmnopqrst.supabase.co` (or its custom domain). */\n readonly projectUrl: string;\n /** What a signed-in user may do, or null to refuse; for example from `session.appMetadata`. */\n readonly identity: (session: SupabaseSession) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /**\n * Your project's legacy JWT secret, only while tokens may still be signed with it (HS256). The project's asymmetric\n * keys (ES256, RS256) are always used for the tokens they sign.\n */\n readonly jwtSecret?: string;\n /** The roles accepted; `['authenticated']` by default, so the public anon key and `service_role` tokens never are. */\n readonly roles?: readonly string[];\n /** The audience tokens must have; `authenticated` by default, as Supabase issues them to signed-in users. */\n readonly audience?: string | readonly string[];\n /** Accept anonymous users (`is_anonymous`); refused by default. */\n readonly allowAnonymous?: boolean;\n /** Accept only users who signed in with a second factor (`aal2`). */\n readonly requireAal2?: boolean;\n /** Clock difference allowed; 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 for the JWKS. */\n readonly fetch?: typeof fetch;\n}\n\nconst text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\nconst record = (value: unknown): Readonly<Record<string, unknown>> => value && typeof value === 'object' && !Array.isArray(value) ? Object.freeze({ ...(value as Record<string, unknown>) }) : Object.freeze({});\n\n/** A Supabase session from verified claims; undefined without a user and role. */\nexport function supabaseSession(claims: JwtClaims): SupabaseSession | undefined {\n if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['role'] !== 'string') return undefined;\n return Object.freeze({\n userId: claims.sub, email: text(claims['email']), phone: text(claims['phone']), role: claims['role'], aal: text(claims['aal']),\n sessionId: text(claims['session_id']), anonymous: claims['is_anonymous'] === true,\n appMetadata: record(claims['app_metadata']), userMetadata: record(claims['user_metadata']), claims,\n });\n}\n\n/** The project's asymmetric keys for ES256 and RS256 tokens, and the legacy secret for HS256 ones. */\nfunction keysFor(jwks: JwtKeySource, secret: JwtKeySource | undefined): JwtKeySource {\n return Object.freeze({\n key: (header: { readonly alg: JwtAlgorithm; readonly kid?: string }, options: { readonly signal: AbortSignal }) =>\n // A JWKS never supplies an HMAC secret, so without one HS256 finds no key.\n header.alg === 'HS256' && secret ? secret.key(header, options) : jwks.key(header, options),\n });\n}\n\n/**\n * A server `authenticate` for Supabase Auth access tokens: issued by your project (`<projectUrl>/auth/v1`) to signed-in\n * users (audience `authenticated`), signed with its asymmetric keys (or, while you still use it, its legacy secret).\n * Only the roles you accept pass (`authenticated` alone by default), anonymous users only if you allow them.\n * `identity` decides what the user may do.\n */\nexport function supabaseAuthenticator(options: SupabaseAuthenticatorOptions): Authenticator {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): identity decides what a signed-in user may do.');\n let url: URL;\n try { url = new URL(options.projectUrl); } catch { throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is your project\\'s URL, such as https://<ref>.supabase.co.'); }\n if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is an https origin, such as https://<ref>.supabase.co.');\n const roles = options.roles ?? ['authenticated'];\n if (!Array.isArray(roles) || roles.length === 0 || roles.some(role => typeof role !== 'string' || role === '')) throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): roles are the Postgres roles accepted, such as authenticated.');\n for (const name of ['allowAnonymous', 'requireAal2'] as const) {\n if (options[name] !== undefined && typeof options[name] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `supabaseAuthenticator(): ${name} must be a boolean.`);\n }\n if (options.jwtSecret !== undefined && typeof options.jwtSecret !== 'string') throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): jwtSecret is your project\\'s legacy JWT secret.');\n const issuer = `${url.origin}/auth/v1`;\n // Supabase caches its JWKS for 10 minutes and asks applications not to keep it longer.\n const jwks = remoteJwks({ url: `${issuer}/.well-known/jwks.json`, maxAgeMs: 600_000, ...(options.fetch ? { fetch: options.fetch } : {}) });\n const secret = options.jwtSecret !== undefined ? hmacSecret(options.jwtSecret) : undefined;\n const verifier = jwtVerifier({\n issuer, audience: options.audience ?? 'authenticated', clockSkewMs: options.clockSkewMs ?? 5_000,\n algorithms: secret ? ['ES256', 'RS256', 'HS256'] : ['ES256', 'RS256'], keys: keysFor(jwks, secret),\n });\n return jwtAuthenticator({\n verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),\n identity: claims => {\n const session = supabaseSession(claims);\n if (!session || !roles.includes(session.role)) return null;\n if (session.anonymous && options.allowAnonymous !== true) return null;\n if (options.requireAal2 === true && session.aal !== 'aal2') return null;\n return options.identity(session);\n },\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/auth-supabase",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Supabase Auth access tokens as Mayura server identities, verified with your project's published keys.",
|
|
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-supabase"
|
|
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,110 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import {
|
|
3
|
+
hmacSecret, jwtAuthenticator, jwtVerifier, remoteJwks,
|
|
4
|
+
type Authenticator, type IdentityGrant, type JwtAlgorithm, type JwtClaims, type JwtKeySource,
|
|
5
|
+
} from 'mayura/auth';
|
|
6
|
+
|
|
7
|
+
/** A verified Supabase Auth user, from the access token's claims. */
|
|
8
|
+
export interface SupabaseSession {
|
|
9
|
+
readonly userId: string;
|
|
10
|
+
readonly email: string | null;
|
|
11
|
+
readonly phone: string | null;
|
|
12
|
+
/** The Postgres role the token stands for: `authenticated` for signed-in users. */
|
|
13
|
+
readonly role: string;
|
|
14
|
+
/** How strongly the user signed in: `aal1`, or `aal2` with a second factor. */
|
|
15
|
+
readonly aal: string | null;
|
|
16
|
+
/** The session, to check against `auth.sessions` where a signed-out session must stop before its token expires. */
|
|
17
|
+
readonly sessionId: string | null;
|
|
18
|
+
readonly anonymous: boolean;
|
|
19
|
+
/** Set only by your server (and Supabase): safe to grant from. */
|
|
20
|
+
readonly appMetadata: Readonly<Record<string, unknown>>;
|
|
21
|
+
/** Editable by the user themselves: never grant from it. */
|
|
22
|
+
readonly userMetadata: Readonly<Record<string, unknown>>;
|
|
23
|
+
/** The token's claims, as verified. */
|
|
24
|
+
readonly claims: JwtClaims;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SupabaseAuthenticatorOptions {
|
|
28
|
+
/** Your project's URL, such as `https://abcdefghijklmnopqrst.supabase.co` (or its custom domain). */
|
|
29
|
+
readonly projectUrl: string;
|
|
30
|
+
/** What a signed-in user may do, or null to refuse; for example from `session.appMetadata`. */
|
|
31
|
+
readonly identity: (session: SupabaseSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
32
|
+
/**
|
|
33
|
+
* Your project's legacy JWT secret, only while tokens may still be signed with it (HS256). The project's asymmetric
|
|
34
|
+
* keys (ES256, RS256) are always used for the tokens they sign.
|
|
35
|
+
*/
|
|
36
|
+
readonly jwtSecret?: string;
|
|
37
|
+
/** The roles accepted; `['authenticated']` by default, so the public anon key and `service_role` tokens never are. */
|
|
38
|
+
readonly roles?: readonly string[];
|
|
39
|
+
/** The audience tokens must have; `authenticated` by default, as Supabase issues them to signed-in users. */
|
|
40
|
+
readonly audience?: string | readonly string[];
|
|
41
|
+
/** Accept anonymous users (`is_anonymous`); refused by default. */
|
|
42
|
+
readonly allowAnonymous?: boolean;
|
|
43
|
+
/** Accept only users who signed in with a second factor (`aal2`). */
|
|
44
|
+
readonly requireAal2?: boolean;
|
|
45
|
+
/** Clock difference allowed; 5 s by default. */
|
|
46
|
+
readonly clockSkewMs?: number;
|
|
47
|
+
/** The longest an identity lasts before the token is checked again; 60 s by default. */
|
|
48
|
+
readonly maxIdentityMs?: number;
|
|
49
|
+
/** For tests and proxies: the fetch to use for the JWKS. */
|
|
50
|
+
readonly fetch?: typeof fetch;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
|
|
54
|
+
const record = (value: unknown): Readonly<Record<string, unknown>> => value && typeof value === 'object' && !Array.isArray(value) ? Object.freeze({ ...(value as Record<string, unknown>) }) : Object.freeze({});
|
|
55
|
+
|
|
56
|
+
/** A Supabase session from verified claims; undefined without a user and role. */
|
|
57
|
+
export function supabaseSession(claims: JwtClaims): SupabaseSession | undefined {
|
|
58
|
+
if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['role'] !== 'string') return undefined;
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
userId: claims.sub, email: text(claims['email']), phone: text(claims['phone']), role: claims['role'], aal: text(claims['aal']),
|
|
61
|
+
sessionId: text(claims['session_id']), anonymous: claims['is_anonymous'] === true,
|
|
62
|
+
appMetadata: record(claims['app_metadata']), userMetadata: record(claims['user_metadata']), claims,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The project's asymmetric keys for ES256 and RS256 tokens, and the legacy secret for HS256 ones. */
|
|
67
|
+
function keysFor(jwks: JwtKeySource, secret: JwtKeySource | undefined): JwtKeySource {
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
key: (header: { readonly alg: JwtAlgorithm; readonly kid?: string }, options: { readonly signal: AbortSignal }) =>
|
|
70
|
+
// A JWKS never supplies an HMAC secret, so without one HS256 finds no key.
|
|
71
|
+
header.alg === 'HS256' && secret ? secret.key(header, options) : jwks.key(header, options),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A server `authenticate` for Supabase Auth access tokens: issued by your project (`<projectUrl>/auth/v1`) to signed-in
|
|
77
|
+
* users (audience `authenticated`), signed with its asymmetric keys (or, while you still use it, its legacy secret).
|
|
78
|
+
* Only the roles you accept pass (`authenticated` alone by default), anonymous users only if you allow them.
|
|
79
|
+
* `identity` decides what the user may do.
|
|
80
|
+
*/
|
|
81
|
+
export function supabaseAuthenticator(options: SupabaseAuthenticatorOptions): Authenticator {
|
|
82
|
+
if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): identity decides what a signed-in user may do.');
|
|
83
|
+
let url: URL;
|
|
84
|
+
try { url = new URL(options.projectUrl); } catch { throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is your project\'s URL, such as https://<ref>.supabase.co.'); }
|
|
85
|
+
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): projectUrl is an https origin, such as https://<ref>.supabase.co.');
|
|
86
|
+
const roles = options.roles ?? ['authenticated'];
|
|
87
|
+
if (!Array.isArray(roles) || roles.length === 0 || roles.some(role => typeof role !== 'string' || role === '')) throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): roles are the Postgres roles accepted, such as authenticated.');
|
|
88
|
+
for (const name of ['allowAnonymous', 'requireAal2'] as const) {
|
|
89
|
+
if (options[name] !== undefined && typeof options[name] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `supabaseAuthenticator(): ${name} must be a boolean.`);
|
|
90
|
+
}
|
|
91
|
+
if (options.jwtSecret !== undefined && typeof options.jwtSecret !== 'string') throw new MayuraError('INVALID_CONFIG', 'supabaseAuthenticator(): jwtSecret is your project\'s legacy JWT secret.');
|
|
92
|
+
const issuer = `${url.origin}/auth/v1`;
|
|
93
|
+
// Supabase caches its JWKS for 10 minutes and asks applications not to keep it longer.
|
|
94
|
+
const jwks = remoteJwks({ url: `${issuer}/.well-known/jwks.json`, maxAgeMs: 600_000, ...(options.fetch ? { fetch: options.fetch } : {}) });
|
|
95
|
+
const secret = options.jwtSecret !== undefined ? hmacSecret(options.jwtSecret) : undefined;
|
|
96
|
+
const verifier = jwtVerifier({
|
|
97
|
+
issuer, audience: options.audience ?? 'authenticated', clockSkewMs: options.clockSkewMs ?? 5_000,
|
|
98
|
+
algorithms: secret ? ['ES256', 'RS256', 'HS256'] : ['ES256', 'RS256'], keys: keysFor(jwks, secret),
|
|
99
|
+
});
|
|
100
|
+
return jwtAuthenticator({
|
|
101
|
+
verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
|
|
102
|
+
identity: claims => {
|
|
103
|
+
const session = supabaseSession(claims);
|
|
104
|
+
if (!session || !roles.includes(session.role)) return null;
|
|
105
|
+
if (session.anonymous && options.allowAnonymous !== true) return null;
|
|
106
|
+
if (options.requireAal2 === true && session.aal !== 'aal2') return null;
|
|
107
|
+
return options.identity(session);
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}
|