@smplcty/auth 0.1.5 → 0.2.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/README.md CHANGED
@@ -171,6 +171,146 @@ await revokeSession(db, sessionId); // idempotent — no error if already revoke
171
171
 
172
172
  Hard-deletes the session row.
173
173
 
174
+ ## Developer OTP — for devs whose phones can't receive SMS
175
+
176
+ Twilio's Verify service doesn't deliver SMS to every carrier reliably (especially overseas, certain pre-paid carriers, and some VoIP numbers). Real-world projects need a way for developers to sign in even when SMS delivery is broken.
177
+
178
+ `@smplcty/auth` ships per-developer TOTP enrollment for exactly this case. Each enrolled dev has their own time-based one-time password secret stored in `dev_otp_enrollments`, scanned into a standard authenticator app (1Password, Authy, Google Authenticator, etc.). The sign-in-verify handler tries the dev OTP first; if it doesn't match, it falls through to Twilio.
179
+
180
+ ### How the codes are distinguished from Twilio codes
181
+
182
+ **They aren't, by format.** A 6-digit TOTP code from an authenticator app is indistinguishable from a 6-digit SMS code from Twilio. Users type whatever they have into the same input field. The backend figures out which one was used by **trying dev OTP first, then falling through to Twilio**.
183
+
184
+ The 1-in-1,000,000 collision risk between a wrong Twilio code and the user's current TOTP is negligible, and the audit trail (`dev_otp_enrollments.last_used_at` + `used_count`) lets you tell after the fact which path succeeded for any given sign-in.
185
+
186
+ ### Send side: skip Twilio for dev-enrolled users
187
+
188
+ When a user is enrolled in dev OTP, you don't need to send them an SMS at all — they'll generate their code from their authenticator app. Use `isDevOtpEnrolled` to skip the Twilio call:
189
+
190
+ ```ts
191
+ import { findUserByCommunicationMethod, isDevOtpEnrolled } from '@smplcty/auth';
192
+ import { createTwilioVerifyClient } from '@smplcty/twilio';
193
+
194
+ const twilio = createTwilioVerifyClient({ /* ... */ });
195
+
196
+ // Sign-in send handler:
197
+ const lookup = await findUserByCommunicationMethod(db, { channel: 'phone', code: phone });
198
+ if (!lookup) {
199
+ // User not registered. Return success anyway to avoid the enumeration oracle.
200
+ return ok();
201
+ }
202
+
203
+ const enrolled = await isDevOtpEnrolled(db, lookup.userCommunicationMethodId);
204
+ if (!enrolled) {
205
+ // Normal user — send the SMS code.
206
+ await twilio.sendVerificationCode({ channel: 'sms', to: phone });
207
+ }
208
+ // Dev-enrolled user gets the same response shape with no SMS — they
209
+ // already know to open their authenticator app.
210
+
211
+ return ok();
212
+ ```
213
+
214
+ `isDevOtpEnrolled(db, userCommunicationMethodId)` returns `boolean`. Cheap one-row lookup. Throws `InvalidInputError` if the id is malformed.
215
+
216
+ ### Verify side: try dev OTP first, fall through to Twilio
217
+
218
+ ```ts
219
+ import { verifyDevOtp, createSession, findUserByCommunicationMethod } from '@smplcty/auth';
220
+ import { createTwilioVerifyClient } from '@smplcty/twilio';
221
+
222
+ const twilio = createTwilioVerifyClient({ /* ... */ });
223
+
224
+ // Sign-in verify handler:
225
+ const lookup = await findUserByCommunicationMethod(db, { channel: 'phone', code: phone });
226
+ if (!lookup) return badRequest('Invalid code');
227
+
228
+ // 1. Try dev OTP first.
229
+ const devOk = await verifyDevOtp(db, lookup.userCommunicationMethodId, submittedCode);
230
+ if (devOk) {
231
+ // dev_otp_enrollments.last_used_at and used_count have been updated
232
+ // — that's your built-in audit signal that the dev path was taken.
233
+ return await createSessionResponse(db, lookup, ip, geo);
234
+ }
235
+
236
+ // 2. Fall through to Twilio. For users without a dev enrollment this
237
+ // is the only path; for users with one whose code didn't match (e.g.
238
+ // they happened to type the SMS code), this is the fallback.
239
+ const twilioOk = await twilio.verifyVerificationCode({ to: phone, code: submittedCode });
240
+ if (twilioOk) {
241
+ return await createSessionResponse(db, lookup, ip, geo);
242
+ }
243
+
244
+ return badRequest('Invalid code');
245
+ ```
246
+
247
+ `verifyDevOtp` returns `false` (does not throw) when:
248
+ - The user has no row in `dev_otp_enrollments`
249
+ - The submitted code doesn't match a TOTP for the stored secret within the ±30s tolerance window
250
+ - The stored secret is malformed (caught and treated as a non-match)
251
+
252
+ On success it updates the enrollment row's `last_used_at` and `used_count`, giving you a built-in audit signal that the dev OTP path was taken.
253
+
254
+ Both `verifyDevOtp` and `isDevOtpEnrolled` return `false` regardless of whether the user is enrolled or not (just with different conditions), so neither leaks enrollment status to the caller.
255
+
256
+ ### Enrolling a dev
257
+
258
+ There's no shipped CLI — at the team sizes this library is designed for, manual enrollment via SQL is fine and explicit. Here's the recipe:
259
+
260
+ ```ts
261
+ // One-off enrollment script: scripts/enroll-dev.mts
262
+ import { generateDevOtpSecret, getDevOtpEnrollmentUri } from '@smplcty/auth';
263
+ import qrcode from 'qrcode'; // pnpm add -D qrcode
264
+
265
+ const phone = process.argv[2]; // e.g. '+15558675309'
266
+ const label = process.argv[3]; // e.g. 'sam@salez1.com'
267
+ const issuer = 'Salez1';
268
+
269
+ const secret = generateDevOtpSecret();
270
+ const uri = getDevOtpEnrollmentUri({ secret, label, issuer });
271
+
272
+ console.log('\nScan this QR code with your authenticator app:\n');
273
+ console.log(await qrcode.toString(uri, { type: 'terminal', small: true }));
274
+ console.log(`\nManual entry secret: ${secret}\n`);
275
+ console.log('After scanning, run this SQL against your database:');
276
+ console.log(`
277
+ INSERT INTO dev_otp_enrollments (user_communication_method_id, totp_secret, label)
278
+ SELECT ucm.user_communication_method_id, '${secret}', '${label.replace(/'/g, "''")}'
279
+ FROM user_communication_methods ucm
280
+ JOIN communication_channels cc ON cc.communication_channel_id = ucm.communication_channel_id
281
+ WHERE cc.name = 'phone' AND ucm.code = '${phone}';
282
+ `);
283
+ ```
284
+
285
+ Run it with `pnpm tsx scripts/enroll-dev.mts +15558675309 'Sam (iPhone)'`. The script generates a fresh secret, prints a scannable QR code, and gives you the SQL to run against your database.
286
+
287
+ ### Revoking a dev's enrollment
288
+
289
+ ```sql
290
+ DELETE FROM dev_otp_enrollments
291
+ WHERE user_communication_method_id = (
292
+ SELECT user_communication_method_id
293
+ FROM user_communication_methods ucm
294
+ JOIN communication_channels cc ON cc.communication_channel_id = ucm.communication_channel_id
295
+ WHERE cc.name = 'phone' AND ucm.code = '+15558675309'
296
+ );
297
+ ```
298
+
299
+ The next sign-in-verify call for that user will fall through to Twilio as if they were never enrolled.
300
+
301
+ ### Why per-dev TOTP instead of a shared bypass code?
302
+
303
+ Earlier versions of this codebase used a `DEV_PHONE_NUMBERS` + `DEV_VERIFICATION_CODE` env var pair where any dev phone, when paired with the magic env var code, bypassed Twilio. That design has several problems: a single static secret shared across all devs, no per-dev revocation, no audit trail, and the bypass mechanism baked into the source code as a recipe for "how to sign in without OTP." Per-dev TOTP fixes all of these:
304
+
305
+ | Concern | Shared bypass code | Per-dev TOTP |
306
+ |---|---|---|
307
+ | Secret leak blast radius | Every dev account compromised | One dev account |
308
+ | Per-dev revocation | Rotate the shared secret + everyone re-syncs | Delete one row |
309
+ | Audit trail | None | `last_used_at` + `used_count` per enrollment |
310
+ | Brute-force resistance | 6-digit space, no rotation | 6-digit space, rotates every 30s |
311
+ | Source-code visible | Shared secret + bypass logic | Just the verification code path; secrets are per-dev in the DB |
312
+ | Possession factor | Just env var knowledge | Authenticator app on a specific device |
313
+
174
314
  ## Typed roles
