@owlmeans/auth 0.1.18-rc.4 → 0.1.18-rc.40

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 (94) hide show
  1. package/README.md +288 -45
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/auth/SKILL.md +131 -32
  4. package/agent-meta/skills/auth-protocol/SKILL.md +165 -90
  5. package/build/allowance/index.d.ts +1 -1
  6. package/build/allowance/index.d.ts.map +1 -1
  7. package/build/allowance/index.js +1 -1
  8. package/build/allowance/index.js.map +1 -1
  9. package/build/allowance/{model.d.ts → schemas.d.ts} +1 -1
  10. package/build/allowance/schemas.d.ts.map +1 -0
  11. package/build/allowance/{model.js → schemas.js} +7 -5
  12. package/build/allowance/schemas.js.map +1 -0
  13. package/build/auth/index.d.ts +1 -1
  14. package/build/auth/index.d.ts.map +1 -1
  15. package/build/auth/index.js +1 -1
  16. package/build/auth/index.js.map +1 -1
  17. package/build/auth/{model.d.ts → schemas.d.ts} +1 -1
  18. package/build/auth/schemas.d.ts.map +1 -0
  19. package/build/auth/{model.js → schemas.js} +4 -4
  20. package/build/auth/schemas.js.map +1 -0
  21. package/build/consts.d.ts +11 -1
  22. package/build/consts.d.ts.map +1 -1
  23. package/build/consts.js +12 -2
  24. package/build/consts.js.map +1 -1
  25. package/build/entity/index.d.ts +1 -1
  26. package/build/entity/index.js +1 -1
  27. package/build/entity/{profile.d.ts → schemas.d.ts} +1 -1
  28. package/build/entity/schemas.d.ts.map +1 -0
  29. package/build/entity/{profile.js → schemas.js} +4 -4
  30. package/build/entity/{profile.js.map → schemas.js.map} +1 -1
  31. package/build/errors.d.ts +15 -0
  32. package/build/errors.d.ts.map +1 -1
  33. package/build/errors.js +19 -0
  34. package/build/errors.js.map +1 -1
  35. package/build/helper/types.d.ts +22 -0
  36. package/build/helper/types.d.ts.map +1 -0
  37. package/build/helper/types.js +2 -0
  38. package/build/helper/types.js.map +1 -0
  39. package/build/helper.d.ts +9 -3
  40. package/build/helper.d.ts.map +1 -1
  41. package/build/helper.js +30 -17
  42. package/build/helper.js.map +1 -1
  43. package/build/index.d.ts +1 -0
  44. package/build/index.d.ts.map +1 -1
  45. package/build/index.js.map +1 -1
  46. package/build/permission/index.d.ts +1 -1
  47. package/build/permission/index.d.ts.map +1 -1
  48. package/build/permission/index.js +1 -1
  49. package/build/permission/index.js.map +1 -1
  50. package/build/permission/{model.d.ts → schemas.d.ts} +1 -1
  51. package/build/permission/schemas.d.ts.map +1 -0
  52. package/build/permission/{model.js → schemas.js} +1 -1
  53. package/build/permission/schemas.js.map +1 -0
  54. package/build/rely/index.d.ts +1 -1
  55. package/build/rely/index.d.ts.map +1 -1
  56. package/build/rely/index.js +1 -1
  57. package/build/rely/index.js.map +1 -1
  58. package/build/rely/{model.d.ts → schemas.d.ts} +1 -1
  59. package/build/rely/schemas.d.ts.map +1 -0
  60. package/build/rely/{model.js → schemas.js} +1 -1
  61. package/build/rely/schemas.js.map +1 -0
  62. package/build/supervisor.d.ts +0 -8
  63. package/build/supervisor.d.ts.map +1 -1
  64. package/build/types.d.ts +23 -1
  65. package/build/types.d.ts.map +1 -1
  66. package/package.json +3 -3
  67. package/src/allowance/index.ts +1 -1
  68. package/src/allowance/{model.ts → schemas.ts} +6 -4
  69. package/src/auth/index.ts +1 -1
  70. package/src/auth/{model.ts → schemas.ts} +3 -3
  71. package/src/consts.ts +14 -2
  72. package/src/entity/index.ts +1 -1
  73. package/src/entity/{profile.ts → schemas.ts} +3 -3
  74. package/src/errors.ts +22 -1
  75. package/src/helper/types.ts +22 -0
  76. package/src/helper.ts +44 -21
  77. package/src/index.ts +1 -0
  78. package/src/permission/index.ts +1 -1
  79. package/src/rely/index.ts +1 -1
  80. package/src/supervisor.ts +0 -8
  81. package/src/types.ts +30 -7
  82. package/tests/errors.spec.ts +19 -0
  83. package/build/.gitkeep +0 -0
  84. package/build/allowance/model.d.ts.map +0 -1
  85. package/build/allowance/model.js.map +0 -1
  86. package/build/auth/model.d.ts.map +0 -1
  87. package/build/auth/model.js.map +0 -1
  88. package/build/entity/profile.d.ts.map +0 -1
  89. package/build/permission/model.d.ts.map +0 -1
  90. package/build/permission/model.js.map +0 -1
  91. package/build/rely/model.d.ts.map +0 -1
  92. package/build/rely/model.js.map +0 -1
  93. /package/src/permission/{model.ts → schemas.ts} +0 -0
  94. /package/src/rely/{model.ts → schemas.ts} +0 -0
package/README.md CHANGED
@@ -1,84 +1,327 @@
1
1
  # @owlmeans/auth
2
2
 
