@smplcty/auth 0.6.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +198 -223
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +18 -23
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/dev-otp.d.ts.map +1 -1
  7. package/dist/dev-otp.js +4 -10
  8. package/dist/dev-otp.js.map +1 -1
  9. package/dist/errors.d.ts +19 -4
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +23 -5
  12. package/dist/errors.js.map +1 -1
  13. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  14. package/dist/find-user-by-communication-method.js +8 -1
  15. package/dist/find-user-by-communication-method.js.map +1 -1
  16. package/dist/get-user-role-names.d.ts.map +1 -1
  17. package/dist/get-user-role-names.js +2 -0
  18. package/dist/get-user-role-names.js.map +1 -1
  19. package/dist/index.d.ts +10 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +13 -7
  22. package/dist/index.js.map +1 -1
  23. package/dist/internal/hash-token.d.ts +16 -0
  24. package/dist/internal/hash-token.d.ts.map +1 -0
  25. package/dist/internal/hash-token.js +21 -0
  26. package/dist/internal/hash-token.js.map +1 -0
  27. package/dist/methods/errors.d.ts +37 -0
  28. package/dist/methods/errors.d.ts.map +1 -0
  29. package/dist/methods/errors.js +48 -0
  30. package/dist/methods/errors.js.map +1 -0
  31. package/dist/methods/oidc/index.d.ts +65 -0
  32. package/dist/methods/oidc/index.d.ts.map +1 -0
  33. package/dist/methods/oidc/index.js +76 -0
  34. package/dist/methods/oidc/index.js.map +1 -0
  35. package/dist/methods/router.d.ts +39 -0
  36. package/dist/methods/router.d.ts.map +1 -0
  37. package/dist/methods/router.js +153 -0
  38. package/dist/methods/router.js.map +1 -0
  39. package/dist/methods/twilio/index.d.ts +44 -0
  40. package/dist/methods/twilio/index.d.ts.map +1 -0
  41. package/dist/methods/twilio/index.js +77 -0
  42. package/dist/methods/twilio/index.js.map +1 -0
  43. package/dist/methods/types.d.ts +124 -0
  44. package/dist/methods/types.d.ts.map +1 -0
  45. package/dist/methods/types.js +2 -0
  46. package/dist/methods/types.js.map +1 -0
  47. package/dist/revoke-session.d.ts +20 -15
  48. package/dist/revoke-session.d.ts.map +1 -1
  49. package/dist/revoke-session.js +66 -20
  50. package/dist/revoke-session.js.map +1 -1
  51. package/dist/scope/flat-tenant.d.ts +36 -0
  52. package/dist/scope/flat-tenant.d.ts.map +1 -0
  53. package/dist/scope/flat-tenant.js +60 -0
  54. package/dist/scope/flat-tenant.js.map +1 -0
  55. package/dist/set-helpers.d.ts +44 -53
  56. package/dist/set-helpers.d.ts.map +1 -1
  57. package/dist/set-helpers.js +67 -74
  58. package/dist/set-helpers.js.map +1 -1
  59. package/dist/touch-session.d.ts +13 -0
  60. package/dist/touch-session.d.ts.map +1 -0
  61. package/dist/touch-session.js +28 -0
  62. package/dist/touch-session.js.map +1 -0
  63. package/dist/types.d.ts +59 -18
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/validate-session.d.ts +15 -14
  66. package/dist/validate-session.d.ts.map +1 -1
  67. package/dist/validate-session.js +28 -27
  68. package/dist/validate-session.js.map +1 -1
  69. package/dist/with-service-context.d.ts +15 -12
  70. package/dist/with-service-context.d.ts.map +1 -1
  71. package/dist/with-service-context.js +34 -39
  72. package/dist/with-service-context.js.map +1 -1
  73. package/dist/with-session.d.ts +22 -16
  74. package/dist/with-session.d.ts.map +1 -1
  75. package/dist/with-session.js +67 -66
  76. package/dist/with-session.js.map +1 -1
  77. package/package.json +53 -4
  78. package/schema/functions/current_user_id.yaml +18 -0
  79. package/schema/functions/resolve_session.yaml +42 -23
  80. package/schema/post/0001-backfill-audit-by.sql +15 -0
  81. package/schema/tables/auth_domains.yaml +43 -0
  82. package/schema/tables/communication_channels.yaml +5 -1
  83. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  84. package/schema/tables/roles.yaml +43 -7
  85. package/schema/tables/sessions.yaml +10 -0
  86. package/schema/tables/tenants.yaml +24 -1
  87. package/schema/tables/user_communication_methods.yaml +5 -1
  88. package/schema/tables/user_roles.yaml +1 -0
  89. package/schema/tables/users.yaml +27 -0
  90. package/dist/with-transaction.d.ts +0 -31
  91. package/dist/with-transaction.d.ts.map +0 -1
  92. package/dist/with-transaction.js +0 -49
  93. package/dist/with-transaction.js.map +0 -1
