Security quick start¶
Add identity and access rules to a resty application in one decorator: a guarded route, a public route, password login and the difference between 401 and 403.
@typeix/resty-security adds two things to a resty application: a way to turn a credential into an Identity, and a list of rules that decide which requests may proceed. Both are declared on the root module, next to @RootModule.
The bootstrap does not change. pipeServer(server, Application) stays exactly as it was — the decorator publishes the guard chain through module metadata and pipeServer picks it up.
Install¶
npm i @typeix/resty-security
A complete, secured application¶
import {createServer} from "http";
import {Controller, GET, Injectable, pipeServer, RootModule} from "@typeix/resty";
import {
DefaultAuthenticator, Guard, Identity, IdentityStore, LoginChecker,
ScryptPasswordHasher, SecurityConfiguration, identityOf
} from "@typeix/resty-security";
@Injectable()
class UsersStore implements IdentityStore {
/** a real application reads this from the database; hashed once here so the sample runs */
private readonly stored: Promise<string> = new ScryptPasswordHasher().hash("secret");
async find(name: string): Promise<Identity | null> {
return name === "ada" ? identityOf({name, grants: ["ROLE_EDITOR"]}) : null;
}
async passwordOf(name: string): Promise<string | null> {
return name === "ada" ? await this.stored : null;
}
}
@Controller({path: "/articles"})
class ArticlesController {
@GET()
list(): object {
return {articles: []};
}
@GET("/draft")
@Guard("inGrant('EDITOR')")
draft(): object {
return {draft: true};
}
}
@SecurityConfiguration({
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
.add(new LoginChecker(store, new ScryptPasswordHasher())),
guards: guards => guards
.match("/health", "allow()")
.anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {
}
async function bootstrap() {
const server = createServer();
await pipeServer(server, Application);
server.listen(3000);
}
bootstrap();
Three things are worth reading twice in that snippet:
- The order of the decorators.
@SecurityConfigurationis applied above@RootModule, which means it runs last and can see the module'sshared_providers. That is how(store: UsersStore, authenticator: DefaultAuthenticator)receives its arguments without aproviderslist. DefaultAuthenticatorinshared_providers, as a bare class. The injector owns the instance, so@Inject(DefaultAuthenticator)anywhere in the application returns the same object the chain consults. The package normalizes that one entry to a zero-argument factory internally — see The authenticator for why that is necessary.guardsis last-match-wins safe.match("/health", "allow()")must come before the fallback. AmatchafteranyRequest()throws at boot.
Try it¶
# no credential: not authenticated, and the fallback requires an identity
curl -i http://localhost:3000/articles
# basic login against the UsersStore
curl -i -u ada:secret http://localhost:3000/articles
# a wrong password
curl -i -u ada:wrong http://localhost:3000/articles
# an open pattern
curl -i http://localhost:3000/health
| Request | Result |
|---|---|
GET /articles without a credential | 401 Unauthorized |
GET /articles as ada:secret | 200 |
GET /articles as ada:wrong | 401 Unauthorized |
GET /articles/draft as ada:secret | 200, the identity holds ROLE_EDITOR |
GET /health without a credential | 404 — the route does not exist, but the rule allowed it to reach the router |
The last row is the important one: 404 there means the chain allowed the request and the router found nothing. If the rule had denied it, the status would be 401. That distinction is the fastest way to tell "not allowed" from "not found".
401 or 403?¶
The chain picks the status from the identity, not from the rule:
| Caller | Denied | Why |
|---|---|---|
| anonymous | 401 Unauthorized | no identity was resolved; the challenge message is Unauthorized |
| authenticated | 403 Forbidden | an identity exists, it just lacks the grant; the denial message is Forbidden |
Both messages are configurable:
@SecurityConfiguration({
guards: guards => guards.anyRequest("identified()"),
challengeMessage: "Sign in with your company account",
denialMessage: "Your account is not allowed to do that"
})
Deny by default¶
A request that matches no rule is denied. This is deliberate: a controller added next month, with no rule of its own, is protected rather than exposed.
guards: guards => guards
.match("/public/**", "allow()") // explicitly public
.anyRequest("identified()") // everything else needs an identity
Even without anyRequest, an unmatched request is denied — the fallback only lets you choose which rule applies to the leftovers.
What the rule language looks like¶
| Rule | Meaning |
|---|---|
allow() | everyone, including anonymous callers |
identified() | any authenticated caller |
inGrant('EDITOR') | holds ROLE_EDITOR |
may('article:write') | holds the article:write permission |
identity.tenant == 'acme' | an attribute matches |
header('x-api-version') == '2' | read a request header |
method != 'DELETE' or may('article:delete') | http method plus a permission |
The full grammar, including what each rule can read and the exact precedence, is in Rules.
Adding more credential kinds¶
DefaultAuthenticator holds a list of checkers. The first one that supports the credential kind and answers non-null wins, so adding a token on top of login is one more .add():
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
.add(new LoginChecker(store, new ScryptPasswordHasher())) // Basic, kind "login"
.add(new TokenChecker(token => resolveApiToken(token))) // Bearer, kind "token"
See Credentials for API keys, custom checkers and JWT.
Next¶
- Rules — patterns, ordering and the complete expression reference
- The authenticator — the four declaration forms and where their arguments come from
- Protecting every endpoint —
/docs,/graphqland websockets