3
- Core authentication types, schemas, and constants for OwlMeans fullstack applications.
4
-
5
- ## Overview
6
-
7
- - Defines the shared `Auth`, `AuthCredentials`, `AuthPayload`, and `AuthToken` types used by all auth-related packages
8
- - Provides AJV schemas for validating auth requests (`AuthCredentialsSchema`, `AllowanceRequestSchema`, etc.)
9
- - Defines the `AuthRole` and `AuthenticationStage` enums used across server and client
10
- - Used in request handlers to access `req.auth` and throw typed auth errors
3
+ The core authentication and authorization vocabulary shared by server and client: the `Auth` /
4
+ `AuthPayload` / `AuthCredentials` types, the `AuthRole` and `AuthenticationType` enums, the auth
5
+ error hierarchy, AJV schemas for request bodies and record fields, the auth entrypoint aliases, and
6
+ `authHelper.entitySlugOf()` for reading the organization entity off a token. An app imports it whenever code
7
+ on either side of the wire needs to name an identity, throw an auth error, or reuse a scalar schema
8
+ (`IdValueSchema`, `DateSchema`). It contains no services and no wiring: guards, the Ed25519 guard,
9
+ shared auth protocols and organization-entity resolution (`makeEntityScope(req)` —
10
+ `entityKeyOf`, `requireEntityKey`, `attachEntity`) live in [`@owlmeans/auth-common`](../auth-common); the server auth service in
11
+ [`@owlmeans/server-auth`](../server-auth); the browser auth service in
12
+ [`@owlmeans/client-auth`](../client-auth).
11
13
 
12
14
  ## Installation
13
15
 
14
16
  ```bash
15
- bun add @owlmeans/auth
17
+ bun add @owlmeans/auth@^0.1.18-rc.40
16
18
  ```
17
19
 
20
+ `ajv` is a **peer** dependency — install it alongside, or `authHelper.verifyAuth` /
21
+ `authHelper.verifyAuthCredentials` fail to resolve.
22
+
23
+ ## Concepts
24
+
25
+ - **Authorization** — the RBAC base every identity shape extends: `entitySlug?`, `scopes`,
26
+ `permissions?` (`PermissionSet[]`), `attributes?`, `permissioned?`, `denormalized?`.
27
+ - **AuthPayload / Auth** — `AuthPayload` adds `type`, `role`, `userId`, `profileId?`,
28
+ `expiresAt?`; `Auth` is the resolved identity a guard puts on `request.auth` (adds `token`,
29
+ `isUser`, `createdAt`).
30
+ - **Allowance / credentials** — the two-step handshake: a client posts an `AllowanceRequest` to get
31
+ a `challenge`, then posts `AuthCredentials` (`challenge` + `credential`) to authenticate.
32
+ - **Organization entity** — `entitySlug` is the renameable organization name and the only
33
+ organization value on the wire. Read it with `authHelper.entitySlugOf(payload)`. The stable `entityId` is
34
+ never on the wire and is not declared here; server handlers get it from
35
+ `makeEntityScope(req).requireEntityKey()` / `.requireEntity()` in `@owlmeans/auth-common`.
36
+ - **Error hierarchy** — `AuthError` is the root of i18n-aware `ResilientError` subclasses that
37
+ survive marshalling across a service boundary: `AuthUnknown` (no identity), `AuthenFailed`
38
+ (credential rejected), `AuthForbidden` (authenticated, not allowed).
39
+ - **Authentication stage** — `AuthenticationStage` tracks a client or socket flow from `Init` to
40
+ `Authenticated` (or `Error`).
41
+
18
42
  ## Usage
19
43
 
20
- Throw a typed auth error when a request lacks an entity:
44
+ ### Reuse scalar schemas in shared contracts
45
+
46
+ Field schemas keep ids, dates and scopes consistent across every app model.
47
+
48
+ ```ts
49
+ import type { JSONSchemaType } from 'ajv'
50
+ import { DateSchema, IdValueSchema } from '@owlmeans/auth'
51
+
52
+ export interface Invoice {
53
+ id?: string
54
+ projectId: string
55
+ total: number
56
+ createdAt: Date
57
+ }
58
+
59
+ export const InvoiceSchema: JSONSchemaType<Invoice> = {
60
+ type: 'object',
61
+ properties: {
62
+ id: { ...IdValueSchema, nullable: true },
63
+ projectId: IdValueSchema,
64
+ total: { type: 'number', minimum: 0 },
65
+ createdAt: DateSchema,
66
+ },
67
+ required: ['projectId', 'total', 'createdAt'],
68
+ additionalProperties: false,
69
+ }
70
+ ```
71
+
72
+ ### Throw typed errors from a handler
21
73
 
22
- ```typescript
23
- import { AuthUnknown } from '@owlmeans/auth'
74
+ A handler that finds no identity throws `AuthUnknown`; one that finds an identity without the right
75
+ to act throws `AuthForbidden`. Organization-scoped records are keyed by the resolved id from
76
+ `makeEntityScope(req).requireEntityKey()`, never by the slug on the token.
24
77
 
25
- export const create = handleBody(async (body, context, request) => {
26
- if (request.auth?.entityId == null) {
27
- throw new AuthUnknown('entity')
78
+ ```ts
79
+ import { AuthForbidden, AuthUnknown } from '@owlmeans/auth'
80
+ import { makeEntityScope } from '@owlmeans/auth-common'
81
+ import { handlers } from '@owlmeans/server-api'
82
+ import { invoiceProtocols } from 'my-app-common'
83
+ import type { AppContext } from '../types.js'
84
+
85
+ const api = handlers<AppContext>()
86
+
87
+ export const listInvoices = api.request(invoiceProtocols.list, async (req, context) => {
88
+ if (req.auth?.profileId == null) {
89
+ throw new AuthUnknown('profile')
90
+ }
91
+ const entityId = makeEntityScope(req).requireEntityKey() // stable record id, never from the token
92
+
93
+ return await loadInvoices(context, entityId, req.params.projectId)
94
+ })
95
+
96
+ export const archiveInvoice = api.request(invoiceProtocols.archive, async (req, context) => {
97
+ const entityId = makeEntityScope(req).requireEntityKey()
98
+ if (!req.auth!.scopes.includes('invoice-admin')) {
99
+ throw new AuthForbidden('permission')
28
100
  }
29
- // ...
101
+
102
+ return await archive(context, entityId, req.params.id)
30
103
  })