@@ -0,0 +1,65 @@
1
+ import { type OidcTokenPayload } from '@smplcty/oidc';
2
+ import type { Queryable } from '../../types.js';
3
+ import type { AuthDomain, MethodHandler, ResolvedUser } from '../types.js';
4
+ /**
5
+ * The OIDC provider config the handler reads from
6
+ * `auth_domains.integration_params`.
7
+ */
8
+ export interface OidcParams {
9
+ /** Provider issuer URL. Used to verify the id_token. */
10
+ issuer: string;
11
+ /** This app's OIDC client id. */
12
+ clientId: string;
13
+ /** The provider's authorization endpoint, used to build the redirect.
14
+ * Required for `initiate` unless a custom `buildRedirectUrl` is given. */
15
+ authorizationEndpoint?: string;
16
+ /** Where the provider sends the user back. */
17
+ redirectUri?: string;
18
+ /** OAuth scope. Defaults to `openid email`. */
19
+ scope?: string;
20
+ }
21
+ export interface OidcHandlerOptions {
22
+ /**
23
+ * Build the authorization redirect URL for `initiate`. Defaults to
24
+ * reading `authorizationEndpoint` from the matched config and appending
25
+ * the standard query params.
26
+ *
27
+ * Note: v1 does not manage `state` / `nonce` / PKCE here — those need
28
+ * per-request storage the library doesn't own. Supply this hook to add
29
+ * them, or wait for the full auth-code flow in `@smplcty/oidc`.
30
+ */
31
+ buildRedirectUrl?: (input: {
32
+ authDomain: AuthDomain<OidcParams>;
33
+ identifier?: string;
34
+ }) => string;
35
+ /**
36
+ * Provision a user when a verified identity has no existing
37
+ * communication method. The app owns the writes and their audit
38
+ * attribution (it knows the tenant from `authDomain.tenantId` and the
39
+ * default roles from `authDomain.integrationParams`). Omit to reject
40
+ * unprovisioned identities.
41
+ */
42
+ provisionUser?: (input: {
43
+ db: Queryable;
44
+ authDomain: AuthDomain<OidcParams>;
45
+ claims: OidcTokenPayload;
46
+ }) => Promise<ResolvedUser>;
47
+ }
48
+ /**
49
+ * The org-bound OIDC method handler (opt-in subpath `@smplcty/auth/oidc`).
50
+ * Phase 1 produces a redirect to the org's IdP; phase 2 verifies the
51
+ * returned id_token (the `credential`) and matches — or provisions, if a
52
+ * `provisionUser` hook is supplied — the user.
53
+ *
54
+ * Org-bound: it requires a matched `auth_domains` row (the per-tenant
55
+ * provider config). Drives `@smplcty/oidc` (an **optional peer**) for the
56
+ * protocol; the `auth_domains` registry lives in auth (own-domain rule),
57
+ * so this handler reads the config and calls `verifyIdToken` itself.
58
+ *
59
+ * ```ts
60
+ * import { oidcHandler } from '@smplcty/auth/oidc';
61
+ * const router = createMethodRouter({ db: pool, handlers: { oidc: oidcHandler() } });
62
+ * ```
63
+ */
64
+ export declare function oidcHandler(options?: OidcHandlerOptions): MethodHandler;
65
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/methods/oidc/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAGrE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,KAAK,EACV,UAAU,EAEV,aAAa,EAGb,YAAY,EACb,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,UAAU;IACzB,wDAAwD;IACxD,MAAM,EAAE,MAAM,CAAC;IACf,iCAAiC;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB;+EAC2E;IAC3E,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,8CAA8C;IAC9C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,+CAA+C;IAC/C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,MAAM,CAAC;IAClG;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE;QACtB,EAAE,EAAE,SAAS,CAAC;QACd,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;QACnC,MAAM,EAAE,gBAAgB,CAAC;KAC1B,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;CAC7B;AA0BD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,aAAa,CAuC3E"}
@@ -0,0 +1,76 @@
1
+ import { verifyIdToken } from '@smplcty/oidc';
2
+ import { InvalidInputError } from '../../errors.js';
3
+ import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
4
+ import { VerificationFailedError } from '../errors.js';
5
+ function paramsOf(authDomain) {
6
+ if (!authDomain) {
7
+ throw new InvalidInputError('OIDC handler requires a matched auth_domains row (org-bound)');
8
+ }
9
+ return authDomain;
10
+ }
11
+ function defaultRedirect(authDomain) {
12
+ const p = authDomain.integrationParams;
13
+ if (!p?.authorizationEndpoint) {
14
+ throw new InvalidInputError('auth_domains.integration_params.authorizationEndpoint is required for OIDC initiate (or pass buildRedirectUrl)');
15
+ }
16
+ const url = new URL(p.authorizationEndpoint);
17
+ url.searchParams.set('response_type', 'code');
18
+ url.searchParams.set('client_id', p.clientId);
19
+ if (p.redirectUri) {
20
+ url.searchParams.set('redirect_uri', p.redirectUri);
21
+ }
22
+ url.searchParams.set('scope', p.scope ?? 'openid email');
23
+ return url.toString();
24
+ }
25
+ /**
26
+ * The org-bound OIDC method handler (opt-in subpath `@smplcty/auth/oidc`).
27
+ * Phase 1 produces a redirect to the org's IdP; phase 2 verifies the
28
+ * returned id_token (the `credential`) and matches — or provisions, if a
29
+ * `provisionUser` hook is supplied — the user.
30
+ *
31
+ * Org-bound: it requires a matched `auth_domains` row (the per-tenant
32
+ * provider config). Drives `@smplcty/oidc` (an **optional peer**) for the
33
+ * protocol; the `auth_domains` registry lives in auth (own-domain rule),
34
+ * so this handler reads the config and calls `verifyIdToken` itself.
35
+ *
36
+ * ```ts
37
+ * import { oidcHandler } from '@smplcty/auth/oidc';
38
+ * const router = createMethodRouter({ db: pool, handlers: { oidc: oidcHandler() } });
39
+ * ```
40
+ */
41
+ export function oidcHandler(options = {}) {
42
+ return {
43
+ async initiate(ctx) {
44
+ const authDomain = paramsOf(ctx.authDomain);
45
+ const redirectUrl = options.buildRedirectUrl
46
+ ? options.buildRedirectUrl({ authDomain, identifier: ctx.identifier })
47
+ : defaultRedirect(authDomain);
48
+ return { redirectUrl };
49
+ },
50
+ async complete(ctx) {
51
+ const authDomain = paramsOf(ctx.authDomain);
52
+ const { issuer, clientId } = authDomain.integrationParams;
53
+ let claims;
54
+ try {
55
+ // credential is the id_token returned from the provider.
56
+ claims = await verifyIdToken(ctx.credential, { issuer, clientId });
57
+ }
58
+ catch {
59
+ throw new VerificationFailedError('OIDC id_token verification failed');
60
+ }
61
+ const email = claims.email ?? claims.preferredUsername;
62
+ if (!email) {
63
+ throw new VerificationFailedError('OIDC id_token has no email or preferred_username');
64
+ }
65
+ const existing = await findUserByCommunicationMethod(ctx.db, { channel: 'email', code: email });
66
+ if (existing) {
67
+ return existing;
68
+ }
69
+ if (options.provisionUser) {
70
+ return options.provisionUser({ db: ctx.db, authDomain, claims });
71
+ }
72
+ throw new VerificationFailedError('No user for verified identity and provisioning is disabled');
73
+ },
74
+ };
75
+ }
76
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/methods/oidc/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAyB,MAAM,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AE,CAAC,CAAC;YACnE,CAAC;YAED,MAAM,IAAI,uBAAuB,CAAC,4DAA4D,CAAC,CAAC;QAClG,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,39 @@
1
+ import type { MethodRouter, MethodRouterOptions } from './types.js';
2
+ /**
3
+ * Build a tenant-centric method router over a set of injected handlers.
4
+ *
5
+ * Sign-in discovery is by **sub-domain → tenant** (the app parses the request
6
+ * Host to a slug). The router lists that tenant's `auth_domains` and dispatches
7
+ * the chosen one (by `auth_domain_id`) to the handler registered for its
8
+ * `integration_type`. The user-bound OTP path is separate and **gated by the
9
+ * tenant's `allow_otp`** — enforced here, not just in the UI.
10
+ *
11
+ * Auth core stays protocol-free: handlers are injected. Install
12
+ * `@smplcty/auth/oidc` / `@smplcty/auth/twilio` (each with its protocol peer)
13
+ * and pass them in.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const router = createMethodRouter({
18
+ * db: pool,
19
+ * handlers: { oidc: oidcHandler() },
20
+ * otpHandler: twilioVerifyHandler({ client }),
21
+ * });
22
+ *
23
+ * // sign-in page (app already parsed Host → 'acme'):
24
+ * const opts = await router.signInOptions({ tenantSlug: 'acme' });
25
+ * // opts = { tenantId, authDomains: [...], otpAllowed }
26
+ * // 0 IdPs → OTP form; 1 → redirect to initiate(); N → a button per IdP
27
+ *
28
+ * // OIDC: user clicked the "Microsoft" button (authDomainId 1)
29
+ * const { redirectUrl } = await router.initiate(1);
30
+ * // ...callback: app loaded the auth_domain it stored against `state`
31
+ * const user = await router.complete(1, idToken);
32
+ *
33
+ * // OTP (only when opts.otpAllowed):
34
+ * await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
35
+ * const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
36
+ * ```
37
+ */
38
+ export declare function createMethodRouter(options: MethodRouterOptions): MethodRouter;
39
+ //# sourceMappingURL=router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/methods/router.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAc,YAAY,EAAE,mBAAmB,EAA+B,MAAM,YAAY,CAAC;AA2C7G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAyF7E"}
@@ -0,0 +1,153 @@
1
+ import { InvalidInputError } from '../errors.js';
2
+ import { OtpNotAllowedError, UnknownMethodError } from './errors.js';
3
+ const SELECT_TENANT_BY_SLUG = `
4
+ SELECT tenant_id AS "tenantId", allow_otp AS "allowOtp"
5
+ FROM tenants
6
+ WHERE slug = $1 AND deleted_at IS NULL
7
+ LIMIT 1
8
+ `;
9
+ const SELECT_ALLOW_OTP = `
10
+ SELECT allow_otp AS "allowOtp"
11
+ FROM tenants
12
+ WHERE tenant_id = $1 AND deleted_at IS NULL
13
+ LIMIT 1
14
+ `;
15
+ const AUTH_DOMAIN_COLUMNS = `
16
+ auth_domain_id AS "authDomainId",
17
+ tenant_id AS "tenantId",
18
+ display_name AS "displayName",
19
+ integration_type AS "integrationType",
20
+ integration_params AS "integrationParams"
21
+ `;
22
+ const SELECT_AUTH_DOMAINS_BY_TENANT = `
23
+ SELECT ${AUTH_DOMAIN_COLUMNS}
24
+ FROM auth_domains
25
+ WHERE tenant_id = $1 AND deleted_at IS NULL
26
+ ORDER BY display_name
27
+ `;
28
+ const SELECT_AUTH_DOMAIN_BY_ID = `
29
+ SELECT ${AUTH_DOMAIN_COLUMNS}
30
+ FROM auth_domains
31
+ WHERE auth_domain_id = $1 AND deleted_at IS NULL
32
+ LIMIT 1
33
+ `;
34
+ /**
35
+ * Build a tenant-centric method router over a set of injected handlers.
36
+ *
37
+ * Sign-in discovery is by **sub-domain → tenant** (the app parses the request
38
+ * Host to a slug). The router lists that tenant's `auth_domains` and dispatches
39
+ * the chosen one (by `auth_domain_id`) to the handler registered for its
40
+ * `integration_type`. The user-bound OTP path is separate and **gated by the
41
+ * tenant's `allow_otp`** — enforced here, not just in the UI.
42
+ *
43
+ * Auth core stays protocol-free: handlers are injected. Install
44
+ * `@smplcty/auth/oidc` / `@smplcty/auth/twilio` (each with its protocol peer)
45
+ * and pass them in.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const router = createMethodRouter({
50
+ * db: pool,
51
+ * handlers: { oidc: oidcHandler() },
52
+ * otpHandler: twilioVerifyHandler({ client }),
53
+ * });
54
+ *
55
+ * // sign-in page (app already parsed Host → 'acme'):
56
+ * const opts = await router.signInOptions({ tenantSlug: 'acme' });
57
+ * // opts = { tenantId, authDomains: [...], otpAllowed }
58
+ * // 0 IdPs → OTP form; 1 → redirect to initiate(); N → a button per IdP
59
+ *
60
+ * // OIDC: user clicked the "Microsoft" button (authDomainId 1)
61
+ * const { redirectUrl } = await router.initiate(1);
62
+ * // ...callback: app loaded the auth_domain it stored against `state`
63
+ * const user = await router.complete(1, idToken);
64
+ *
65
+ * // OTP (only when opts.otpAllowed):
66
+ * await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
67
+ * const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
68
+ * ```
69
+ */
70
+ export function createMethodRouter(options) {
71
+ const { db, handlers, otpHandler } = options;
72
+ const q = db;
73
+ async function loadAuthDomain(authDomainId) {
74
+ if (!Number.isInteger(authDomainId) || authDomainId <= 0) {
75
+ throw new InvalidInputError('authDomainId must be a positive integer');
76
+ }
77
+ const { rows } = await q.query(SELECT_AUTH_DOMAIN_BY_ID, [authDomainId]);
78
+ const authDomain = rows[0];
79
+ if (!authDomain) {
80
+ throw new UnknownMethodError(String(authDomainId));
81
+ }
82
+ return authDomain;
83
+ }
84
+ async function assertOtpAllowed(tenantId) {
85
+ if (!Number.isInteger(tenantId) || tenantId <= 0) {
86
+ throw new InvalidInputError('tenantId must be a positive integer');
87
+ }
88
+ if (!otpHandler) {
89
+ throw new OtpNotAllowedError(tenantId, 'No OTP handler is configured');
90
+ }
91
+ const { rows } = await q.query(SELECT_ALLOW_OTP, [tenantId]);
92
+ const row = rows[0];
93
+ // Unknown tenant or allow_otp=false both deny — fail closed.
94
+ if (!row || row.allowOtp !== true) {
95
+ throw new OtpNotAllowedError(tenantId);
96
+ }
97
+ }
98
+ return {
99
+ async signInOptions({ tenantSlug }) {
100
+ if (typeof tenantSlug !== 'string' || tenantSlug.length === 0) {
101
+ throw new InvalidInputError('tenantSlug must be a non-empty string');
102
+ }
103
+ const { rows } = await q.query(SELECT_TENANT_BY_SLUG, [tenantSlug]);
104
+ const tenant = rows[0];
105
+ if (!tenant) {
106
+ return null;
107
+ }
108
+ const { rows: authDomains } = await q.query(SELECT_AUTH_DOMAINS_BY_TENANT, [tenant.tenantId]);
109
+ return {
110
+ tenantId: tenant.tenantId,
111
+ authDomains,
112
+ otpAllowed: tenant.allowOtp === true && !!otpHandler,
113
+ };
114
+ },
115
+ async initiate(authDomainId) {
116
+ const authDomain = await loadAuthDomain(authDomainId);
117
+ const handler = handlers[authDomain.integrationType];
118
+ if (!handler) {
119
+ throw new UnknownMethodError(String(authDomainId), authDomain.integrationType);
120
+ }
121
+ return handler.initiate({ db, authDomain });
122
+ },
123
+ async complete(authDomainId, credential) {
124
+ if (typeof credential !== 'string' || credential.length === 0) {
125
+ throw new InvalidInputError('credential must be a non-empty string');
126
+ }
127
+ const authDomain = await loadAuthDomain(authDomainId);
128
+ const handler = handlers[authDomain.integrationType];
129
+ if (!handler) {
130
+ throw new UnknownMethodError(String(authDomainId), authDomain.integrationType);
131
+ }
132
+ return handler.complete({ db, authDomain, credential });
133
+ },
134
+ async initiateOtp({ tenantId, identifier }) {
135
+ if (typeof identifier !== 'string' || identifier.length === 0) {
136
+ throw new InvalidInputError('identifier must be a non-empty string');
137
+ }
138
+ await assertOtpAllowed(tenantId);
139
+ return otpHandler.initiate({ db, authDomain: null, identifier });
140
+ },
141
+ async completeOtp({ tenantId, identifier, credential }) {
142
+ if (typeof identifier !== 'string' || identifier.length === 0) {
143
+ throw new InvalidInputError('identifier must be a non-empty string');
144
+ }
145
+ if (typeof credential !== 'string' || credential.length === 0) {
146
+ throw new InvalidInputError('credential must be a non-empty string');
147
+ }
148
+ await assertOtpAllowed(tenantId);
149
+ return otpHandler.complete({ db, authDomain: null, identifier, credential });
150
+ },
151
+ };
152
+ }
153
+ //# sourceMappingURL=router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/methods/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGrE,MAAM,qBAAqB,GAAG;;;;;CAK7B,CAAC;AAEF,MAAM,gBAAgB,GAAG;;;;;CAKxB,CAAC;AAEF,MAAM,mBAAmB,GAAG;;;;;;CAM3B,CAAC;AAEF,MAAM,6BAA6B,GAAG;WAC3B,mBAAmB;;;;CAI7B,CAAC;AAEF,MAAM,wBAAwB,GAAG;WACtB,mBAAmB;;;;CAI7B,CAAC;AAOF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAA4B;IAC7D,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;IAC7C,MAAM,CAAC,GAAG,EAAe,CAAC;IAE1B,KAAK,UAAU,cAAc,CAAC,YAAoB;QAChD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;YACzD,MAAM,IAAI,iBAAiB,CAAC,yCAAyC,CAAC,CAAC;QACzE,CAAC;QACD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,CAAC,KAAK,CAAa,wBAAwB,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;QACrF,MAAM,UAAU,GAAG,IAAI,CAAC,C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E,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;QAC1D,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE;YACxC,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,CAAC;YACjC,OAAO,UAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE;YACpD,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,CAAC;YACjC,OAAO,UAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;QAChF,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { TwilioVerifyClient, VerificationChannel } from '@smplcty/twilio';
2
+ import type { MethodHandler } from '../types.js';
3
+ /**
4
+ * How an identifier maps onto a communication channel.
5
+ *
6
+ * - `channelName` — the `communication_channels.name` to match the user
7
+ * on (e.g. 'email' / 'phone').
8
+ * - `verifyChannel` — the Twilio Verify delivery channel ('sms' / 'email').
9
+ */
10
+ export interface ResolvedChannel {
11
+ channelName: string;
12
+ verifyChannel: VerificationChannel;
13
+ }
14
+ export interface TwilioVerifyHandlerOptions {
15
+ /** A Twilio Verify client from `createTwilioVerifyClient` (in the app). */
16
+ client: TwilioVerifyClient;
17
+ /** Map an identifier to its channel. Default: contains '@' → email,
18
+ * otherwise phone/sms. */
19
+ resolveChannel?: (identifier: string) => ResolvedChannel;
20
+ }
21
+ /**
22
+ * The user-bound Twilio Verify method handler (opt-in subpath
23
+ * `@smplcty/auth/twilio`). Phase 1 sends an OTP (skipping the send for
24
+ * dev-OTP-enrolled users); phase 2 verifies the submitted code — dev-OTP
25
+ * first, then Twilio — and resolves the existing user.
26
+ *
27
+ * User-bound: it never provisions. The user must already have a
28
+ * `user_communication_methods` row for the identifier. To avoid a
29
+ * user-enumeration oracle, `initiate` reports `otpSent` even for an unknown
30
+ * identifier (it just doesn't send); `complete` fails verification.
31
+ *
32
+ * Drives `@smplcty/twilio` (an **optional peer**); auth core depends on
33
+ * neither it nor `jose`. Install the peer and pass a client:
34
+ *
35
+ * ```ts
36
+ * import { createTwilioVerifyClient } from '@smplcty/twilio';
37
+ * import { twilioVerifyHandler } from '@smplcty/auth/twilio';
38
+ *
39
+ * const handler = twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) });
40
+ * const router = createMethodRouter({ db: pool, handlers: {}, defaultHandler: handler });
41
+ * ```
42
+ */
43
+ export declare function twilioVerifyHandler(options: TwilioVerifyHandlerOptions): MethodHandler;
44
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/methods/twilio/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAK/E,OAAO,KAAK,EAEV,aAAa,EAId,MAAM,aAAa,CAAC;AAErB;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,mBAAmB,CAAC;CACpC;AAED,MAAM,WAAW,0BAA0B;IACzC,2EAA2E;IAC3E,MAAM,EAAE,kBAAkB,CAAC;IAC3B;+BAC2B;IAC3B,cAAc,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,eAAe,CAAC;CAC1D;AAiBD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,aAAa,CA2CtF"}
@@ -0,0 +1,77 @@
1
+ import { InvalidInputError } from '../../errors.js';
2
+ import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
3
+ import { verifyDevOtp, isDevOtpEnrolled } from '../../dev-otp.js';
4
+ import { VerificationFailedError } from '../errors.js';
5
+ function defaultResolveChannel(identifier) {
6
+ return identifier.includes('@')
7
+ ? { channelName: 'email', verifyChannel: 'email' }
8
+ : { channelName: 'phone', verifyChannel: 'sms' };
9
+ }
10
+ // User-bound: the identifier (phone/email) is required. The router always
11
+ // supplies it via initiateOtp/completeOtp; this guards direct handler use.
12
+ function requireIdentifier(identifier) {
13
+ if (typeof identifier !== 'string' || identifier.length === 0) {
14
+ throw new InvalidInputError('the Twilio handler requires a non-empty identifier');
15
+ }
16
+ return identifier;
17
+ }
18
+ /**
19
+ * The user-bound Twilio Verify method handler (opt-in subpath
20
+ * `@smplcty/auth/twilio`). Phase 1 sends an OTP (skipping the send for
21
+ * dev-OTP-enrolled users); phase 2 verifies the submitted code — dev-OTP
22
+ * first, then Twilio — and resolves the existing user.
23
+ *
24
+ * User-bound: it never provisions. The user must already have a
25
+ * `user_communication_methods` row for the identifier. To avoid a
26
+ * user-enumeration oracle, `initiate` reports `otpSent` even for an unknown
27
+ * identifier (it just doesn't send); `complete` fails verification.
28
+ *
29
+ * Drives `@smplcty/twilio` (an **optional peer**); auth core depends on
30
+ * neither it nor `jose`. Install the peer and pass a client:
31
+ *
32
+ * ```ts
33
+ * import { createTwilioVerifyClient } from '@smplcty/twilio';
34
+ * import { twilioVerifyHandler } from '@smplcty/auth/twilio';
35
+ *
36
+ * const handler = twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) });
37
+ * const router = createMethodRouter({ db: pool, handlers: {}, defaultHandler: handler });
38
+ * ```
39
+ */
40
+ export function twilioVerifyHandler(options) {
41
+ const { client } = options;
42
+ const resolveChannel = options.resolveChannel ?? defaultResolveChannel;
43
+ return {
44
+ async initiate(ctx) {
45
+ const identifier = requireIdentifier(ctx.identifier);
46
+ const { channelName, verifyChannel } = resolveChannel(identifier);
47
+ const user = await findUserByCommunicationMethod(ctx.db, { channel: channelName, code: identifier });
48
+ // Unknown identifier: report sent without sending (anti-enumeration).
49
+ if (!user) {
50
+ return { otpSent: true };
51
+ }
52
+ // Dev-OTP-enrolled devs generate their code from an authenticator
53
+ // app, so skip the (likely undeliverable) SMS.
54
+ if (await isDevOtpEnrolled(ctx.db, user.userCommunicationMethodId)) {
55
+ return { otpSent: true };
56
+ }
57
+ await client.sendVerificationCode({ channel: verifyChannel, to: identifier });
58
+ return { otpSent: true };
59
+ },
60
+ async complete(ctx) {
61
+ const identifier = requireIdentifier(ctx.identifier);
62
+ const { channelName } = resolveChannel(identifier);
63
+ const user = await findUserByCommunicationMethod(ctx.db, { channel: channelName, code: identifier });
64
+ if (!user) {
65
+ throw new VerificationFailedError();
66
+ }
67
+ // Dev-OTP first (authenticator-app code), then Twilio Verify.
68
+ const okDev = await verifyDevOtp(ctx.db, user.userCommunicationMethodId, ctx.credential);
69
+ const ok = okDev || (await client.verifyVerificationCode({ to: identifier, code: ctx.credential }));
70
+ if (!ok) {
71
+ throw new VerificationFailedError();
72
+ }
73
+ return user;
74
+ },
75
+ };
76
+ }
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/methods/twilio/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAA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OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,124 @@
1
+ import type { Queryable } from '../types.js';
2
+ /**
3
+ * An `auth_domains` row — one of a tenant's org-bound sign-in IdPs. A tenant
4
+ * has 0..N of these; the router lists them for a tenant and dispatches by
5
+ * `integrationType`. Rows are configured at runtime and resolved by
6
+ * `authDomainId` (there is no stable text key); `displayName` is the button
7
+ * label when a tenant has more than one.
8
+ *
9
+ * @typeParam TParams - Shape of `integration_params`. Defaults to an open
10
+ * record; narrow it in a handler.
11
+ */
12
+ export interface AuthDomain<TParams = Record<string, unknown>> {
13
+ readonly authDomainId: number;
14
+ readonly tenantId: number;
15
+ /** Button label when the tenant has several IdPs (e.g. "Microsoft"). */
16
+ readonly displayName: string;
17
+ /** Selects the handler — e.g. 'oidc'. */
18
+ readonly integrationType: string;
19
+ /** Provider config + provisioning policy. Handler-specific. */
20
+ readonly integrationParams: TParams;
21
+ }
22
+ /**
23
+ * A user verified by a method handler, ready for `createSession`.
24
+ */
25
+ export interface ResolvedUser {
26
+ readonly userId: number;
27
+ readonly userCommunicationMethodId: number;
28
+ }
29
+ /**
30
+ * Result of a handler's `initiate` phase: either an OTP was sent
31
+ * (user-bound methods) or the caller should redirect (org-bound methods).
32
+ */
33
+ export type MethodInitiateResult = {
34
+ readonly otpSent: true;
35
+ } | {
36
+ readonly redirectUrl: string;
37
+ };
38
+ /**
39
+ * Context handed to a handler's `initiate`.
40
+ */
41
+ export interface MethodInitiateContext {
42
+ /** A connection or pool the handler may query (e.g. to find the user). */
43
+ readonly db: Queryable;
44
+ /** The matched `auth_domains` row for an org-bound method, or null for the
45
+ * user-bound (OTP) handler. */
46
+ readonly authDomain: AuthDomain | null;
47
+ /** The identifier the user entered (email/phone). Required by user-bound
48
+ * handlers; org-bound handlers may use it as a `login_hint`. */
49
+ readonly identifier?: string;
50
+ }
51
+ /**
52
+ * Context handed to a handler's `complete`. Adds the credential the user
53
+ * submitted back: an OTP code (user-bound) or an OIDC id_token (org-bound).
54
+ */
55
+ export interface MethodCompleteContext extends MethodInitiateContext {
56
+ readonly credential: string;
57
+ }
58
+ /**
59
+ * A pluggable two-phase authentication method. Models OTP (send → check)
60
+ * and OIDC (redirect → callback) under one interface. Handlers are
61
+ * **injected** into the router, so auth core depends on no protocol library.
62
+ */
63
+ export interface MethodHandler {
64
+ /** Phase 1: send an OTP, or produce a redirect URL. */
65
+ initiate(ctx: MethodInitiateContext): Promise<MethodInitiateResult>;
66
+ /** Phase 2: verify the submitted credential and resolve (provisioning
67
+ * if the handler's policy allows) the user. */
68
+ complete(ctx: MethodCompleteContext): Promise<ResolvedUser>;
69
+ }
70
+ /**
71
+ * Options for {@link createMethodRouter}.
72
+ */
73
+ export interface MethodRouterOptions {
74
+ /** Used to look up tenants and their `auth_domains`. */
75
+ db: Queryable;
76
+ /** Org-bound handlers keyed by `auth_domains.integration_type` (e.g. `{ oidc }`). */
77
+ handlers: Record<string, MethodHandler>;
78
+ /** The user-bound OTP handler (e.g. a `TwilioVerifyHandler`). Offered only
79
+ * when the tenant's `allow_otp` is true; omit it for an SSO-only product. */
80
+ otpHandler?: MethodHandler;
81
+ }
82
+ /**
83
+ * The sign-in methods available for a tenant — what the app renders on the
84
+ * sign-in surface.
85
+ */
86
+ export interface SignInOptions {
87
+ readonly tenantId: number;
88
+ /** The tenant's org-bound IdPs. Zero ⇒ OTP only; one ⇒ straight redirect;
89
+ * several ⇒ a chooser (button label `displayName`, value `authDomainId`). */
90
+ readonly authDomains: readonly AuthDomain[];
91
+ /** Whether to offer OTP: the tenant's `allow_otp` AND an `otpHandler` is set. */
92
+ readonly otpAllowed: boolean;
93
+ }
94
+ /**
95
+ * Tenant-centric sign-in dispatch. Discovery is by sub-domain → tenant (the
96
+ * app parses the Host to a slug); the router lists the tenant's IdPs and
97
+ * dispatches the chosen one by `auth_domains.integration_type`. The user-bound
98
+ * OTP path is gated by the tenant's `allow_otp` (enforced here, not just in UI).
99
+ */
100
+ export interface MethodRouter {
101
+ /** The sign-in methods for the tenant owning `tenantSlug`, or null if no
102
+ * such (live) tenant. */
103
+ signInOptions(input: {
104
+ tenantSlug: string;
105
+ }): Promise<SignInOptions | null>;
106
+ /** Org-bound phase 1 for a chosen `auth_domains` row (e.g. OIDC redirect). */
107
+ initiate(authDomainId: number): Promise<MethodInitiateResult>;
108
+ /** Org-bound phase 2 for a chosen `auth_domains` row (verify id_token, etc.). */
109
+ complete(authDomainId: number, credential: string): Promise<ResolvedUser>;
110
+ /** User-bound (OTP) phase 1. Throws {@link OtpNotAllowedError} when the
111
+ * tenant disallows OTP. */
112
+ initiateOtp(input: {
113
+ tenantId: number;
114
+ identifier: string;
115
+ }): Promise<MethodInitiateResult>;
116
+ /** User-bound (OTP) phase 2. Throws {@link OtpNotAllowedError} when the
117
+ * tenant disallows OTP. */
118
+ completeOtp(input: {
119
+ tenantId: number;
120
+ identifier: string;
121
+ credential: string;
122
+ }): Promise<ResolvedUser>;
123
+ }
124
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/methods/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C;;;;;;;;;GASG;AACH,MAAM,WAAW,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,wEAAwE;IACxE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,yCAAyC;IACzC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,+DAA+D;IAC/D,QAAQ,CAAC,iBAAiB,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;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