175
315
 
176
316
  By default `roleName` is typed as `string`, which works for any consumer. To get autocomplete and typo detection for your specific role names, write a thin wrapper in your application code:
@@ -0,0 +1,89 @@
1
+ import type { Queryable } from './types.js';
2
+ /**
3
+ * Verify a TOTP code against a developer's enrolled secret.
4
+ *
5
+ * Returns `true` if the user has a row in `dev_otp_enrollments` AND
6
+ * the submitted code matches a valid TOTP for the stored secret within
7
+ * the configured ±30s tolerance window. On a successful verification,
8
+ * the enrollment row's `last_used_at` and `used_count` are updated.
9
+ *
10
+ * Returns `false` if no enrollment exists for the user, or if the code
11
+ * doesn't match. **Does not throw on these cases** — falling through to
12
+ * Twilio verification (or any other verification path) is the caller's
13
+ * responsibility.
14
+ *
15
+ * Use this in a sign-in-verify handler to give devs whose phones can't
16
+ * receive Twilio SMS a way to sign in via an authenticator app:
17
+ *
18
+ * ```ts
19
+ * const ok = await verifyDevOtp(db, ucmId, submittedCode);
20
+ * if (ok) {
21
+ * // log audit event with phone, IP, timestamp
22
+ * return createSession(db, { ... });
23
+ * }
24
+ * // fall through to Twilio verification
25
+ * const verified = await verifyVerificationCode(to, submittedCode);
26
+ * ```
27
+ *
28
+ * @throws {InvalidInputError} If `userCommunicationMethodId` is not a
29
+ * positive integer or `code` is not a non-empty string.
30
+ */
31
+ export declare function verifyDevOtp(db: Queryable, userCommunicationMethodId: number, code: string): Promise<boolean>;
32
+ /**
33
+ * Check whether a user_communication_method has a dev OTP enrollment.
34
+ *
35
+ * Use this on the **send** side of a sign-in flow to skip the Twilio
36
+ * SMS send for dev-enrolled users — they'll generate their code from
37
+ * an authenticator app instead, so the SMS would be wasted (and may
38
+ * not deliver anyway, which is the whole reason they're enrolled in
39
+ * dev OTP).
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const enrolled = await isDevOtpEnrolled(db, user.userCommunicationMethodId);
44
+ * if (!enrolled) {
45
+ * await twilio.sendVerificationCode({ channel: 'sms', to });
46
+ * }
47
+ * return ok(); // dev users get the same response shape; the verify
48
+ * // step will accept their TOTP code
49
+ * ```
50
+ *
51
+ * @throws {InvalidInputError} If `userCommunicationMethodId` is not a positive integer.
52
+ */
53
+ export declare function isDevOtpEnrolled(db: Queryable, userCommunicationMethodId: number): Promise<boolean>;
54
+ /**
55
+ * Generate a fresh base32-encoded TOTP secret suitable for storing in
56
+ * the `dev_otp_enrollments.totp_secret` column.
57
+ *
58
+ * Use this from a one-off enrollment script:
59
+ *
60
+ * ```ts
61
+ * import { generateDevOtpSecret, getDevOtpEnrollmentUri } from '@smplcty/auth';
62
+ *
63
+ * const secret = generateDevOtpSecret();
64
+ * const uri = getDevOtpEnrollmentUri({
65
+ * secret,
66
+ * label: 'sam@salez1.com',
67
+ * issuer: 'Salez1',
68
+ * });
69
+ *
70
+ * // INSERT secret into dev_otp_enrollments via SQL,
71
+ * // print uri as a QR code with the qrcode package,
72
+ * // and have the dev scan it with their authenticator app.
73
+ * ```
74
+ */
75
+ export declare function generateDevOtpSecret(): string;
76
+ /**
77
+ * Build an `otpauth://` URI suitable for QR-code encoding. Authenticator
78
+ * apps scan this URI and add the secret to their list of accounts.
79
+ *
80
+ * The label is what the user sees in their authenticator app — typically
81
+ * the user's email address or phone number. The issuer is the application
82
+ * name (e.g., "Salez1"). Both are URI-encoded by the underlying library.
83
+ */
84
+ export declare function getDevOtpEnrollmentUri(input: {
85
+ secret: string;
86
+ label: string;
87
+ issuer: string;
88
+ }): string;
89
+ //# sourceMappingURL=dev-otp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-otp.d.ts","sourceRoot":"","sources":["../src/dev-otp.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AA4C5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,SAAS,EACb,yBAAyB,EAAE,MAAM,EACjC,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,OAAO,CAAC,CAwClB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,SAAS,EACb,yBAAyB,EAAE,MAAM,GAChC,OAAO,CAAC,OAAO,CAAC,CAalB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,MAAM,CAeT"}
@@ -0,0 +1,175 @@
1
+ import { generateSecret, generateURI, verifySync } from 'otplib';
2
+ import { InvalidInputError } from './errors.js';
3
+ // Accept codes within a ±30-second window — i.e. the current code,
4
+ // the previous code (just rolled), and the next code (about to roll).
5
+ // This handles small clock drift between the dev's authenticator app
6
+ // and the database server. Larger windows trade security for
7
+ // convenience and are not worth it.
8
+ const EPOCH_TOLERANCE_SECONDS = 30;
9
+ const SELECT_ENROLLMENT = `
10
+ SELECT
11
+ user_communication_method_id AS "userCommunicationMethodId",
12
+ totp_secret AS "totpSecret",
13
+ label AS "label",
14
+ enrolled_at AS "enrolledAt",
15
+ last_used_at AS "lastUsedAt",
16
+ used_count AS "usedCount"
17
+ FROM dev_otp_enrollments
18
+ WHERE user_communication_method_id = $1
19
+ `;
20
+ const SELECT_ENROLLMENT_EXISTS = `
21
+ SELECT 1
22
+ FROM dev_otp_enrollments
23
+ WHERE user_communication_method_id = $1
24
+ LIMIT 1
25
+ `;
26
+ const RECORD_USE = `
27
+ UPDATE dev_otp_enrollments
28
+ SET last_used_at = now(),
29
+ used_count = used_count + 1
30
+ WHERE user_communication_method_id = $1
31
+ `;
32
+ /**
33
+ * Verify a TOTP code against a developer's enrolled secret.
34
+ *
35
+ * Returns `true` if the user has a row in `dev_otp_enrollments` AND
36
+ * the submitted code matches a valid TOTP for the stored secret within
37
+ * the configured ±30s tolerance window. On a successful verification,
38
+ * the enrollment row's `last_used_at` and `used_count` are updated.
39
+ *
40
+ * Returns `false` if no enrollment exists for the user, or if the code
41
+ * doesn't match. **Does not throw on these cases** — falling through to
42
+ * Twilio verification (or any other verification path) is the caller's
43
+ * responsibility.
44
+ *
45
+ * Use this in a sign-in-verify handler to give devs whose phones can't
46
+ * receive Twilio SMS a way to sign in via an authenticator app:
47
+ *
48
+ * ```ts
49
+ * const ok = await verifyDevOtp(db, ucmId, submittedCode);
50
+ * if (ok) {
51
+ * // log audit event with phone, IP, timestamp
52
+ * return createSession(db, { ... });
53
+ * }
54
+ * // fall through to Twilio verification
55
+ * const verified = await verifyVerificationCode(to, submittedCode);
56
+ * ```
57
+ *
58
+ * @throws {InvalidInputError} If `userCommunicationMethodId` is not a
59
+ * positive integer or `code` is not a non-empty string.
60
+ */
61
+ export async function verifyDevOtp(db, userCommunicationMethodId, code) {
62
+ if (!Number.isInteger(userCommunicationMethodId) ||
63
+ userCommunicationMethodId <= 0) {
64
+ throw new InvalidInputError('userCommunicationMethodId must be a positive integer');
65
+ }
66
+ if (typeof code !== 'string' || code.length === 0) {
67
+ throw new InvalidInputError('code must be a non-empty string');
68
+ }
69
+ const { rows } = await db.query(SELECT_ENROLLMENT, [
70
+ userCommunicationMethodId,
71
+ ]);
72
+ const enrollment = rows[0];
73
+ if (!enrollment) {
74
+ return false;
75
+ }
76
+ try {
77
+ const result = verifySync({
78
+ secret: enrollment.totpSecret,
79
+ token: code,
80
+ epochTolerance: EPOCH_TOLERANCE_SECONDS,
81
+ });
82
+ if (!result.valid) {
83
+ return false;
84
+ }
85
+ }
86
+ catch {
87
+ // otplib throws on malformed secrets or non-numeric tokens — treat
88
+ // as a non-match rather than crashing the request. A malformed
89
+ // secret in the DB is a configuration error worth noticing through
90
+ // the consumer's audit pipeline.
91
+ return false;
92
+ }
93
+ await db.query(RECORD_USE, [userCommunicationMethodId]);
94
+ return true;
95
+ }
96
+ /**
97
+ * Check whether a user_communication_method has a dev OTP enrollment.
98
+ *
99
+ * Use this on the **send** side of a sign-in flow to skip the Twilio
100
+ * SMS send for dev-enrolled users — they'll generate their code from
101
+ * an authenticator app instead, so the SMS would be wasted (and may
102
+ * not deliver anyway, which is the whole reason they're enrolled in
103
+ * dev OTP).
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * const enrolled = await isDevOtpEnrolled(db, user.userCommunicationMethodId);
108
+ * if (!enrolled) {
109
+ * await twilio.sendVerificationCode({ channel: 'sms', to });
110
+ * }
111
+ * return ok(); // dev users get the same response shape; the verify
112
+ * // step will accept their TOTP code
113
+ * ```
114
+ *
115
+ * @throws {InvalidInputError} If `userCommunicationMethodId` is not a positive integer.
116
+ */
117
+ export async function isDevOtpEnrolled(db, userCommunicationMethodId) {
118
+ if (!Number.isInteger(userCommunicationMethodId) ||
119
+ userCommunicationMethodId <= 0) {
120
+ throw new InvalidInputError('userCommunicationMethodId must be a positive integer');
121
+ }
122
+ const { rowCount } = await db.query(SELECT_ENROLLMENT_EXISTS, [
123
+ userCommunicationMethodId,
124
+ ]);
125
+ return (rowCount ?? 0) > 0;
126
+ }
127
+ /**
128
+ * Generate a fresh base32-encoded TOTP secret suitable for storing in
129
+ * the `dev_otp_enrollments.totp_secret` column.
130
+ *
131
+ * Use this from a one-off enrollment script:
132
+ *
133
+ * ```ts
134
+ * import { generateDevOtpSecret, getDevOtpEnrollmentUri } from '@smplcty/auth';
135
+ *
136
+ * const secret = generateDevOtpSecret();
137
+ * const uri = getDevOtpEnrollmentUri({
138
+ * secret,
139
+ * label: 'sam@salez1.com',
140
+ * issuer: 'Salez1',
141
+ * });
142
+ *
143
+ * // INSERT secret into dev_otp_enrollments via SQL,
144
+ * // print uri as a QR code with the qrcode package,
145
+ * // and have the dev scan it with their authenticator app.
146
+ * ```
147
+ */
148
+ export function generateDevOtpSecret() {
149
+ return generateSecret();
150
+ }
151
+ /**
152
+ * Build an `otpauth://` URI suitable for QR-code encoding. Authenticator
153
+ * apps scan this URI and add the secret to their list of accounts.
154
+ *
155
+ * The label is what the user sees in their authenticator app — typically
156
+ * the user's email address or phone number. The issuer is the application
157
+ * name (e.g., "Salez1"). Both are URI-encoded by the underlying library.
158
+ */
159
+ export function getDevOtpEnrollmentUri(input) {
160
+ if (typeof input?.secret !== 'string' || input.secret.length === 0) {
161
+ throw new InvalidInputError('secret must be a non-empty string');
162
+ }
163
+ if (typeof input?.label !== 'string' || input.label.length === 0) {
164
+ throw new InvalidInputError('label must be a non-empty string');
165
+ }
166
+ if (typeof input?.issuer !== 'string' || input.issuer.length === 0) {
167
+ throw new InvalidInputError('issuer must be a non-empty string');
168
+ }
169
+ return generateURI({
170
+ issuer: input.issuer,
171
+ label: input.label,
172
+ secret: input.secret,
173
+ });
174
+ }
175
+ //# sourceMappingURL=dev-otp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-otp.js","sourceRoot":"","sources":["../src/dev-otp.ts"],"names":[],"mappings":"AAAA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;IACD,IAAI,OAAO,KAAK,EAAE,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,iBAAiB,CAAC,mCAAmC,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,WAAW,CAAC;QACjB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC"}
package/dist/index.d.ts CHANGED
@@ -7,4 +7,5 @@ export { findUserByCommunicationMethod } from './find-user-by-communication-meth
7
7
  export { withSession } from './with-session.js';
