@nocobase/app-plugin-verification 0.0.0-stage → 0.1.0-beta.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 (67) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE.txt +127 -0
  3. package/README.md +6 -2
  4. package/dist/client/api.d.ts +18 -0
  5. package/dist/client/api.d.ts.map +1 -0
  6. package/dist/client/api.js +44 -0
  7. package/dist/client/api.js.map +1 -0
  8. package/dist/client/hooks.d.ts +17 -0
  9. package/dist/client/hooks.d.ts.map +1 -0
  10. package/dist/client/hooks.js +91 -0
  11. package/dist/client/hooks.js.map +1 -0
  12. package/dist/client/index.d.ts +4 -0
  13. package/dist/client/index.d.ts.map +1 -0
  14. package/dist/client/index.js +4 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/database/migrations/.manifest.json +9 -0
  17. package/dist/database/migrations/202611250001_verification_create_tables.d.ts +4 -0
  18. package/dist/database/migrations/202611250001_verification_create_tables.d.ts.map +1 -0
  19. package/dist/database/migrations/202611250001_verification_create_tables.js +68 -0
  20. package/dist/database/migrations/202611250001_verification_create_tables.js.map +1 -0
  21. package/dist/server/config.d.ts +27 -0
  22. package/dist/server/config.d.ts.map +1 -0
  23. package/dist/server/config.js +38 -0
  24. package/dist/server/config.js.map +1 -0
  25. package/dist/server/contracts.d.ts +71 -0
  26. package/dist/server/contracts.d.ts.map +1 -0
  27. package/dist/server/contracts.js +2 -0
  28. package/dist/server/contracts.js.map +1 -0
  29. package/dist/server/index.d.ts +6 -0
  30. package/dist/server/index.d.ts.map +1 -0
  31. package/dist/server/index.js +5 -0
  32. package/dist/server/index.js.map +1 -0
  33. package/dist/server/plugin.d.ts +4 -0
  34. package/dist/server/plugin.d.ts.map +1 -0
  35. package/dist/server/plugin.js +15 -0
  36. package/dist/server/plugin.js.map +1 -0
  37. package/dist/server/providers/index.d.ts +4 -0
  38. package/dist/server/providers/index.d.ts.map +1 -0
  39. package/dist/server/providers/index.js +6 -0
  40. package/dist/server/providers/index.js.map +1 -0
  41. package/dist/server/providers/verification.d.ts +7 -0
  42. package/dist/server/providers/verification.d.ts.map +1 -0
  43. package/dist/server/providers/verification.js +59 -0
  44. package/dist/server/providers/verification.js.map +1 -0
  45. package/dist/server/routes/index.d.ts +5 -0
  46. package/dist/server/routes/index.d.ts.map +1 -0
  47. package/dist/server/routes/index.js +123 -0
  48. package/dist/server/routes/index.js.map +1 -0
  49. package/dist/server/routes/schemas.d.ts +9 -0
  50. package/dist/server/routes/schemas.d.ts.map +1 -0
  51. package/dist/server/routes/schemas.js +38 -0
  52. package/dist/server/routes/schemas.js.map +1 -0
  53. package/dist/server/services/verification.d.ts +64 -0
  54. package/dist/server/services/verification.d.ts.map +1 -0
  55. package/dist/server/services/verification.js +467 -0
  56. package/dist/server/services/verification.js.map +1 -0
  57. package/dist/server/tokens.d.ts +4 -0
  58. package/dist/server/tokens.d.ts.map +1 -0
  59. package/dist/server/tokens.js +3 -0
  60. package/dist/server/tokens.js.map +1 -0
  61. package/dist/shared/contracts.d.ts +27 -0
  62. package/dist/shared/contracts.d.ts.map +1 -0
  63. package/dist/shared/contracts.js +2 -0
  64. package/dist/shared/contracts.js.map +1 -0
  65. package/package.json +76 -3
  66. package/skills/nocobase-app-plugin-verification/SKILL.md +87 -0
  67. package/skills/nocobase-app-plugin-verification/references/client.md +115 -0
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: nocobase-app-plugin-verification
3
+ description: Configure and integrate NocoBase one-time verification codes, verified phone binding, and step-up credentials using server services and React hooks.
4
+ ---
5
+
6
+ # Integrate verification in a NocoBase application
7
+
8
+ Register the default export from `@nocobase/app-plugin-verification/server` after Authentication, Notification, and Notification Providers, including their setup dependencies. Install or apply database migrations before serving traffic. The plugin owns `userPhones`; account identity, sessions, and passwords belong to Authentication and Users. The plugin contributes no pages, no sign-in by SMS and no password reset routes: the application builds those flows on `verify()`. Installing it does not make a given application capable of any of them, so inspect the registered plugins and the `verification` configuration first. Verification codes must never travel through ordinary `notification.send()`, which persists messages; this plugin delivers only the code through `sendTransient()`. A step-up credential is never sent by SMS: the client exchanges the code for it and receives it in the response body of `POST /api/verification/stepUpTokens`, then presents it in the `X-Verification-Token` header of the protected request.
9
+
10
+ Import the API and hooks from `@nocobase/app-plugin-verification/client`. Use them inside the host application's Authentication and query providers. The [client integration guide](references/client.md) shows binding, changing a number, and confirming a sensitive operation. The hooks improve the user experience only: the business server must check permissions and consume its own step-up credential with `consumeStepUp`, whatever the caller. Notification channel and SMS provider settings stay in the `nocobase-app-plugin-notification-providers` Skill; ordinary notifications stay in `nocobase-app-plugin-notification`.
11
+
12
+ ## Configure SMS
13
+
14
+ Set up an SMS notification channel using the Notification Providers Skill; `system-sms` is the conventional name that its environment mapping fills, not a fixed requirement. The channel each flow uses is the one named by `verification.bindPhone.channel` for phone binding and `verification.stepUp.channel` for step-up, and each registered scene names its own `channel`. Use `type: sms`, `service: aliyun` or `service: tencent`, and a template such as `code` with a variable mapped from the message's `code`. Keep provider credentials in private environment mappings. Configure a stable application secrets keyring shared by all instances. Keep the preceding key during rotation until all codes issued under it expire.
15
+
16
+ Add the verification section to the application's `defaultAppConfigs`:
17
+
18
+ ```ts
19
+ import { defineVerificationConfig } from '@nocobase/app-plugin-verification/server';
20
+
21
+ const verification = defineVerificationConfig({
22
+ defaults: {
23
+ ttlSeconds: 300,
24
+ resendSeconds: 60,
25
+ hourlyLimit: 5,
26
+ maxAttempts: 5,
27
+ },
28
+ ipHourlyLimit: 20,
29
+ userHourlyLimit: 20,
30
+ stepUpTtlSeconds: 300,
31
+ bindPhone: { channel: 'system-sms', template: 'code' },
32
+ stepUp: { channel: 'system-sms', template: 'code' },
33
+ });
34
+ ```
35
+
36
+ Each reserved scene is enabled when its destination is configured. Code expiry and attempt limits are overridable by scene. A scene may increase the common resend interval or decrease the common hourly number limit. The number limits apply across all SMS scenes and server instances. Anonymous requests use an IP quota, while signed-in requests use a separate quota per person. All sender counters use the configured application cache. Use a shared counter backend such as Redis in multi-instance deployments. Anonymous HTTP requests use the authentication plugin's peer-anchored `auth.advanced.ipAddress` proxy rules. Configure `trustedProxies` and, if needed, `ipAddressHeaders` to recognize your ingress. Forwarded addresses from untrusted peers are ignored. Requests with no peer metadata share a fallback bucket.
37
+
38
+ ## Register scenes and verify a code
39
+
40
+ Resolve `verificationServiceToken` during your server provider's boot and register scenes before use. Choose `signedIn` for a person proving control of a supplied target and `verifiedPhone` for a person receiving a code at their existing verified number. Use `public` for an intentional anonymous flow; provide an eligibility check when sends should be limited to known recipients. Public requests to ineligible targets still count toward limits and return the same response fields as submissions. Providers are contacted synchronously, so response timing may vary.
41
+
42
+ ```ts
43
+ import { verificationServiceToken } from '@nocobase/app-plugin-verification/server';
44
+
45
+ const verification = container.resolve(verificationServiceToken);
46
+ verification.registerScene('confirmEnrollment', {
47
+ method: 'sms',
48
+ channel: 'system-sms',
49
+ template: 'code',
50
+ audience: 'signedIn',
51
+ });
52
+
53
+ await verification.verify({
54
+ scene: 'confirmEnrollment',
55
+ target: normalizedPhone,
56
+ userId: authenticatedUser.id,
57
+ code: submittedCode,
58
+ });
59
+ ```
60
+
61
+ Clients request codes with `POST /api/verification/codes/send`, body `{ scene, phone? }`. Supply a canonical E.164 phone for SMS unless the scene targets the user's verified phone. A 429 response includes a `Retry-After` header in seconds and `error.metadata.retryAt` in ISO format. For a trusted server send, use `verification.send({ scene, target, userId, clientAddress })` with the authenticated user ID when signed in. For anonymous sends, resolve the peer through `Auth.clientAddress(request, peer)`. `verify()` belongs inside the consuming operation's authorized server path. A successful verification consumes the code, and inputs from a client must never select another user's identity. Register additional delivery methods with `registerMethod()` and keep their OTP messages in memory during delivery.
62
+
63
+ ## Bind a phone or enforce step-up
64
+
65
+ Read the signed-in person's masked phone at `GET /api/verification/me/phone`. Send a `bindPhone` code to the new phone and submit `{ phone, code }` to `PUT /api/verification/me/phone`. For a change, also prove control of the currently bound phone using the built-in purpose `verification.changePhone` and include the resulting credential as `X-Verification-Token`. An incorrect new-phone code counts as a failed code attempt and leaves the old-phone credential available. A verified phone can belong to one person. There is no phone recovery or administrative unlink endpoint. Account deletion removes its phone binding and step-up records.
66
+
67
+ ```ts
68
+ verification.registerStepUpPurpose('tenants.disable', { ttlSeconds: 300 });
69
+
70
+ // In an operation that has already checked the person's session and tenant permission:
71
+ await verification.consumeStepUp({
72
+ userId: context.get('auth')!.user.id,
73
+ purpose: 'tenants.disable',
74
+ token: context.req.header('X-Verification-Token'),
75
+ });
76
+ await disableTenant(tenantId);
77
+ ```
78
+
79
+ To obtain the credential, send `{ scene: 'stepUp', purpose: 'tenants.disable' }` to the code endpoint, then post `{ purpose, code }` to `/api/verification/stepUpTokens`. Keep the returned opaque token in memory and send it only to the intended operation. A new credential for the same user and purpose replaces the previous one. Consumption is atomic and precedes the operation. If the operation fails afterward, request a new credential. Changing the verified phone invalidates credentials issued against the previous binding. Step-up confirms the person and action purpose. The protected operation checks its own target authorization, and can register distinct purposes for operations it needs to distinguish.
80
+
81
+ The documented business actions are `verification.codes/send`, `verification.stepUpTokens/create`, `verification.phone/read`, and `verification.phone/update`. Access to public sends is limited by the scene and rate policy. All other access is limited to the signed-in person's own account by session authentication and ownership. No role grant can extend this access to a different account. Only codes go through `sendTransient()`; tokens come back in the response body. Keep codes and tokens out of request logs and analytics.
82
+
83
+ ## Migrate a sub-application from SmsCodes
84
+
85
+ Move the Alibaba Cloud template settings to the shared channel's `templates.code` and keep secrets in the Notification Providers environment mappings. Preserve other uses such as activation messages as distinct templates. For a gradual rollout, register `externalSignIn` and `resetPassword` as public scenes with an eligibility check that looks up the application's member records. Use `verification.verify({ scene, target, code })` inside the corresponding server flow, then run the application's existing account activation, authentication, or password reset policy. Keep old routes until their callers switch. The verification plugin does not automatically create accounts or start sessions.
86
+
87
+ Review old profile/member data before importing phones. Use an application migration to add only independently verified E.164 values to `userPhones`, with the matching authentication `userId`, a distinct random `bindingId`, and a `verifiedAt` timestamp. Resolve duplicates and conflicting identities before import. Require reverification for numbers without trustworthy provenance, and ask users to request new codes after cutover. Pending `SmsCodes` records use a different challenge format and should expire under the old flow. Remove the old sender and code store after the application has switched its callers.
@@ -0,0 +1,115 @@
1
+ # Verification client integration
2
+
3
+ Register the Verification server and configure the `bindPhone` and `stepUp` scenes as described in the [Verification Skill](../SKILL.md). Use the hooks in routes under the application's Authentication client and query providers. The client entry consists of named imports that can be used directly from application code.
4
+
5
+ | Hook | Contract |
6
+ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | `useSendVerificationCode()` | Submit a scene with `phone` or `purpose` as required, and receive `expiresAt` and `resendAt`. |
8
+ | `useMyVerifiedPhone()` | Read `data.phone`, which is masked or `null` after a successful read. Use `isLoading` for the initial fetch and `error` for a failed read. |
9
+ | `useBindPhone()` | Submit a new phone and its code, plus the old-phone credential when changing a binding. On success, read the updated masked phone from the result or the refreshed query. |
10
+ | `useIssueStepUpToken()` | Submit a registered purpose and the code sent to the verified phone, and receive `{ token, expiresAt }`. |
11
+
12
+ Action hooks expose `isPending`, `isSuccess`, `error` and `reset()`. Access successful results through the promise returned by `submit(input)`. Use those handlers in response to explicit user actions. Outside React, call `sendVerificationCode(api, input)`, `getMyVerifiedPhone(api)`, `bindPhone(api, input)` or `issueStepUpToken(api, input)` with the host's `ApiClient`. The API functions use the configured base path and credentials. If you call `bindPhone` directly, refresh your caller's phone state after it succeeds.
13
+
14
+ ## Bind a first phone
15
+
16
+ Collect a phone in E.164 format and submit the code in a separate interaction after it arrives. The signed-in user sees the masked number through `useMyVerifiedPhone()` after the bind.
17
+
18
+ ```ts
19
+ import {
20
+ useBindPhone,
21
+ useMyVerifiedPhone,
22
+ useSendVerificationCode,
23
+ } from '@nocobase/app-plugin-verification/client';
24
+
25
+ export function useFirstPhoneBinding() {
26
+ const send = useSendVerificationCode();
27
+ const bind = useBindPhone();
28
+ const verifiedPhone = useMyVerifiedPhone();
29
+
30
+ return {
31
+ verifiedPhone,
32
+ sendCode: (phone: string) => send.submit({ scene: 'bindPhone', phone }),
33
+ confirm: (phone: string, code: string) => bind.submit({ phone, code }),
34
+ };
35
+ }
36
+ ```
37
+
38
+ ## Change a verified phone
39
+
40
+ Send a `stepUp` code to the currently verified phone for the built-in `changePhonePurpose`. Send a `bindPhone` code to the new number. Once the user has entered both codes, exchange the old-phone code and immediately pass the returned token to the bind call. The hook sends it in `X-Verification-Token`.
41
+
42
+ ```ts
43
+ import {
44
+ changePhonePurpose,
45
+ useBindPhone,
46
+ useIssueStepUpToken,
47
+ useSendVerificationCode,
48
+ } from '@nocobase/app-plugin-verification/client';
49
+
50
+ export function useChangeVerifiedPhone() {
51
+ const send = useSendVerificationCode();
52
+ const issue = useIssueStepUpToken();
53
+ const bind = useBindPhone();
54
+
55
+ return {
56
+ sendOldPhoneCode: () =>
57
+ send.submit({ scene: 'stepUp', purpose: changePhonePurpose }),
58
+ sendNewPhoneCode: (phone: string) =>
59
+ send.submit({ scene: 'bindPhone', phone }),
60
+ async confirm(phone: string, oldCode: string, newCode: string) {
61
+ const { token } = await issue.submit({
62
+ purpose: changePhonePurpose,
63
+ code: oldCode,
64
+ });
65
+ return bind.submit({ phone, code: newCode, token });
66
+ },
67
+ };
68
+ }
69
+ ```
70
+
71
+ ## Confirm a sensitive business operation
72
+
73
+ Register the application's purpose on the server before sending a code. Use the issued credential only for the intended request, in the verification header. This example assumes the application owns the tenant endpoint.
74
+
75
+ ```ts
76
+ import { useApiClient } from '@nocobase/app-client';
77
+ import {
78
+ useIssueStepUpToken,
79
+ useSendVerificationCode,
80
+ } from '@nocobase/app-plugin-verification/client';
81
+
82
+ const disableTenantPurpose = 'tenants.disable';
83
+
84
+ export function useDisableTenant() {
85
+ const api = useApiClient();
86
+ const send = useSendVerificationCode();
87
+ const issue = useIssueStepUpToken();
88
+
89
+ return {
90
+ sendCode: () =>
91
+ send.submit({ scene: 'stepUp', purpose: disableTenantPurpose }),
92
+ async confirm(tenantId: string, code: string) {
93
+ const { token } = await issue.submit({
94
+ purpose: disableTenantPurpose,
95
+ code,
96
+ });
97
+ return api.request({
98
+ method: 'POST',
99
+ path: `tenants/${encodeURIComponent(tenantId)}/disable`,
100
+ headers: { 'X-Verification-Token': token },
101
+ });
102
+ },
103
+ };
104
+ }
105
+ ```
106
+
107
+ The business server checks the authenticated person's permission to operate on the target and calls `consumeStepUp({ userId, purpose, token })` before the write. Use the authenticated user ID and the server's registered purpose. See the [server example](../SKILL.md#bind-a-phone-or-enforce-step-up). Enforce both checks on every protected request, including callers outside the React flow.
108
+
109
+ ## Handle errors and resend timing
110
+
111
+ Use `resendAt` to render the normal countdown and `expiresAt` to show when the code expires. On HTTP 429, `getVerificationRateLimit(error)` gives the raw `retryAfter` header when visible to the client and the ISO `retryAt` from `error.metadata`. The server decides when another send is allowed. The original `ApiClientError` retains its status, reason, domain, request ID and payload. Network errors propagate as received.
112
+
113
+ The action hooks send each submission once. A network failure can occur after the server has already sent a message, issued a credential or changed the binding. Before asking for another bind submission, refresh the phone query to see the current binding. Wait for the applicable resend time before asking for another code.
114
+
115
+ Keep codes and credentials in the active interaction and clear app-owned inputs when the flow completes, is cancelled, or changes account. Keep both out of URLs, logs, analytics and persistent storage. Hook status is local and can be cleared with `reset()`. The hooks pass credentials back through the initiating promise and keep submitted parameters and successful responses out of the mutation cache. The phone query uses a session-specific key, discards its inactive data, and follows the host's query-cache lifecycle on sign-out.