@miguelmorales13/nestkit 0.20.0 → 0.22.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.
@@ -4,3 +4,23 @@ export declare class MagicLinkRequestDto {
4
4
  export declare class MagicLinkVerifyDto {
5
5
  token: string;
6
6
  }
7
+ export declare class TwoFactorCodeDto {
8
+ code: string;
9
+ }
10
+ export declare class MfaVerifyDto {
11
+ challenge: string;
12
+ code: string;
13
+ }
14
+ export declare class PasskeyRegisterDto {
15
+ token: string;
16
+ /** The JSON `navigator.credentials.create()` produced (via `@simplewebauthn/browser`). */
17
+ response: Record<string, unknown>;
18
+ name?: string;
19
+ }
20
+ export declare class PasskeyLoginOptionsDto {
21
+ email?: string;
22
+ }
23
+ export declare class PasskeyLoginDto {
24
+ token: string;
25
+ response: Record<string, unknown>;
26
+ }
@@ -0,0 +1,19 @@
1
+ import type { Passkey, PasskeyStorePort, TwoFactorRecord, TwoFactorStorePort } from './oauth.ports.js';
2
+ /** In-memory `TwoFactorStorePort`, for development and tests. Gone on restart. */
3
+ export declare class MemoryTwoFactorStore implements TwoFactorStorePort {
4
+ private readonly records;
5
+ get(userId: string): Promise<TwoFactorRecord | null>;
6
+ set(userId: string, record: TwoFactorRecord): Promise<void>;
7
+ delete(userId: string): Promise<void>;
8
+ claimStep(userId: string, step: number): Promise<boolean>;
9
+ consumeBackupCode(userId: string, hash: string): Promise<boolean>;
10
+ }
11
+ /** In-memory `PasskeyStorePort`, for development and tests. Gone on restart. */
12
+ export declare class MemoryPasskeyStore implements PasskeyStorePort {
13
+ private readonly passkeys;
14
+ listByUser(userId: string): Promise<Passkey[]>;
15
+ findById(id: string): Promise<Passkey | null>;
16
+ create(passkey: Passkey): Promise<void>;
17
+ touch(id: string, counter: number, lastUsedAt: Date): Promise<void>;
18
+ delete(id: string, userId: string): Promise<boolean>;
19
+ }
@@ -1,8 +1,34 @@
1
+ import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server';
1
2
  import { type OAuthProfile, type OAuthProviderConfig } from './oauth-provider.js';
2
3
  import { type OAuthAuthOptions, type ResolvedOAuthOptions } from './oauth.options.js';
3
- import type { MagicLinkSenderPort, MagicLinkStorePort, OAuthStorePort, OAuthUser, RefreshTokenStorePort } from './oauth.ports.js';
4
+ import type { MagicLinkSenderPort, MagicLinkStorePort, OAuthStorePort, OAuthUser, Passkey, PasskeyStorePort, RefreshTokenStorePort, TwoFactorStorePort } from './oauth.ports.js';
5
+ import { type WebAuthnPort } from './webauthn.port.js';
4
6
  /** The stored provider key a magic-link session reports as its origin. */
5
7
  export declare const MAGIC_LINK_PROVIDER = "email";
8
+ /**
9
+ * A sign-in that stopped short of a session because the account has a
10
+ * second factor. The client shows the code screen and sends `challenge`
11
+ * back with the code to `verifyMfa`.
12
+ */
13
+ export interface MfaChallenge {
14
+ mfaRequired: true;
15
+ challenge: string;
16
+ expiresAt: Date;
17
+ }
18
+ export type SessionResult = {
19
+ user: unknown;
20
+ } & TokenPair;
21
+ export type SignInResult = SessionResult | MfaChallenge;
22
+ export declare function isMfaChallenge(result: SignInResult): result is MfaChallenge;
23
+ /** What the settings screen sees of a passkey — never the public key. */
24
+ export interface PasskeySummary {
25
+ id: string;
26
+ name: string | null;
27
+ deviceType: Passkey['deviceType'];
28
+ backedUp: boolean;
29
+ createdAt: Date;
30
+ lastUsedAt: Date | null;
31
+ }
6
32
  export interface TokenPair {
7
33
  accessToken: string;
8
34
  refreshToken: string;
@@ -23,8 +49,11 @@ export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
23
49
  private readonly sessions;
24
50
  private readonly magicLinks?;
25
51
  private readonly magicLinkSender?;
52
+ private readonly twoFactor?;
53
+ private readonly passkeys?;
54
+ private readonly webauthnImpl?;
26
55
  private readonly options;
27
- constructor(options: OAuthAuthOptions<U>, store: OAuthStorePort<U>, sessions: RefreshTokenStorePort, magicLinks?: MagicLinkStorePort | undefined, magicLinkSender?: MagicLinkSenderPort | undefined);
56
+ constructor(options: OAuthAuthOptions<U>, store: OAuthStorePort<U>, sessions: RefreshTokenStorePort, magicLinks?: MagicLinkStorePort | undefined, magicLinkSender?: MagicLinkSenderPort | undefined, twoFactor?: TwoFactorStorePort | undefined, passkeys?: PasskeyStorePort | undefined, webauthnImpl?: WebAuthnPort | undefined);
28
57
  get config(): ResolvedOAuthOptions<U>;
29
58
  /**
30
59
  * Looks up a configured provider, or explains that it is unavailable.
@@ -65,19 +94,30 @@ export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
65
94
  * proves the pair was not simply invented by whoever crafted the URL.
66
95
  */
67
96
  verifyState(received: string | undefined, fromCookie: string | undefined, provider: string): boolean;
68
- /** Exchanges the callback's `code` for a normalised profile. */
69
- profileFromCode(name: string, code: string): Promise<OAuthProfile>;
97
+ /**
98
+ * Exchanges the callback's `code` for a normalised profile.
99
+ *
100
+ * `callback` is whatever came back alongside the code — the query string,
101
+ * or the form body for a POST callback. Apple is why it is passed through:
102
+ * the person's name arrives there, on the first authorisation only.
103
+ *
104
+ * A profile with no email is returned as is, not rejected: whether that is
105
+ * a problem depends on what happens next. Linking an already-signed-in
106
+ * user needs none, and neither does signing in to an account linked
107
+ * earlier. `login` is where the absence stops things, and only when it
108
+ * would have to create an account from it.
109
+ */
110
+ profileFromCode(name: string, code: string, callback?: Record<string, unknown>): Promise<OAuthProfile>;
70
111
  /**
71
112
  * Signs someone in, creating the account the first time.
72
113
  *
73
114
  * The provider is a parameter because the flow is identical for all of
74
115
  * them: find the linked account, and failing that link by email to whoever
75
116
  * is already registered. That email link is what makes signing in with
76
- * Facebook today and Google tomorrow land on one account instead of two.
117
+ * Facebook today and Google tomorrow land on one account instead of two —
118
+ * and why the email must be one the provider verified (see `OAuthProfile`).
77
119
  */
78
- login(providerName: string, profile: OAuthProfile): Promise<{
79
- user: unknown;
80
- } & TokenPair>;
120
+ login(providerName: string, profile: OAuthProfile): Promise<SignInResult>;
81
121
  /**
82
122
  * Sends a sign-in link to an address.
83
123
  *
@@ -100,18 +140,132 @@ export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
100
140
  * touched: a link carries no name or photo, and running `syncProfile` with
101
141
  * an empty profile would erase what the OAuth provider supplied.
102
142
  */
103
- magicLinkLogin(rawToken: string): Promise<{
104
- user: unknown;
105
- } & TokenPair>;
143
+ magicLinkLogin(rawToken: string): Promise<SignInResult>;
106
144
  /** Whether the magic-link routes can work in this app. */
107
145
  get magicLinkEnabled(): boolean;
108
146
  private requireMagicLink;
109
147
  /**
110
- * The one place a session is opened. Every sign-in — OAuth or magic link —
111
- * ends here, so `singleSession` and the token pair behave identically
112
- * whichever door was used.
148
+ * The one place a session is opened. Every sign-in — OAuth, magic link,
149
+ * passkey, a second factor just passed — ends here, so `singleSession`,
150
+ * the token pair and the second-factor rule behave identically whichever
151
+ * door was used.
152
+ *
153
+ * `strong` says the door already verified the person beyond a shared
154
+ * secret: a passkey (the device checked their face or finger) or the
155
+ * second factor itself. Anything else, for an account with 2FA confirmed,
156
+ * gets a challenge instead of a session.
113
157
  */
114
158
  private establishSession;
159
+ twoFactorStatus(userId: string): Promise<{
160
+ enabled: boolean;
161
+ backupCodesLeft: number;
162
+ }>;
163
+ /**
164
+ * Starts enrolment: a fresh secret, parked unconfirmed, and the URI the
165
+ * QR code encodes. Nothing changes for sign-in until `twoFactorConfirm`
166
+ * sees a code from the app — a person who scans and closes the tab must
167
+ * not be locked out of an account whose second factor they never finished.
168
+ */
169
+ twoFactorSetup(userId: string): Promise<{
170
+ secret: string;
171
+ otpauthUri: string;
172
+ }>;
173
+ /** Turns the pending secret on, once a code proves the app has it. Hands out the backup codes — the only time they are readable. */
174
+ twoFactorConfirm(userId: string, code: string): Promise<{
175
+ backupCodes: string[];
176
+ }>;
177
+ /** Off, but only for whoever can still produce a code or a backup code. */
178
+ twoFactorDisable(userId: string, code: string): Promise<void>;
179
+ /** Completes a sign-in that stopped at {@link MfaChallenge}. */
180
+ verifyMfa(challenge: string, code: string): Promise<SessionResult>;
181
+ private hasSecondFactor;
182
+ private issueMfaChallenge;
183
+ /**
184
+ * A TOTP code, or failing that a backup code. Each accepted once: the step
185
+ * is claimed and the backup code consumed atomically, so a code seen over
186
+ * a shoulder is spent by whoever typed it first.
187
+ */
188
+ private checkSecondFactor;
189
+ private invalidCode;
190
+ private requireTwoFactor;
191
+ /**
192
+ * Options for `navigator.credentials.create()`, and the token that ties
193
+ * the answer back to this challenge.
194
+ *
195
+ * `residentKey: 'required'` is not negotiable. A discoverable credential
196
+ * is what iCloud Keychain stores and syncs reliably — a non-discoverable
197
+ * one made iOS answer "no passkeys for this site" on the next open — and
198
+ * it is the only kind the browser can offer in the username field's
199
+ * autofill, which is the sign-in experience passkeys exist for.
200
+ */
201
+ passkeyRegistrationOptions(userId: string): Promise<{
202
+ options: unknown;
203
+ token: string;
204
+ }>;
205
+ /** Verifies the authenticator's answer and keeps the public key. */
206
+ passkeyRegister(userId: string, token: string, response: RegistrationResponseJSON, name?: string): Promise<PasskeySummary>;
207
+ /**
208
+ * Options for `navigator.credentials.get()`.
209
+ *
210
+ * With no email — the usual case — `allowCredentials` is empty and the
211
+ * browser offers whatever discoverable passkeys it holds for this site,
212
+ * including in the username field's autofill (`mediation: 'conditional'`
213
+ * on the client). With one, the known credentials are listed, which some
214
+ * platforms use to go straight to the biometric prompt. An unknown email
215
+ * gets the same empty list as no email, so nothing reveals which is which.
216
+ */
217
+ passkeyAuthenticationOptions(email?: string): Promise<{
218
+ options: unknown;
219
+ token: string;
220
+ }>;
221
+ /**
222
+ * Signs in with the authenticator's answer. The credential id in the
223
+ * answer says who; the signature over the challenge proves it.
224
+ *
225
+ * The counter is persisted only when it moved. Synced passkeys report 0
226
+ * forever, and a store that insists on "greater than before" would refuse
227
+ * every one of them — which is how a passkey sign-in "randomly" breaks on
228
+ * iPhones. The library already rejects a counter that went backwards on
229
+ * hardware that does count, which is the actual clone signal.
230
+ */
231
+ passkeyLogin(token: string, response: AuthenticationResponseJSON): Promise<SessionResult>;
232
+ /** The verification both sign-in and unlock share: the credential named in the answer, checked against the challenge, counter touched. */
233
+ private verifyPasskeyAnswer;
234
+ /**
235
+ * Options to re-verify the signed-in person — a lock screen over a session
236
+ * that never expires, opened with Face ID when the app comes back.
237
+ *
238
+ * Not `passkeyAuthenticationOptions`: the user is known, so their own
239
+ * credentials are listed (some platforms then go straight to the biometric
240
+ * prompt), and the token is bound to them so an unlock answer can never be
241
+ * replayed as somebody else's.
242
+ */
243
+ passkeyUnlockOptions(userId: string): Promise<{
244
+ options: unknown;
245
+ token: string;
246
+ }>;
247
+ /**
248
+ * Verifies an unlock answer. Opens no session and rotates no token: the
249
+ * session the person already has stays exactly as it was, and the answer
250
+ * is only accepted for a passkey that belongs to them.
251
+ */
252
+ passkeyUnlock(userId: string, token: string, response: AuthenticationResponseJSON): Promise<{
253
+ ok: true;
254
+ passkeyId: string;
255
+ }>;
256
+ listPasskeys(userId: string): Promise<PasskeySummary[]>;
257
+ deletePasskey(userId: string, id: string): Promise<void>;
258
+ private webauthn;
259
+ /**
260
+ * The challenge travels signed, not stored: no table, no cleanup, and it
261
+ * expires by itself — the same reasoning as the OAuth `state`. `typ` keeps
262
+ * a registration token from passing as a sign-in one, and `sub` ties a
263
+ * registration to the account that asked for it.
264
+ */
265
+ private signChallenge;
266
+ private readChallenge;
267
+ private invalidPasskey;
268
+ private requirePasskeys;
115
269
  /**
116
270
  * Rotates a refresh token: the old one is spent, a new pair comes back.
117
271
  *
@@ -19,10 +19,26 @@
19
19
  export interface OAuthProfile {
20
20
  /** The provider's own id for this person. Stable; the email is not. */
21
21
  providerAccountId: string;
22
- email: string;
22
+ /**
23
+ * Only an email the provider has **verified**. An unverified one must be
24
+ * left out: linking by email is how one account is joined across
25
+ * providers, and an attacker who registers a Discord with the victim's
26
+ * address — unverified — would otherwise sign in as them. Absent for
27
+ * providers that give none (TikTok): such an account can be linked to a
28
+ * signed-in user and used to sign in afterwards, never to sign up.
29
+ */
30
+ email?: string;
23
31
  name?: string;
24
32
  avatarUrl?: string;
25
33
  }
34
+ /** The token endpoint's answer, whole. What `fetchProfile` gets besides the access token. */
35
+ export interface OAuthTokens {
36
+ access_token?: string;
37
+ /** OpenID providers (Apple, Google, LinkedIn) put the identity here. */
38
+ id_token?: string;
39
+ refresh_token?: string;
40
+ [key: string]: unknown;
41
+ }
26
42
  export interface OAuthProviderConfig {
27
43
  /**
28
44
  * Route segment and stored provider key: `/auth/google`. Whatever goes in
@@ -31,7 +47,12 @@ export interface OAuthProviderConfig {
31
47
  */
32
48
  name: string;
33
49
  clientId?: string;
34
- clientSecret?: string;
50
+ /**
51
+ * A string, or a function for providers whose secret is minted: Apple's
52
+ * is a short-lived JWT signed with the team's private key. Called at every
53
+ * exchange; memoise inside if minting is expensive.
54
+ */
55
+ clientSecret?: string | (() => string | Promise<string>);
35
56
  /**
36
57
  * Must match the redirect URI registered with the provider **exactly**,
37
58
  * including the path prefix the app is mounted under. A mismatch is
@@ -45,8 +66,25 @@ export interface OAuthProviderConfig {
45
66
  scope: string;
46
67
  /** Extra query parameters for the consent screen (`prompt`, `access_type`…). */
47
68
  authorizeParams?: Record<string, string>;
48
- /** Fetches the profile with the provider's access token and normalises it. */
49
- fetchProfile(accessToken: string): Promise<OAuthProfile>;
69
+ /**
70
+ * What the provider calls the client id, in both the consent URL and the
71
+ * token exchange. `client_id` for everyone but TikTok, which says
72
+ * `client_key` and rejects the other.
73
+ */
74
+ clientIdParam?: string;
75
+ /**
76
+ * How the provider sends the browser back. Apple, with `response_mode=
77
+ * form_post`, POSTs `code` and `state` as a form; everyone else redirects
78
+ * with a query string. Default `GET`. A POST callback is a cross-site
79
+ * request, so the cookies it needs are written `SameSite=None`.
80
+ */
81
+ callbackMethod?: 'GET' | 'POST';
82
+ /**
83
+ * Turns the tokens into a profile. `tokens` is the token endpoint's whole
84
+ * answer (for an `id_token`); `callback` is what came back with the code —
85
+ * Apple puts the person's name there, once, and nowhere else.
86
+ */
87
+ fetchProfile(accessToken: string, tokens: OAuthTokens, callback: Record<string, unknown>): Promise<OAuthProfile>;
50
88
  }
51
89
  export interface ProviderCredentials {
52
90
  clientId?: string;
@@ -55,6 +93,15 @@ export interface ProviderCredentials {
55
93
  /** Overrides the default scope. */
56
94
  scope?: string;
57
95
  }
96
+ /**
97
+ * Reads a provider's JSON, or throws with the body when it fails.
98
+ *
99
+ * Providers answer errors with a 200 and an `error` field about as often as
100
+ * with a status code, so the status alone is not enough to tell success from
101
+ * failure — and a silent `undefined` here surfaces much later as "no email",
102
+ * far from the call that actually failed.
103
+ */
104
+ export declare function readJson(response: Response, what: string): Promise<Record<string, unknown>>;
58
105
  /**
59
106
  * Google. Returns the email verified by Google itself, so it is safe to link
60
107
  * accounts on.
@@ -69,5 +116,7 @@ export declare function googleProvider(credentials?: ProviderCredentials): OAuth
69
116
  export declare function facebookProvider(credentials?: ProviderCredentials): OAuthProviderConfig;
70
117
  /** The consent-screen URL to send the browser to. */
71
118
  export declare function buildAuthorizeUrl(provider: OAuthProviderConfig, state?: string): string;
72
- /** Trades the `code` from the callback for the provider's access token. */
119
+ /** Trades the `code` from the callback for the token endpoint's whole answer. */
120
+ export declare function exchangeCode(provider: OAuthProviderConfig, code: string): Promise<OAuthTokens>;
121
+ /** The access token alone — what most providers' profile endpoints need. */
73
122
  export declare function exchangeCodeForToken(provider: OAuthProviderConfig, code: string): Promise<string>;
@@ -9,6 +9,56 @@ export declare const REFRESH_TOKEN_STORE: unique symbol;
9
9
  export declare const MAGIC_LINK_STORE: unique symbol;
10
10
  /** Bind to an implementation of `MagicLinkSenderPort`. Optional, same rule. */
11
11
  export declare const MAGIC_LINK_SENDER: unique symbol;
12
+ /** Bind to a `TwoFactorStorePort`. Optional: without it no one has a second factor and the 2FA routes answer 503. */
13
+ export declare const TWO_FACTOR_STORE: unique symbol;
14
+ /** Bind to a `PasskeyStorePort`. Optional: without it the passkey routes answer 503. */
15
+ export declare const PASSKEY_STORE: unique symbol;
16
+ /**
17
+ * Bind to a `WebAuthnPort` to replace the WebAuthn implementation. Left
18
+ * unbound, `@simplewebauthn/server` is loaded lazily on first use — tests
19
+ * bind a fake here rather than needing an authenticator.
20
+ */
21
+ export declare const WEBAUTHN: unique symbol;
22
+ export interface TwoFactorOptions {
23
+ /** What the authenticator app shows above the code. Defaults to the host of `webUrl`. */
24
+ issuer?: string;
25
+ /** How long a sign-in may wait for its code. Default 5 minutes. */
26
+ challengeTtlSeconds?: number;
27
+ /** How many one-time backup codes to hand out on confirmation. Default 10. */
28
+ backupCodes?: number;
29
+ /**
30
+ * Where a redirect flow (OAuth callback, magic-link callback) lands when
31
+ * the account needs its second factor. Default `${webUrl}/two-factor#challenge=…`:
32
+ * the page reads the fragment, asks for the code and calls `POST /auth/2fa/verify`.
33
+ */
34
+ onMfaRedirect?(challenge: string): string;
35
+ /** Shown when the code is wrong or the challenge expired. Reaches the user. */
36
+ invalidCodeMessage?(): string;
37
+ }
38
+ export interface PasskeyOptions {
39
+ /**
40
+ * The relying party id — the domain passkeys are bound to, **without
41
+ * scheme or port**. Defaults to the hostname of `webUrl`. Must be the
42
+ * site's registrable domain or a parent of it; a passkey created for
43
+ * `app.example.com` will not be offered on `example.com`, and one for a
44
+ * wrong id is a passkey nobody can ever use.
45
+ */
46
+ rpId?: string;
47
+ /** Shown by the OS in the creation dialog. Defaults to `rpId`. */
48
+ rpName?: string;
49
+ /** Every origin the ceremony may run on. Defaults to `[webUrl]`. */
50
+ origins?: string[];
51
+ /** How long a challenge stays valid. Default 5 minutes. */
52
+ challengeTtlSeconds?: number;
53
+ /**
54
+ * Whether the authenticator must verify the person (Face ID, fingerprint,
55
+ * PIN). Default `required`: a passkey sign-in skips the second factor, so
56
+ * it has to *be* one. `preferred` lets a security key without PIN through.
57
+ */
58
+ userVerification?: 'required' | 'preferred';
59
+ /** Shown when a registration or sign-in does not verify. Reaches the user. */
60
+ invalidMessage?(): string;
61
+ }
12
62
  export interface MagicLinkOptions {
13
63
  /**
14
64
  * How long a link works. Default 15 minutes: long enough to open the inbox
@@ -101,6 +151,10 @@ export interface OAuthAuthOptions<U extends OAuthUser = OAuthUser> {
101
151
  syncProfile?: ProfileSyncPolicy<U>;
102
152
  /** Passwordless sign-in by email. Needs `MAGIC_LINK_STORE` and `MAGIC_LINK_SENDER` bound. */
103
153
  magicLink?: MagicLinkOptions;
154
+ /** Authenticator-app second factor. Needs `TWO_FACTOR_STORE` bound. */
155
+ twoFactor?: TwoFactorOptions;
156
+ /** Passkeys (WebAuthn). Needs `PASSKEY_STORE` bound and `@simplewebauthn/server` installed. */
157
+ passkeys?: PasskeyOptions;
104
158
  /**
105
159
  * Shapes the user in API responses. Without it the stored row goes out
106
160
  * whole, password hashes and internal columns included — so anything with
@@ -122,11 +176,13 @@ export interface OAuthAuthOptions<U extends OAuthUser = OAuthUser> {
122
176
  genericErrorMessage?(): string;
123
177
  }
124
178
  /** Everything above, with the defaults filled in. Internal. */
125
- export interface ResolvedOAuthOptions<U extends OAuthUser = OAuthUser> extends Required<Omit<OAuthAuthOptions<U>, 'accessSecret' | 'refreshSecret' | 'cookie' | 'mapUser' | 'syncProfile' | 'magicLink'>> {
179
+ export interface ResolvedOAuthOptions<U extends OAuthUser = OAuthUser> extends Required<Omit<OAuthAuthOptions<U>, 'accessSecret' | 'refreshSecret' | 'cookie' | 'mapUser' | 'syncProfile' | 'magicLink' | 'twoFactor' | 'passkeys'>> {
126
180
  accessSecret?: string;
127
181
  refreshSecret?: string;
128
182
  cookie: Required<OAuthCookieOptions>;
129
183
  magicLink: Required<MagicLinkOptions>;
184
+ twoFactor: Required<TwoFactorOptions>;
185
+ passkeys: Required<PasskeyOptions>;
130
186
  mapUser?(user: U): unknown;
131
187
  syncProfile: ProfileSyncPolicy<U>;
132
188
  }
@@ -122,3 +122,61 @@ export interface MagicLinkDelivery {
122
122
  export interface MagicLinkSenderPort {
123
123
  send(delivery: MagicLinkDelivery): Promise<void>;
124
124
  }
125
+ /** One person's authenticator-app setup. `confirmedAt` null until the first code is entered. */
126
+ export interface TwoFactorRecord {
127
+ /** Base32, as the QR code carries it. Encrypt at rest if the database is shared. */
128
+ secret: string;
129
+ confirmedAt: Date | null;
130
+ /** SHA-256 of each unused backup code. A used one is removed. */
131
+ backupCodeHashes: string[];
132
+ /** The last TOTP step accepted, so the same code is never accepted twice. */
133
+ lastStep: number | null;
134
+ }
135
+ /**
136
+ * Persistence for two-factor (TOTP) setups, one row per user.
137
+ *
138
+ * `claimStep` and `consumeBackupCode` **must be atomic** (a conditional
139
+ * UPDATE), for the same reason `revokeIfActive` is: a code seen over a
140
+ * shoulder is valid for thirty seconds, and the second use is the attack.
141
+ */
142
+ export interface TwoFactorStorePort {
143
+ get(userId: string): Promise<TwoFactorRecord | null>;
144
+ /** Upsert. */
145
+ set(userId: string, record: TwoFactorRecord): Promise<void>;
146
+ delete(userId: string): Promise<void>;
147
+ /** Records `step` as used if it is newer than the last one; false when it is not. */
148
+ claimStep(userId: string, step: number): Promise<boolean>;
149
+ /** Removes the hash if present; false when it was not there (already used, or never valid). */
150
+ consumeBackupCode(userId: string, hash: string): Promise<boolean>;
151
+ }
152
+ /** A WebAuthn credential. Only the public key is ever here — the private one never leaves the device. */
153
+ export interface Passkey {
154
+ /** The credential id, base64url. What the browser sends back on sign-in. */
155
+ id: string;
156
+ userId: string;
157
+ /** COSE public key, base64url. */
158
+ publicKey: string;
159
+ /**
160
+ * Signature counter. Synced passkeys (iCloud Keychain, Google Password
161
+ * Manager) keep it at 0 forever; only hardware keys increment it. Never
162
+ * treat "did not increase" as an error when both sides are 0.
163
+ */
164
+ counter: number;
165
+ transports?: string[];
166
+ /** `multiDevice` is a synced passkey; `singleDevice` a hardware key or a non-synced platform one. */
167
+ deviceType: 'singleDevice' | 'multiDevice';
168
+ backedUp: boolean;
169
+ /** What the person called it ("iPhone de Ana"); for the list in settings. */
170
+ name?: string | null;
171
+ createdAt: Date;
172
+ lastUsedAt?: Date | null;
173
+ }
174
+ export interface PasskeyStorePort {
175
+ listByUser(userId: string): Promise<Passkey[]>;
176
+ findById(id: string): Promise<Passkey | null>;
177
+ create(passkey: Passkey): Promise<void>;
178
+ /** After a successful sign-in: the new counter (when it moved) and when. */
179
+ touch(id: string, counter: number, lastUsedAt: Date): Promise<void>;
180
+ /** Scoped by user so nobody deletes someone else's credential by id. False when nothing matched. */
181
+ delete(id: string, userId: string): Promise<boolean>;
182
+ }
@@ -0,0 +1,58 @@
1
+ import { type OAuthProviderConfig } from '../oauth-provider.js';
2
+ export interface AppleCredentials {
3
+ /** The Services ID (`com.example.web`), not the App ID. `APPLE_CLIENT_ID`. */
4
+ clientId?: string;
5
+ /** `APPLE_TEAM_ID`. */
6
+ teamId?: string;
7
+ /** The id of the Sign in with Apple key. `APPLE_KEY_ID`. */
8
+ keyId?: string;
9
+ /**
10
+ * The `.p8` contents, PEM. `APPLE_PRIVATE_KEY` — with real newlines or
11
+ * `\n` escapes, both are accepted, because every secrets manager mangles
12
+ * one of the two.
13
+ */
14
+ privateKey?: string;
15
+ /** Must be `https`: Apple refuses anything else. `APPLE_CALLBACK_URL`. */
16
+ callbackUrl?: string;
17
+ scope?: string;
18
+ /** Default `https://appleid.apple.com/auth/keys`; a test points it elsewhere. */
19
+ keysUrl?: string;
20
+ }
21
+ interface AppleIdClaims {
22
+ sub: string;
23
+ email?: string;
24
+ email_verified?: boolean | 'true' | 'false';
25
+ is_private_email?: boolean | 'true' | 'false';
26
+ }
27
+ /**
28
+ * Sign in with Apple. Differs from every other provider on four counts, and
29
+ * each one is why the generic flow gained the knob it uses:
30
+ *
31
+ * - There is no client secret to copy. It is a JWT the app signs itself, with
32
+ * the team's private key, valid at most six months — `clientSecret` is a
33
+ * function that mints one per exchange.
34
+ * - The callback is a **POST**. With `name` or `email` in the scope Apple
35
+ * insists on `response_mode=form_post`, so `code` and `state` arrive as a
36
+ * form body, cross-site. `callbackMethod: 'POST'` makes the controller
37
+ * accept that and write the `state` cookie `SameSite=None`. On Fastify the
38
+ * app has to register `@fastify/formbody`; Express parses forms by default.
39
+ * - There is no profile endpoint. The identity is the `id_token` from the
40
+ * exchange, verified here against Apple's published keys — no library, Node
41
+ * imports a JWK natively. `email_verified` decides whether the address may
42
+ * link; a relay address (`@privaterelay.appleid.com`) is a real mailbox and
43
+ * is kept.
44
+ * - The name comes **once**, in the POST body of the first authorisation, as
45
+ * a JSON string in `user`, and never again. Miss it and it is gone until the
46
+ * person revokes the app in their Apple ID settings.
47
+ */
48
+ export declare function appleProvider(credentials?: AppleCredentials): OAuthProviderConfig;
49
+ /**
50
+ * The secret Apple expects: ES256, `iss` team, `sub` client, `aud` Apple,
51
+ * `kid` the key. Six months is Apple's maximum lifetime; one is minted per
52
+ * exchange, which is cheap and never lets a cached one expire under a
53
+ * long-running process.
54
+ */
55
+ export declare function mintClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string): string;
56
+ /** Signature, issuer, audience and expiry — the four things a forged or replayed token fails. */
57
+ export declare function verifyAppleIdToken(idToken: string, clientId: string, keysUrl?: string): Promise<AppleIdClaims>;
58
+ export {};
@@ -0,0 +1,7 @@
1
+ import { type OAuthProviderConfig, type ProviderCredentials } from '../oauth-provider.js';
2
+ /**
3
+ * Discord. `verified` says whether Discord confirmed the address — an
4
+ * unverified one is dropped, since anyone can register a Discord account
5
+ * under someone else's email and it would otherwise sign in as them.
6
+ */
7
+ export declare function discordProvider(credentials?: ProviderCredentials): OAuthProviderConfig;
@@ -0,0 +1,8 @@
1
+ import { type OAuthProviderConfig, type ProviderCredentials } from '../oauth-provider.js';
2
+ /**
3
+ * GitHub. `/user` may answer `email: null` — the address is private by
4
+ * default — so the verified primary is read from `/user/emails`, which is
5
+ * what the `user:email` scope is for. Every API call needs a `User-Agent`;
6
+ * GitHub rejects the request without one.
7
+ */
8
+ export declare function githubProvider(credentials?: ProviderCredentials): OAuthProviderConfig;
@@ -0,0 +1,7 @@
1
+ import { type OAuthProviderConfig, type ProviderCredentials } from '../oauth-provider.js';
2
+ /**
3
+ * LinkedIn, through its OpenID Connect endpoints — the only ones a new app
4
+ * can use since 2023; the old `r_liteprofile`/`r_emailaddress` pair is gone.
5
+ * `userinfo` returns standard claims, `email_verified` included.
6
+ */
7
+ export declare function linkedinProvider(credentials?: ProviderCredentials): OAuthProviderConfig;
@@ -0,0 +1,17 @@
1
+ import { type OAuthProviderConfig, type ProviderCredentials } from '../oauth-provider.js';
2
+ export interface MicrosoftCredentials extends ProviderCredentials {
3
+ /**
4
+ * `common` (any Microsoft account, personal or work), `organizations`,
5
+ * `consumers`, or a tenant id to lock sign-in to one organisation.
6
+ * `MICROSOFT_TENANT`, default `common`.
7
+ */
8
+ tenant?: string;
9
+ }
10
+ /**
11
+ * Microsoft — Entra ID work accounts and personal ones, through the v2.0
12
+ * endpoint and Graph. The address is `mail`, or the UPN when the account has
13
+ * no mailbox; both are owned by the tenant that issued them, which is what
14
+ * makes them safe to link on. Graph serves the photo as bytes on another
15
+ * endpoint, so there is no avatar URL to hand back.
16
+ */
17
+ export declare function microsoftProvider(credentials?: MicrosoftCredentials): OAuthProviderConfig;
@@ -0,0 +1,17 @@
1
+ import { type OAuthProviderConfig, type ProviderCredentials } from '../oauth-provider.js';
2
+ /**
3
+ * TikTok Login Kit. Two things set it apart, and both are visible here so
4
+ * nobody has to rediscover them:
5
+ *
6
+ * - It calls the client id `client_key` and rejects `client_id`, on the
7
+ * consent screen and at the exchange alike — `clientIdParam` exists for it.
8
+ * - It hands out **no email, under any scope**. So an account from here can
9
+ * be linked to a signed-in user (`link-intent`) and used to sign in once
10
+ * linked, but never to sign up: `login` stops with `missingEmailMessage`
11
+ * when there is no linked account to land on.
12
+ *
13
+ * `user.info.basic` is the whole ask: open id, display name, photo. The
14
+ * profile and stats scopes are one more checkbox on a consent screen for
15
+ * data a sign-in does not need.
16
+ */
17
+ export declare function tiktokProvider(credentials?: ProviderCredentials): OAuthProviderConfig;