8
8
  export { withTransaction } from './with-transaction.js';
9
9
  export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
10
+ export { verifyDevOtp, isDevOtpEnrolled, generateDevOtpSecret, getDevOtpEnrollmentUri, } from './dev-otp.js';
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACV,SAAS,EACT,OAAO,EACP,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,yBAAyB,EACzB,aAAa,EACb,MAAM,EACN,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAGvF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACV,SAAS,EACT,OAAO,EACP,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,yBAAyB,EACzB,aAAa,EACb,MAAM,EACN,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAGvF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -10,4 +10,6 @@ export { withSession } from './with-session.js';
10
10
  export { withTransaction } from './with-transaction.js';
11
11
  // Low-level helpers — must be called inside an open transaction.
12
12
  export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
13
+ // Developer OTP — for devs whose phones can't receive Twilio SMS.
14
+ export { verifyDevOtp, isDevOtpEnrolled, generateDevOtpSecret, getDevOtpEnrollmentUri, } from './dev-otp.js';
13
15
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,SAAS;AACT,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAgBrB,oBAAoB;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAEvF,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,iEAAiE;AACjE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,SAAS;AACT,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAgBrB,oBAAoB;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAEvF,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,iEAAiE;AACjE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,kEAAkE;AAClE,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,cAAc,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smplcty/auth",
3
- "version": "0.1.5",
3
+ "version": "0.2.1",
4
4
  "description": "Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -57,12 +57,17 @@