31
104
  ```
32
105
 
33
- Check authentication stage in a WebSocket connection:
106
+ ### Deny access in a gate
107
+
108
+ A gate service declared on a protocol (`gate: { alias, params }`) asserts scopes and throws
109
+ `AuthForbidden` on denial.
110
+
111
+ ```ts
112
+ import { createLazyService } from '@owlmeans/context'
113
+ import type { GateService } from '@owlmeans/entrypoint'
114
+ import { ALL_SCOPES, AuthForbidden } from '@owlmeans/auth'
115
+ import { makeEntityScope } from '@owlmeans/auth-common'
34
116
 
35
- ```typescript
36
- import { AuthenticationStage } from '@owlmeans/auth'
117
+ export const makeProjectGate = (alias: string = 'my-app:project-gate'): GateService =>
118
+ createLazyService<GateService>(alias, {
119
+ assert: async (req, _, params) => {
120
+ if (req.auth == null) throw new AuthForbidden('auth')
121
+
122
+ const entityId = makeEntityScope(req).entityKeyOf()
123
+ if (entityId == null) throw new AuthForbidden('entity')
124
+
125
+ // Params name the organization by its stable id, matching how grants are stored.
126
+ const required = params.map(p => p.replace(/\{entity\}/g, entityId))
127
+ const scopes = req.auth.scopes ?? []
128
+ if (!required.every(p => scopes.includes(ALL_SCOPES) || scopes.includes(p))) {
129
+ throw new AuthForbidden('permission')
130
+ }
131
+ },
132
+ })
133
+ ```
37
134
 