57
57
  "pg": ">=8.0.0"
58
58
  },
59
59
  "devDependencies": {
60
+ "@eslint/js": "^10.0.1",
60
61
  "@smplcty/schema-flow": "^0.3.7",
61
62
  "@types/node": "^25.5.2",
62
63
  "@types/pg": "^8.20.0",
63
64
  "eslint": "^10.2.0",
64
65
  "pg": "^8.20.0",
65
66
  "typescript": "^6.0.2",
67
+ "typescript-eslint": "^8.58.1",
66
68
  "vitest": "^4.1.4"
69
+ },
70
+ "dependencies": {
71
+ "otplib": "^13.4.0"
67
72
  }
68
73
  }
@@ -0,0 +1,37 @@
1
+ table: dev_otp_enrollments
2
+ columns:
3
+ # The user_communication_method this enrollment is for. There can only
4
+ # be one dev OTP enrollment per communication method (PK + FK).
5
+ - name: user_communication_method_id
6
+ type: integer
7
+ primary_key: true
8
+ references:
9
+ table: user_communication_methods
10
+ column: user_communication_method_id
11
+
12
+ # Base32-encoded TOTP shared secret. Compatible with any standard TOTP
13
+ # authenticator (1Password, Authy, Google Authenticator, etc.).
14
+ # Recommend storing encrypted at rest if your Postgres has pgcrypto;
15
+ # the library reads/writes the raw value.
16
+ - name: totp_secret
17
+ type: text
18
+ nullable: false
19
+
20
+ # Human label for the enrollment — useful when an admin needs to
21
+ # know whose phone this is. Examples: "Sam's iPhone", "Mark's 1Password vault".
22
+ - name: label
23
+ type: text
24
+ nullable: false
25
+
26
+ - name: enrolled_at
27
+ type: timestamptz
28
+ nullable: false
29
+ default: now()
30
+
31
+ - name: last_used_at
32
+ type: timestamptz
33
+
34
+ - name: used_count
35
+ type: integer
36
+ nullable: false
37
+ default: 0