38
- if (connection.stage !== AuthenticationStage.Authenticated) {
39
- throw new AuthUnknown('not-authenticated')
135
+ ### Authenticate a socket connection
136
+
137
+ A socket authenticates after its connection is open, so it moves through `AuthenticationStage`
138
+ itself, sets the bearer token under `AUTH_HEADER`, and must call `makeEntityScope(req).attachEntity(context)`.
139
+
140
+ ```ts
141
+ import type { Auth, AuthToken } from '@owlmeans/auth'
142
+ import { AUTH_HEADER, AuthenFailed, AuthenticationStage, AuthUnknown } from '@owlmeans/auth'
143
+ import { DEFAULT_GUARD, makeEntityScope } from '@owlmeans/auth-common'
144
+ import type { AbstractRequest, AbstractResponse, GuardService } from '@owlmeans/entrypoint'
145
+ import { provideResponse } from '@owlmeans/entrypoint'
146
+ import type { AppContext } from '../types.js'
147
+
148
+ export const authenticateSocket = (context: AppContext, req: AbstractRequest) =>
149
+ async (stage: AuthenticationStage, token: AuthToken) => {
150
+ if (stage !== AuthenticationStage.Authenticate) throw new AuthUnknown('stage')
151
+
152
+ req.headers ??= {}
153
+ req.headers[AUTH_HEADER] ??= token.token
154
+
155
+ const res: AbstractResponse<Auth> = provideResponse({ header: () => void 0 })
156
+ if (!await context.service<GuardService>(DEFAULT_GUARD).handle(req, res) || res.value == null) {
157
+ throw new AuthenFailed('guard')
158
+ }
159
+
160
+ req.auth = res.value
161
+ await makeEntityScope(req).attachEntity(context)
162
+
163
+ return [AuthenticationStage.Authenticated, true]
164
+ }
165
+ ```
166
+
167
+ ### Build payloads, read the organization, widen a token schema
168
+
169
+ `AuthRole` is a string enum, `authHelper.entitySlugOf` is the only supported way to read the organization off a
170
+ payload, and `AuthTokenSchema` caps `token` at 1024 characters — a route carrying a wrapped
171
+ credential envelope declares its own wider schema.
172
+
173
+ ```ts
174
+ import type { JSONSchemaType } from 'ajv'
175
+ import type { AuthPayload, AuthToken } from '@owlmeans/auth'
176
+ import { AuthRole, AuthenticationType, authHelper } from '@owlmeans/auth'
177
+
178
+ const payload: AuthPayload = {
179
+ type: AuthenticationType.OneTimeToken,
180
+ role: AuthRole.User,
181
+ userId: 'account-1',
182
+ profileId: 'profile-1',
183
+ entitySlug: 'acme-studio',
184
+ scopes: ['my-app-project'],
185
+ }
186
+
187
+ const orgLabel = authHelper.entitySlugOf(payload) // string | undefined — opaque, never a database key
188
+
189
+ export const WrappedTokenSchema: JSONSchemaType<AuthToken> = {
190
+ type: 'object',
191
+ properties: { token: { type: 'string', minLength: 32, maxLength: 8192 } },
192
+ required: ['token'],
193
+ additionalProperties: false,
40
194
  }
195
+
196
+ export const tokenOf = (body: unknown): string | undefined =>
197
+ authHelper.isAuthToken(body) ? body.token : undefined
41
198
  ```
42
199
 
43
200
  ## API
44
201
 
202
+ All symbols are exported from the package root (`@owlmeans/auth`); there are no subpath exports.
203
+
45
204
  ### Types
46
205
 
47
- - `Auth` — the auth object attached to `request.auth`; contains `userId`, `entityId`, `role`, `scopes`
48
- - `AuthCredentials` — signed credential payload with `challenge`, `credential`, `publicKey`
49
- - `AuthPayload` — base payload with `type`, `role`, `userId`, `profileId`, `expiresAt`
50
- - `AuthToken` — JWT-like token structure
206
+ | Symbol | Kind | Purpose |
207
+ |--------|------|---------|
208
+ | `Authorization` | interface | RBAC base: `entitySlug?`, `scopes`, `permissions?`, `attributes?`, `permissioned?`, `denormalized?` |
209
+ | `ProfilePayload` | interface | `Authorization` + `groups?` |
210
+ | `AuthPayload` | interface | `ProfilePayload` + `type`, `role`, `userId`, `source?`, `profileId?`, `expiresAt?` |
211
+ | `AuthCredentials` | interface | `AuthPayload` + `challenge`, `credential`, `publicKey?` — the authenticate body |
212
+ | `Auth` | interface | `AuthPayload` + `token`, `isUser`, `createdAt` — the identity on `request.auth` |
213
+ | `Profile` | interface | `ProfilePayload` + `id`, `name`, `credential?`, `secret?` — a stored identity record |
214
+ | `Group` | interface | `Authorization` + `id`, `name` |
215
+ | `AllowanceRequest` | interface | `Partial<AuthPayload>` with required `type` — asks for a challenge |
216
+ | `AllowanceResponse` | interface | `{ challenge }` |
217
+ | `AuthToken` | interface | `{ token }` — the bearer envelope on the wire |
218
+ | `PermissionSet` | interface | `scope`, `title?`, `permissions: Capabilties`, `resources?` |
219
+ | `Capabilties` | interface | Map of capability name to `boolean \| number \| null` |
220
+ | `AttributeSet` | interface | `scope`, `attributes: string[]` |
221
+ | `RelyToken` | interface | Rely-handshake token: `nonce`, `pin?`, `token?`, `check?` |
222
+ | `SupervisorCredentialPayload` | interface | `{ salt, signature }` packed into a supervisor credential |
51
223
 
52
224
  ### Enums
53
225
 
54
- ```typescript
55
- enum AuthRole { User, Guest, Service, System, Admin, Superuser, Blocked }
56
- enum AuthenticationType { BasicEd25519, OneTimeToken, ReCaptcha }
57
- enum AuthenticationStage { /* connection auth lifecycle */ }
58
- ```
226
+ | Symbol | Kind | Purpose |
227
+ |--------|------|---------|
228
+ | `AuthRole` | string enum | `User`, `Guest`, `Service`, `System`, `Admin`, `Superuser`, `Blocked` |
229
+ | `AuthenticationType` | string enum | How identity is proven: `BasicEd25519`, `OneTimeToken`, `ReCaptcha`, `WalletDid`, `RelyHandshake`, `WalletConsumer`, `WalletProvider`, `Google` (`'google-oauth'`), `Supervisor` (`'pk-supervisor'`) |
230
+ | `AuthroizationType` (sic) | string enum | How a request carries authorization: `AuthToken`, `Ed25519BasicToken`, `Ed25519BasicSignature` |
231
+ | `AuthenticationStage` | string enum | Flow stage: `Error`, `Init`, `Allowence`, `Authenticate`, `Authentication`, `Authenticated` |
232
+
233
+ ### Constants
234
+
235
+ | Symbol | Kind | Purpose |
236
+ |--------|------|---------|
237
+ | `AUTH_HEADER` / `AUTH_QUERY` | const | `'authorization'` / `'token'` |
238
+ | `ENTITY_QUERY` / `PROFILE_QUERY` | const | `'entitySlug'` / `'profile'` query parameter names |
239
+ | `ALL_SCOPES` / `AUTH_SCOPE` | const | `'*'` / `'__auth'` |
240
+ | `INCLUDE`, `EXCLUDE`, `WILDCARD`, `DELIMITER` | const | Permission-string grammar: `'+'`, `'-'`, `'*'`, `':'` |
241
+ | `GUEST_ID`, `RELY_3RD` | const | Reserved ids: `'__guest'`, `'rely'` |
242
+ | `AUTHEN`, `AUTHEN_INIT`, `AUTHEN_AUTHEN`, `AUTHEN_RELY` | const | Backend authentication entrypoint aliases |
243
+ | `CAUTHEN`, `CAUTHEN_AUTHEN`, `CAUTHEN_AUTHEN_DEFAULT`, `CAUTHEN_AUTHEN_TYPED`, `CAUTHEN_FLOW_ENTER` | const | Front-end authentication entrypoint aliases |
244
+ | `DISPATCHER`, `DISPATCHER_AUTHEN`, `DISPATCHER_SURROGATE` | const | Dispatcher and surrogate login-window entrypoint aliases |
245
+ | `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | const | reCAPTCHA entrypoint aliases |
59
246
 
60
247
  ### Errors
61
248
 
62
- - `AuthUnknown` — thrown when a request is missing or has invalid auth
249
+ Every class extends `ResilientError` (`@owlmeans/error`), is registered for marshalling, and takes
250
+ an optional message suffix (default `'error'`).
251
+
252
+ | Symbol | Kind | Purpose |
253
+ |--------|------|---------|
254
+ | `AuthError` | class | Root of the hierarchy |
255
+ | `AuthUnknown` | class | The subject is not known — missing auth state, unregistered plugin type |
256
+ | `AuthManagerError` | class | The auth manager itself failed |
257
+ | `AuthManagerUnsupported` | class | The manager cannot serve this request shape |
258
+ | `AuthenFailed` | class | Authentication attempted and rejected (bad challenge, code, signature) |
259
+ | `AuthenExists` | class | The identity being registered already exists |
260
+ | `AuthenPayloadError` | class | A required credential field is missing |
261
+ | `AuthPluginError` | class | An auth plugin misbehaved |
262
+ | `TypeMissmatchError` | class | A plugin was handed the wrong authentication type |
263
+ | `AuthorizationError` | class | Authenticated, but no usable authorization |
264
+ | `AuthForbidden` | class | Authenticated and understood — and not allowed |
265
+ | `ProfileError` / `ProfileConsistencyError` | class | A profile is missing / internally inconsistent |
266
+
267
+ ### Schemas
268
+
269
+ | Symbol | Kind | Purpose |
270
+ |--------|------|---------|
271
+ | `AuthorizationSchema`, `ProfilePayloadSchema`, `AuthPayloadSchema` | JSON schema | Payload validation; `AuthPayloadSchema` requires `scopes`, `role`, `type` |
272
+ | `PartialAuthPayloadSchema`, `AllowanceRequestSchema` | JSON schema | The `authentication:init` body |
273
+ | `AuthCredentialsSchema` | JSON schema | The `authentication:authenticate` body; requires `challenge`, `credential`, `scopes`, `role`, `type` |
274
+ | `AuthSchema` | JSON schema | A resolved `Auth` |
275
+ | `AuthTokenSchema`, `OptionalAuthTokenSchema` | JSON schema | Bearer-token bodies; `token` is 32–1024 characters |
276
+ | `ProfileSchema` | JSON schema | A stored `Profile` |
277
+ | `PermissionSetSchema`, `AttributeSetSchema`, `CapabiltiesSchema` | JSON schema | Permission and attribute shapes |
278
+ | `RelyChallengeSchema` | JSON schema | A `RelyToken` |
279
+ | `ScopeValueSchema`, `PermissionValueSchema`, `ResourceValueSchema`, `AttributeValueSchema`, `GroupValueSchema`, `TypeNameSchema`, `EnumValueSchema`, `IdValueSchema` | JSON schema | Reusable string field schemas with length bounds |
280
+ | `EntitySlugValueSchema` | JSON schema | Organization slug field (3–256 characters) |
281
+ | `EntityValueSchema` | JSON schema | Deprecated alias of `EntitySlugValueSchema` |
282
+ | `DateSchema` | JSON schema | `date-time` formatted `Date` field |
283
+ | `AuthRoleSchema` | JSON schema | Enum of `AuthRole` values |
63
284
 
64
- ## Product-Viable Integration Notes
285
+ ### Helpers
65
286
 
66
- - Manager API handlers use `AuthUnknown('entity')` when `request.auth?.entityId` is missing.
67
- - WebSocket helpers use `Auth`, `AuthToken`, and `AuthenticationStage` to authenticate token-bearing connections.
68
- - Google/OIDC login is normalized into an `AuthPayload` with `userId`, `profileId`, `entityId`, and `scopes`; the local identity store lives in `@owlmeans/server-auth-identity`.
69
- - Gate denial should use `AuthForbidden`; product ownership checks should stay in module gates or handlers, not in this core package.
287
+ | Symbol | Kind | Purpose |
288
+ |--------|------|---------|
289
+ | `authHelper.entitySlugOf(payload?)` | method | The organization carried by a payload: `entitySlug`, falling back to a legacy `entityId` |
290
+ | `authHelper.verifyAuth(auth)` | method | Validate against `AuthSchema` (AJV with formats) |
291
+ | `authHelper.verifyAuthCredentials(auth)` | method | Validate against `AuthCredentialsSchema` |
292
+ | `authHelper.isAuth(value)` | type guard | Has `token` and `isUser` |
293
+ | `authHelper.isAuthCredentials(value)` | type guard | Has `challenge` and `credential` |
294
+ | `authHelper.isAuthToken(value)` | type guard | Has a string `token` |
295
+ | `buildSupervisorPayload(challenge, userId, salt)` | function | The canonical payload the PK supervisor login signs and verifies |
70
296
 
71
- ### AJV Schemas (for module filter definitions)
297
+ ## Common pitfalls
72
298
 
73
- - `AuthCredentialsSchema` — validates an auth credential request body
74
- - `AllowanceRequestSchema` — validates an allowance/init request body
75
- - `AuthTokenSchema` — validates query params containing an auth token
299
+ - `AuthRole` is a **string** enum — use the members; numeric literals do not compile.
300
+ - Read the organization with `authHelper.entitySlugOf()`, never `payload.entitySlug` directly. Its result may
301
+ be a legacy `entityId`, so treat it as an opaque key: never compose names from it and never write
302
+ it as a database key — use `makeEntityScope(req).requireEntityKey()` / `.requireEntity()` from
303
+ `@owlmeans/auth-common`.
304
+ - Never put `entityId` on the wire (tokens, URLs, query params, forms) — only `entitySlug`.
305
+ - Any code path that establishes authentication outside the HTTP boundary (sockets) must call
306
+ `makeEntityScope(request).attachEntity(context)`, or `request.entity` stays empty.
307
+ - Pick the right error: a gate denial is `AuthForbidden`, a missing identity is `AuthUnknown`, a
308
+ failed credential check is `AuthenFailed`.
309
+ - `AuthCredentialsSchema` requires `type`, `role` and `scopes` on every authenticate call.
310
+ - `AuthTokenSchema` caps `token` at 1024 characters; a route accepting a wrapped credential envelope
311
+ needs its own wider schema.
312
+ - Keep ownership and permission rules out of this package — compose them in entrypoint gates or
313
+ handlers around these types.
314
+ - `ajv` is a peer dependency; without it the `verify*` helpers fail to resolve.
76
315
 
77
- ## Related Packages
316
+ ## Related packages
78
317
 
79
- - [`@owlmeans/auth-common`](../auth-common) — auth modules, guards, and middleware
80
- - [`@owlmeans/server-auth`](../server-auth) — server-side auth service implementation
81
- - [`@owlmeans/client-auth`](../client-auth) — client-side auth service
318
+ - [`@owlmeans/auth-common`](../auth-common) — guards, shared auth protocols, organization-entity resolution
319
+ - [`@owlmeans/server-auth`](../server-auth) — server-side auth service and plugins
320
+ - [`@owlmeans/server-auth-identity`](../server-auth-identity) — local identity store behind provider logins
321
+ - [`@owlmeans/client-auth`](../client-auth) — browser auth service and login hooks
322
+ - [`@owlmeans/entrypoint`](../entrypoint) — protocols, guards and gates that consume these types
323
+ - [`@owlmeans/error`](../error) — `ResilientError`, the base of every auth error
324
+ - [`@owlmeans/socket`](../socket) — socket connections that authenticate through `AuthenticationStage`
82
325
 
83
326
  <!-- owlmeans:agent-guidance:start -->
84
327
  ## Agent guidance
@@ -88,7 +331,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
88
331
  your project's skill store (`.agents/skills/`):
89
332
 
90
333
  ```sh
91
- npx @owlmeans/agent-skills
334
+ npx @owlmeans/agent-skills@^0.1.18-rc.49
92
335
  ```
93
336
 
94
337
  The embedded files are version-matched to this package release. Do not edit them
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
3
  "package": "@owlmeans/auth",
4
- "version": "0.1.18-rc.0",
5
- "generatedAt": "2026-08-16T22:20:50.498Z",
4
+ "version": "0.1.18-rc.40",
5
+ "generatedAt": "2026-10-05T21:03:06.362Z",
6
6
  "canonicalRepo": "https://github.com/owlmeans/common",
7
7
  "entries": [
8
8
  {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: auth
3
- description: How to use @owlmeans/auth — core authentication types, errors (AuthUnknown, AuthError), permissions, allowance, rely, and entity primitives shared across server and client. Auto-invoked when importing auth types/errors or working with request authentication.
3
+ description: How to use @owlmeans/auth — the core authentication and authorization vocabulary shared by server and client, covering the Auth / AuthPayload / AuthCredentials types, the AuthRole and AuthenticationType enums, the error hierarchy (AuthUnknown, AuthenFailed, AuthForbidden …), the request JSON schemas, the entrypoint aliases, and authHelper.entitySlugOf for reading the organization entity off a token. Auto-invoked when importing auth types, errors, schemas or constants, or when working with request authentication.
4
4
  user-invocable: false
5
5
  ---
6
6
  <!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
@@ -8,58 +8,157 @@ user-invocable: false
8
8
  # @owlmeans/auth
9
9
 
10
10
  **Layer:** Core
11
- **Install:** `"@owlmeans/auth": "^0.1.18-rc.0"` in `dependencies`
11
+ **Install:** `"@owlmeans/auth": "^0.1.18-rc.40"` in `dependencies`
12
+
13
+ Types, enums, errors and schemas only — no services, no wiring. Every other auth package builds on
14
+ this vocabulary, so a symbol belongs here exactly when both a server and a browser need to agree on
15
+ it.
12
16
 
13
17
  ## Key Exports
14
18
 
19
+ ### Identity types
20
+
15
21
  | Export | Description |
16
22
  |--------|-------------|
17
- | `AuthUnknown` | Error thrown when expected entity/auth is missing on a request |
18
- | `AuthError` and subclasses | Typed auth errors mapping to HTTP 401/403 |
19
- | `Auth` types | Request auth payload shape (entityId, scopes, profile) |
20
- | `Permission` helpers | Check scopes/permissions on a request |
21
- | `Allowance` helpers | Inspect/grant allowances |
22
- | `Entity`, `Rely` types | Shared entity-relationship primitives |
23
+ | `Authorization` | RBAC base: `entitySlug?`, `scopes`, `permissions?`, `attributes?`, `permissioned?`, `denormalized?` |
24
+ | `ProfilePayload` | `Authorization` + `groups?` |
25
+ | `AuthPayload` | `ProfilePayload` + `type`, `role`, `userId`, `source?`, `profileId?`, `expiresAt?` |
26
+ | `AuthCredentials` | `AuthPayload` + `challenge`, `credential`, `publicKey?` — what a client posts to authenticate |
27
+ | `Auth` | `AuthPayload` + `token`, `isUser`, `createdAt` — the authenticated identity a guard resolves |
28
+ | `Profile` | `ProfilePayload` + `id`, `name`, `credential?`, `secret?` — a stored identity record |
29
+ | `Group` | `Authorization` + `id`, `name` |
30
+ | `AllowanceRequest` | `Partial<AuthPayload>` with a required `type` — asks for a challenge |
31
+ | `AllowanceResponse` | `{ challenge }` |
32
+ | `AuthToken` | `{ token }` — the bearer envelope on the wire |
33
+ | `PermissionSet` / `Capabilties` / `AttributeSet` | Scope-bound capability shapes |
34
+ | `RelyToken` | The rely-handshake token used by wallet/provider flows |
35
+
36
+ ### Enums and constants
23
37
 
24
- ## Usage
38
+ | Export | Description |
39
+ |--------|-------------|
40
+ | `AuthRole` | **String** enum: `User`, `Guest`, `Service`, `System`, `Admin`, `Superuser`, `Blocked` |
41
+ | `AuthenticationType` | How identity is proven: `BasicEd25519`, `OneTimeToken`, `ReCaptcha`, `WalletDid`, `RelyHandshake`, `WalletConsumer`, `WalletProvider`, `Google` (`'google-oauth'`), `Supervisor` (`'pk-supervisor'`) |
42
+ | `AuthroizationType` (sic) | How a request carries authorization: `AuthToken`, `Ed25519BasicToken`, `Ed25519BasicSignature` |
43
+ | `AuthenticationStage` | Client-side flow stage: `Error`, `Init`, `Allowence`, `Authenticate`, `Authentication`, `Authenticated` |
44
+ | `AUTH_HEADER` / `AUTH_QUERY` | `'authorization'` / `'token'` |
45
+ | `ENTITY_QUERY` / `PROFILE_QUERY` | `'entitySlug'` / `'profile'` |
46
+ | `ALL_SCOPES` / `AUTH_SCOPE` | `'*'` / `'__auth'` |
47
+ | `INCLUDE`, `EXCLUDE`, `WILDCARD`, `DELIMITER` | Permission-string grammar |
48
+ | `GUEST_ID`, `RELY_3RD` | Reserved ids |
49
+ | `AUTHEN`, `AUTHEN_INIT`, `AUTHEN_AUTHEN`, `AUTHEN_RELY` | Backend entrypoint aliases |
50
+ | `CAUTHEN`, `CAUTHEN_AUTHEN`, `CAUTHEN_AUTHEN_DEFAULT`, `CAUTHEN_AUTHEN_TYPED`, `CAUTHEN_FLOW_ENTER` | Front-end entrypoint aliases |
51
+ | `DISPATCHER`, `DISPATCHER_AUTHEN`, `DISPATCHER_SURROGATE` | Dispatcher and surrogate-window entrypoint aliases |
52
+ | `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | reCAPTCHA entrypoint aliases |
53
+
54
+ ### Errors
55
+
56
+ `AuthError` is the root; everything below is a subclass and every class is i18n-aware through
57
+ `@owlmeans/error`.
58
+
59
+ | Error | Raise it when |
60
+ |-------|---------------|
61
+ | `AuthUnknown` | The thing being authenticated is not known at all — an unregistered plugin type, a method a gate refuses, a request whose auth state is missing. Declares `httpStatus = 400`: the caller's request, never a 500 |
62
+ | `AuthManagerError` | The auth manager itself failed |
63
+ | `AuthManagerUnsupported` | The manager cannot serve this request shape |
64
+ | `AuthenFailed` | Authentication was attempted and rejected (bad challenge, bad code, bad signature) |
65
+ | `AuthenExists` | The identity being registered already exists |
66
+ | `AuthenPayloadError` | A required credential field is missing |
67
+ | `AuthPluginError` / `TypeMissmatchError` | A plugin misbehaved / was handed the wrong type |
68
+ | `AuthorizationError` | Authenticated, but the request carries no usable authorization |
69
+ | `AuthForbidden` | Authenticated and understood — and not allowed |
70
+ | `ProfileError` / `ProfileConsistencyError` | A profile is missing or internally inconsistent |
71
+
72
+ ### Schemas and helpers
25
73
 
26
- Throw `AuthUnknown` from a handler when the auth context is missing the entity:
74
+ | Export | Description |
75
+ |--------|-------------|
76
+ | `AuthorizationSchema`, `ProfilePayloadSchema`, `AuthPayloadSchema` | Payload validation; `AuthPayloadSchema.required` is `['scopes', 'role', 'type']` |
77
+ | `PartialAuthPayloadSchema`, `AllowanceRequestSchema` | The `/authentication/init` body |
78
+ | `AuthCredentialsSchema` | The `/authentication/authenticate` body — spreads `AuthPayloadSchema.required`, so `type`, `role` and `scopes` are mandatory on every authenticate call |
79
+ | `AuthSchema`, `AuthTokenSchema`, `OptionalAuthTokenSchema` | Resolved auth and bearer-token bodies |
80
+ | `ProfileSchema`, `RelyChallengeSchema`, `PermissionSetSchema`, `AttributeSetSchema`, `CapabiltiesSchema` | Record and permission schemas |
81
+ | `ScopeValueSchema`, `PermissionValueSchema`, `ResourceValueSchema`, `AttributeValueSchema`, `EntitySlugValueSchema`, `GroupValueSchema`, `TypeNameSchema`, `EnumValueSchema`, `IdValueSchema`, `DateSchema`, `AuthRoleSchema` | Reusable scalar schemas |
82
+ | `authHelper.entitySlugOf(payload)` | The organization entity carried by an auth payload — its `entitySlug`, falling back to an `entityId` the payload may carry instead — see below |
83
+ | `authHelper.verifyAuth`, `authHelper.verifyAuthCredentials` | Validate against `AuthSchema` / `AuthCredentialsSchema` |
84
+ | `authHelper.isAuth`, `authHelper.isAuthCredentials`, `authHelper.isAuthToken` | Type guards |
85
+ | `buildSupervisorPayload`, `SupervisorCredentialPayload` | The payload the PK supervisor login signs — see the `supervisor-auth` skill |
86
+
87
+ `AuthTokenSchema` caps `token` at 1024 characters. A route that accepts a token wrapping a full
88
+ credential envelope needs its own wider schema.
89
+
90
+ ## The organization entity on a token
91
+
92
+ `entitySlug` is the organization-entity value this package declares: `Authorization.entitySlug`,
93
+ the renameable, human-readable name of the customer organization, and what travels in tokens, URLs,
94
+ query params and request bodies. No `entityId` is declared on any type here — the stable record id
95
+ an implementation stores its rows against belongs to whichever package owns the organization
96
+ registry, and is resolved from the slug at the server boundary.
97
+
98
+ Read the value through `authHelper.entitySlugOf()` rather than off the field. A token is signed once
99
+ and then read for as long as it lives, across deployments, and the helper absorbs that spread: when
100
+ `entitySlug` is absent it returns an `entityId` the payload carries instead, so a payload that names
101
+ the organization under either field resolves through one code path. That fallback is why the helper
102
+ is the only supported way to get the value out of a payload:
27
103
 
28
104
  ```typescript
29
- import { AuthUnknown } from '@owlmeans/auth'
30
- import { handleRequest } from '@owlmeans/server-app'
105
+ import { authHelper } from '@owlmeans/auth'
31
106
 
32
- export const list = handleRequest(async (req, context) => {
33
- if (req.auth?.entityId == null) throw new AuthUnknown('entity')
34
- return await (context as Context).project().list({ entityId: req.auth.entityId })
35
- })
107
+ const slug = authHelper.entitySlugOf(req.auth) // string | undefined
36
108
  ```
37
109
 
38
- ## Product-Viable Usage Notes
39
-
40
- - `product-viable` handlers use `AuthUnknown('entity')` when a request should be authenticated but lacks `req.auth.entityId`.
41
- - WebSocket helpers use `Auth`, `AuthToken`, and `AuthenticationStage` to move token-bearing connections into authenticated state.
42
- - Google/OIDC login ultimately produces a normal `AuthPayload` with `userId`, `profileId`, `entityId`, and `scopes`; `@owlmeans/server-auth-identity` stores that local identity and returns the payload.
43
- - Authorization failures in gates should use `AuthForbidden`, while missing handler auth/entity state usually uses `AuthUnknown`.
44
- - Keep product ownership rules outside `@owlmeans/auth`; downstream apps compose `@owlmeans/entrypoint` gates or handler-level entity checks around these core types.
110
+ Because of that fallback the result is not guaranteed to be a slug: a payload carrying only
111
+ `entityId` yields that id. Treat it as an opaque organization key, never as a name to compose from
112
+ and never as a database key written directly — `@owlmeans/auth-common`'s
113
+ `makeEntityScope(req).entityKeyOf()` / `.requireEntityKey()` give storage keys, and they prefer the
114
+ resolved id; a user-facing name wants the resolved entity's current slug.
45
115
 
46
- ## AuthRole enum
116
+ ## AuthRole is a string enum
47
117
 
48
- `AuthRole` is a **string** enum (not numeric). Always use the enum members — never assign a number literal to `role`:
118
+ Always use the members; a numeric literal does not compile.
49
119
 
50
120
  ```typescript
51
121
  import { AuthRole } from '@owlmeans/auth'
122
+ import type { AuthCredentials } from '@owlmeans/auth'
52
123
 
53
- // Correct
54
- const creds: AuthCredentials = { role: AuthRole.User, ... }
124
+ const creds: AuthCredentials = { role: AuthRole.User, /* … */ } as AuthCredentials
125
+ ```
126
+
127
+ ## Usage
55
128
 
56
- // WRONG — will not compile
57
- const creds: AuthCredentials = { role: 0, ... }
129
+ Throw from a handler when the request is missing the identity it needs:
130
+
131
+ ```typescript
132
+ import { AuthUnknown, authHelper } from '@owlmeans/auth'
133
+ import { handlers } from '@owlmeans/server-app'
134
+
135
+ export const list = handlers<Context>().request(projectProtocols.list, async (req, context) => {
136
+ const slug = authHelper.entitySlugOf(req.auth)
137
+ if (slug == null) throw new AuthUnknown('entity')
138
+
139
+ return await listProjects(context, slug)
140
+ })
58
141
  ```
59
142
 
60
- Members: `User`, `Guest`, `Service`, `System`, `Admin`, `Superuser`, `Blocked`.
143
+ Rules of thumb:
144
+
145
+ - A gate that decides "not allowed" throws `AuthForbidden` (403); a handler that finds no identity
146
+ to act on, or a sign-in naming a method nobody serves, throws `AuthUnknown` (400); a failed
147
+ credential check throws `AuthenFailed`. `@owlmeans/server-api` maps the authorization family to
148
+ 401/403 before reading a class's declared `httpStatus`, so `AuthUnknown`'s 400 never masks them.
149
+ - Keep ownership rules out of this package. Downstream apps compose `@owlmeans/entrypoint` gates or
150
+ handler-level checks around these types.
151
+ - WebSocket wiring uses `Auth`, `AuthToken` and `AuthenticationStage` to move a token-bearing
152
+ connection into an authenticated state.
153
+ - A provider login (Google/OIDC, OTP, supervisor) ultimately produces an ordinary `AuthPayload` with
154
+ `userId`, `profileId`, `entitySlug` and `scopes`; `@owlmeans/server-auth-identity` stores the local
155
+ identity behind it and returns that payload.
61
156
 
62
157
  ## Depends On
63
158
 
64
- - `@owlmeans/error` — `AuthUnknown` and friends extend `ResilientError`
65
- - `@owlmeans/i18n` — for translatable error messages
159
+ - `@owlmeans/error` — every error class extends `ResilientError`, which is what makes the messages
160
+ translatable and re-throwable across the wire
161
+ - `ajv-formats` — date/time formats for the `verify*` helpers
162
+ - `ajv` — a **peer** dependency (`"*"`), not a direct one: `authHelper.verifyAuth` /
163
+ `authHelper.verifyAuthCredentials` construct `new Ajv({ strict: false })`. Install it alongside
164
+ this package, or those two helpers fail to resolve.