@plinthjs/api-tokens 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Plinth contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # @plinthjs/api-tokens
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lightweight API token authentication for Plinth. Issue personal
4
+ access tokens with abilities and optional expiry, store only a SHA-256 hash of each secret, and
5
+ authenticate `id|secret` bearer tokens with a constant-time `TokenGuard`. Persistence sits behind a
6
+ small `TokenStore` interface with an in-memory `ArrayTokenStore` default, and the clock and id/secret
7
+ generators are injectable for deterministic tests.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @plinthjs/api-tokens
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { ArrayTokenStore, hasApiTokens, TokenGuard } from '@plinthjs/api-tokens'
19
+
20
+ const store = new ArrayTokenStore()
21
+
22
+ // Issue a token for a user (the HasApiTokens trait equivalent).
23
+ const user = hasApiTokens(store, { id: 42, type: 'User' })
24
+ const { plainTextToken, accessToken } = user.createToken({
25
+ name: 'cli',
26
+ abilities: ['servers:read', 'servers:deploy'],
27
+ expiresAt: Date.now() + 30 * 24 * 3_600_000, // optional
28
+ })
29
+
30
+ // plainTextToken ('id|secret') is shown to the user exactly once; only the hash is stored.
31
+
32
+ // Authenticate an incoming request.
33
+ const guard = new TokenGuard(store)
34
+ const bearer = request.headers.authorization?.replace(/^Bearer /, '') ?? ''
35
+
36
+ const token = guard.authenticate(bearer) // PersonalAccessToken | null
37
+ if (token?.can('servers:deploy')) {
38
+ // ...
39
+ }
40
+
41
+ guard.check(bearer) // boolean
42
+ guard.authenticateToken(bearer) // the owner id (42), or null
43
+ ```
44
+
45
+ `authenticate` returns `null` for a malformed, unknown, mismatched or expired token, and stamps
46
+ `lastUsedAt` on success.
47
+
48
+ ## Abilities
49
+
50
+ Tokens default to the wildcard ability `'*'` (`WILDCARD_ABILITY`), which grants everything.
51
+
52
+ ```ts
53
+ token.can('servers:read') // true
54
+ token.cant('billing:write') // true
55
+ token.isExpired(Date.now()) // false
56
+
57
+ user.tokens() // every token this owner holds
58
+ user.tokenCan('servers:deploy') // true if any of the owner's tokens grants it
59
+ ```
60
+
61
+ ## Issuing tokens directly
62
+
63
+ ```ts
64
+ import { createToken, parseToken } from '@plinthjs/api-tokens'
65
+
66
+ const { plainTextToken } = createToken(store, {
67
+ name: 'deploy-bot',
68
+ abilities: ['servers:deploy'],
69
+ tokenableId: 'bot-1',
70
+ tokenableType: 'Bot',
71
+ })
72
+
73
+ parseToken(plainTextToken) // { id, secret }, or null when malformed
74
+ ```
75
+
76
+ `issueToken` is an alias of `createToken`. Revoke a token by deleting it from the store:
77
+ `store.delete(accessToken.id)`.
78
+
79
+ ## Stores and deterministic tests
80
+
81
+ Implement `TokenStore` (`find`, `save`, `delete`, `all`) to persist tokens elsewhere; a record
82
+ round-trips through `token.toAttributes()` and `PersonalAccessToken.from(attributes)`.
83
+
84
+ ```ts
85
+ let now = 1_000
86
+ let n = 0
87
+ const { plainTextToken } = createToken(
88
+ store,
89
+ { name: 'test', expiresAt: 2_000 },
90
+ { now: () => now, generateId: () => `id-${n++}`, generateSecret: () => 'secret' },
91
+ )
92
+
93
+ const guard = new TokenGuard(store, () => now)
94
+ guard.check(plainTextToken) // true
95
+ now = 2_000
96
+ guard.check(plainTextToken) // false: expired
97
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,247 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var support = require('@plinthjs/support');
5
+
6
+ // src/factory.ts
7
+
8
+ // src/token.ts
9
+ var WILDCARD_ABILITY = "*";
10
+ var PersonalAccessToken = class _PersonalAccessToken {
11
+ /** @see PersonalAccessTokenAttributes.id */
12
+ id;
13
+ /** @see PersonalAccessTokenAttributes.name */
14
+ name;
15
+ /** @see PersonalAccessTokenAttributes.tokenHash */
16
+ tokenHash;
17
+ /** @see PersonalAccessTokenAttributes.abilities */
18
+ abilities;
19
+ /** @see PersonalAccessTokenAttributes.tokenableId */
20
+ tokenableId;
21
+ /** @see PersonalAccessTokenAttributes.tokenableType */
22
+ tokenableType;
23
+ /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
24
+ lastUsedAt;
25
+ /** @see PersonalAccessTokenAttributes.expiresAt */
26
+ expiresAt;
27
+ /** @see PersonalAccessTokenAttributes.createdAt */
28
+ createdAt;
29
+ constructor(attributes) {
30
+ this.id = attributes.id;
31
+ this.name = attributes.name;
32
+ this.tokenHash = attributes.tokenHash;
33
+ this.abilities = [...attributes.abilities];
34
+ if (attributes.tokenableId !== void 0) this.tokenableId = attributes.tokenableId;
35
+ if (attributes.tokenableType !== void 0) this.tokenableType = attributes.tokenableType;
36
+ if (attributes.lastUsedAt !== void 0) this.lastUsedAt = attributes.lastUsedAt;
37
+ if (attributes.expiresAt !== void 0) this.expiresAt = attributes.expiresAt;
38
+ this.createdAt = attributes.createdAt;
39
+ }
40
+ /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */
41
+ static from(attributes) {
42
+ return new _PersonalAccessToken(attributes);
43
+ }
44
+ /**
45
+ * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any
46
+ * other ability must match an entry exactly.
47
+ */
48
+ can(ability) {
49
+ return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability);
50
+ }
51
+ /** The negation of {@link can}. */
52
+ cant(ability) {
53
+ return !this.can(ability);
54
+ }
55
+ /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */
56
+ isExpired(now) {
57
+ return this.expiresAt !== void 0 && this.expiresAt <= now;
58
+ }
59
+ /** A plain snapshot of the record, omitting any unset optional fields. */
60
+ toAttributes() {
61
+ const attributes = {
62
+ id: this.id,
63
+ name: this.name,
64
+ tokenHash: this.tokenHash,
65
+ abilities: [...this.abilities],
66
+ createdAt: this.createdAt
67
+ };
68
+ if (this.tokenableId !== void 0) attributes.tokenableId = this.tokenableId;
69
+ if (this.tokenableType !== void 0) attributes.tokenableType = this.tokenableType;
70
+ if (this.lastUsedAt !== void 0) attributes.lastUsedAt = this.lastUsedAt;
71
+ if (this.expiresAt !== void 0) attributes.expiresAt = this.expiresAt;
72
+ return attributes;
73
+ }
74
+ };
75
+
76
+ // src/factory.ts
77
+ var DEFAULT_ABILITIES = ["*"];
78
+ var SECRET_BYTES = 40;
79
+ var TOKEN_SEPARATOR = "|";
80
+ function hashSecret(secret) {
81
+ return crypto.createHash("sha256").update(secret).digest("hex");
82
+ }
83
+ function parseToken(plainTextToken) {
84
+ const index = plainTextToken.indexOf(TOKEN_SEPARATOR);
85
+ if (index <= 0) return null;
86
+ const id = plainTextToken.slice(0, index);
87
+ const secret = plainTextToken.slice(index + 1);
88
+ if (secret.length === 0) return null;
89
+ return { id, secret };
90
+ }
91
+ function generateSecret() {
92
+ return crypto.randomBytes(SECRET_BYTES).toString("hex");
93
+ }
94
+ function createToken(store, options, seams) {
95
+ const now = (seams?.now ?? Date.now)();
96
+ const id = (seams?.generateId ?? support.uuid)();
97
+ const secret = (seams?.generateSecret ?? generateSecret)();
98
+ const abilities = options.abilities ?? [...DEFAULT_ABILITIES];
99
+ const attributes = {
100
+ id,
101
+ name: options.name,
102
+ tokenHash: hashSecret(secret),
103
+ abilities,
104
+ createdAt: now
105
+ };
106
+ if (options.tokenableId !== void 0) attributes.tokenableId = options.tokenableId;
107
+ if (options.tokenableType !== void 0) attributes.tokenableType = options.tokenableType;
108
+ if (options.expiresAt !== void 0) attributes.expiresAt = options.expiresAt;
109
+ const accessToken = new PersonalAccessToken(attributes);
110
+ store.save(accessToken);
111
+ return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` };
112
+ }
113
+ var issueToken = createToken;
114
+
115
+ // src/store.ts
116
+ function findToken(store, id) {
117
+ return store.find(id);
118
+ }
119
+ var ArrayTokenStore = class {
120
+ tokens = /* @__PURE__ */ new Map();
121
+ /** Seed the store with an optional initial set of tokens. */
122
+ constructor(initial) {
123
+ if (initial !== void 0) {
124
+ for (const token of initial) this.tokens.set(token.id, token);
125
+ }
126
+ }
127
+ find(id) {
128
+ return this.tokens.get(id);
129
+ }
130
+ save(token) {
131
+ this.tokens.set(token.id, token);
132
+ }
133
+ delete(id) {
134
+ this.tokens.delete(id);
135
+ }
136
+ all() {
137
+ return [...this.tokens.values()];
138
+ }
139
+ /** Remove every stored token. Convenience for resetting between tests. */
140
+ flush() {
141
+ this.tokens.clear();
142
+ }
143
+ /** The number of stored tokens. */
144
+ get size() {
145
+ return this.tokens.size;
146
+ }
147
+ };
148
+
149
+ // src/guard.ts
150
+ function hashesMatch(a, b) {
151
+ const left = Buffer.from(a, "utf8");
152
+ const right = Buffer.from(b, "utf8");
153
+ if (left.length !== right.length) return false;
154
+ return crypto.timingSafeEqual(left, right);
155
+ }
156
+ var TokenGuard = class {
157
+ store;
158
+ clock;
159
+ /**
160
+ * @param store The token repository to look records up in.
161
+ * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.
162
+ */
163
+ constructor(store, clock) {
164
+ this.store = store;
165
+ this.clock = clock ?? Date.now;
166
+ }
167
+ /**
168
+ * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the
169
+ * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`
170
+ * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.
171
+ */
172
+ authenticate(bearer) {
173
+ const parts = parseToken(bearer);
174
+ if (parts === null) return null;
175
+ const { id, secret } = parts;
176
+ const token = findToken(this.store, id);
177
+ if (token === void 0) return null;
178
+ if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null;
179
+ const now = this.clock();
180
+ if (token.isExpired(now)) return null;
181
+ token.lastUsedAt = now;
182
+ this.store.save(token);
183
+ return token;
184
+ }
185
+ /**
186
+ * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token
187
+ * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need
188
+ * the user id.
189
+ */
190
+ authenticateToken(bearer) {
191
+ const token = this.authenticate(bearer);
192
+ if (token === null) return null;
193
+ return token.tokenableId ?? null;
194
+ }
195
+ /** Whether `bearer` resolves to a valid, unexpired token. */
196
+ check(bearer) {
197
+ return this.authenticate(bearer) !== null;
198
+ }
199
+ };
200
+
201
+ // src/has-api-tokens.ts
202
+ function ownedBy(token, owner) {
203
+ if (token.tokenableId !== owner.id) return false;
204
+ if (owner.type === void 0) return true;
205
+ return token.tokenableType === owner.type;
206
+ }
207
+ function hasApiTokens(store, owner) {
208
+ return {
209
+ createToken(options, seams) {
210
+ const base = {
211
+ name: options.name,
212
+ tokenableId: owner.id
213
+ };
214
+ if (options.abilities !== void 0) base.abilities = options.abilities;
215
+ if (options.expiresAt !== void 0) base.expiresAt = options.expiresAt;
216
+ if (owner.type !== void 0) base.tokenableType = owner.type;
217
+ return createToken(store, base, seams);
218
+ },
219
+ tokens() {
220
+ return store.all().filter((token) => ownedBy(token, owner));
221
+ },
222
+ tokenCan(ability) {
223
+ return store.all().some(
224
+ (token) => ownedBy(token, owner) && (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability))
225
+ );
226
+ }
227
+ };
228
+ }
229
+
230
+ // src/index.ts
231
+ var VERSION = "0.1.0";
232
+
233
+ exports.ArrayTokenStore = ArrayTokenStore;
234
+ exports.PersonalAccessToken = PersonalAccessToken;
235
+ exports.TOKEN_SEPARATOR = TOKEN_SEPARATOR;
236
+ exports.TokenGuard = TokenGuard;
237
+ exports.VERSION = VERSION;
238
+ exports.WILDCARD_ABILITY = WILDCARD_ABILITY;
239
+ exports.createToken = createToken;
240
+ exports.findToken = findToken;
241
+ exports.hasApiTokens = hasApiTokens;
242
+ exports.hashSecret = hashSecret;
243
+ exports.hashesMatch = hashesMatch;
244
+ exports.issueToken = issueToken;
245
+ exports.parseToken = parseToken;
246
+ //# sourceMappingURL=index.cjs.map
247
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/token.ts","../src/factory.ts","../src/store.ts","../src/guard.ts","../src/has-api-tokens.ts","../src/index.ts"],"names":["createHash","randomBytes","uuid","timingSafeEqual"],"mappings":";;;;;;;;AAUO,IAAM,gBAAA,GAAmB;AAkCzB,IAAM,mBAAA,GAAN,MAAM,oBAAA,CAA6D;AAAA;AAAA,EAE/D,EAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA,EAEA,aAAA;AAAA;AAAA,EAET,UAAA;AAAA;AAAA,EAES,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EA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A,CACJ,KAAI,CACJ,IAAA;AAAA,QACC,CAAC,KAAA,KACC,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,KACnB,KAAA,CAAM,SAAA,CAAU,QAAA,CAAS,gBAAgB,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,SAAS,OAAO,CAAA;AAAA,OACnF;AAAA,IACJ;AAAA,GACF;AACF;;;AClEO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token - the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id - the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme - the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret - the part AFTER the `|` - with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified - full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only - no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` - the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted - the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` - authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens - its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens - API token authentication.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
@@ -0,0 +1,261 @@
1
+ /**
2
+ * `PersonalAccessToken`.
3
+ *
4
+ * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash
5
+ * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what
6
+ * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard
7
+ * `'*'` grants every ability and any other ability requires an exact string match.
8
+ */
9
+ /** The wildcard ability that grants every permission, as in Sanctum. */
10
+ declare const WILDCARD_ABILITY = "*";
11
+ /**
12
+ * The persisted shape of a personal access token - the columns of Sanctum's
13
+ * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is
14
+ * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the
15
+ * record round-trips cleanly under `exactOptionalPropertyTypes`.
16
+ */
17
+ interface PersonalAccessTokenAttributes {
18
+ /** The token id - the part before the `|` in the plaintext, used to look the record up. */
19
+ id: string;
20
+ /** A human-readable name for the token (e.g. the device or integration it was issued for). */
21
+ name: string;
22
+ /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */
23
+ tokenHash: string;
24
+ /** The abilities granted to the token; `['*']` grants everything. */
25
+ abilities: string[];
26
+ /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */
27
+ tokenableId?: string | number;
28
+ /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */
29
+ tokenableType?: string;
30
+ /** Epoch milliseconds when the token was last used to authenticate, if ever. */
31
+ lastUsedAt?: number;
32
+ /** Epoch milliseconds when the token expires; absent means it never expires. */
33
+ expiresAt?: number;
34
+ /** Epoch milliseconds when the token was created. */
35
+ createdAt: number;
36
+ }
37
+ /**
38
+ * A personal access token record. Construct directly from attributes, or via
39
+ * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives
40
+ * here; persistence lives behind a `TokenStore`.
41
+ */
42
+ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
43
+ /** @see PersonalAccessTokenAttributes.id */
44
+ readonly id: string;
45
+ /** @see PersonalAccessTokenAttributes.name */
46
+ readonly name: string;
47
+ /** @see PersonalAccessTokenAttributes.tokenHash */
48
+ readonly tokenHash: string;
49
+ /** @see PersonalAccessTokenAttributes.abilities */
50
+ readonly abilities: string[];
51
+ /** @see PersonalAccessTokenAttributes.tokenableId */
52
+ readonly tokenableId?: string | number;
53
+ /** @see PersonalAccessTokenAttributes.tokenableType */
54
+ readonly tokenableType?: string;
55
+ /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
56
+ lastUsedAt?: number;
57
+ /** @see PersonalAccessTokenAttributes.expiresAt */
58
+ readonly expiresAt?: number;
59
+ /** @see PersonalAccessTokenAttributes.createdAt */
60
+ readonly createdAt: number;
61
+ constructor(attributes: PersonalAccessTokenAttributes);
62
+ /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */
63
+ static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken;
64
+ /**
65
+ * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any
66
+ * other ability must match an entry exactly.
67
+ */
68
+ can(ability: string): boolean;
69
+ /** The negation of {@link can}. */
70
+ cant(ability: string): boolean;
71
+ /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */
72
+ isExpired(now: number): boolean;
73
+ /** A plain snapshot of the record, omitting any unset optional fields. */
74
+ toAttributes(): PersonalAccessTokenAttributes;
75
+ }
76
+
77
+ /**
78
+ * `TokenStore` - the persistence seam for personal access tokens.
79
+ *
80
+ * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the
81
+ * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is
82
+ * an in-memory implementation suitable for tests and ephemeral use.
83
+ */
84
+
85
+ /**
86
+ * The seam between the guard/factory and however tokens are persisted - the Sanctum
87
+ * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).
88
+ */
89
+ interface TokenStore {
90
+ /** Find a token by its id, or `undefined` if none is stored. */
91
+ find(id: string): PersonalAccessToken | undefined;
92
+ /** Persist (insert or replace) a token, keyed by its id. */
93
+ save(token: PersonalAccessToken): void;
94
+ /** Delete the token with the given id, if present. The revoke equivalent. */
95
+ delete(id: string): void;
96
+ /** Every stored token. */
97
+ all(): PersonalAccessToken[];
98
+ }
99
+ /**
100
+ * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so
101
+ * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell
102
+ * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).
103
+ */
104
+ declare function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined;
105
+ /**
106
+ * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for
107
+ * tests, fixtures, and short-lived use. Real persistence is implemented by the application.
108
+ */
109
+ declare class ArrayTokenStore implements TokenStore {
110
+ private readonly tokens;
111
+ /** Seed the store with an optional initial set of tokens. */
112
+ constructor(initial?: Iterable<PersonalAccessToken>);
113
+ find(id: string): PersonalAccessToken | undefined;
114
+ save(token: PersonalAccessToken): void;
115
+ delete(id: string): void;
116
+ all(): PersonalAccessToken[];
117
+ /** Remove every stored token. Convenience for resetting between tests. */
118
+ flush(): void;
119
+ /** The number of stored tokens. */
120
+ get size(): number;
121
+ }
122
+
123
+ /** The separator between the id and the secret in a plaintext token. */
124
+ declare const TOKEN_SEPARATOR = "|";
125
+ /**
126
+ * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the
127
+ * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and
128
+ * is shared by issuance and verification so the two stay in lockstep.
129
+ */
130
+ declare function hashSecret(secret: string): string;
131
+ /**
132
+ * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the
133
+ * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a
134
+ * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.
135
+ */
136
+ declare function parseToken(plainTextToken: string): {
137
+ id: string;
138
+ secret: string;
139
+ } | null;
140
+ /** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */
141
+ interface CreateTokenOptions {
142
+ /** A human-readable name for the token. */
143
+ name: string;
144
+ /** The abilities to grant; defaults to `['*']` (full access). */
145
+ abilities?: string[];
146
+ /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */
147
+ expiresAt?: number;
148
+ /** The owning model's primary key (`tokenable_id`). */
149
+ tokenableId?: string | number;
150
+ /** The owning model's type/morph name (`tokenable_type`). */
151
+ tokenableType?: string;
152
+ }
153
+ /** Overridable seams for {@link createToken}, primarily for deterministic tests. */
154
+ interface CreateTokenSeams {
155
+ /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */
156
+ now?: () => number;
157
+ /** Id generator; defaults to a UUID v4. */
158
+ generateId?: () => string;
159
+ /** Secret generator; defaults to 40 random bytes as hex. */
160
+ generateSecret?: () => string;
161
+ }
162
+ /**
163
+ * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is
164
+ * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the
165
+ * hash.
166
+ */
167
+ interface NewAccessToken {
168
+ /** The persisted record (hash only - no plaintext). */
169
+ accessToken: PersonalAccessToken;
170
+ /** The full plaintext token to hand to the client this one time. */
171
+ plainTextToken: string;
172
+ }
173
+ /**
174
+ * Issue a new personal access token, persist its record (hash only) to `store`, and return the
175
+ * record together with the one-time plaintext.
176
+ */
177
+ declare function createToken(store: TokenStore, options: CreateTokenOptions, seams?: CreateTokenSeams): NewAccessToken;
178
+ /** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */
179
+ declare const issueToken: (store: TokenStore, options: CreateTokenOptions, seams?: CreateTokenSeams) => NewAccessToken;
180
+
181
+ /**
182
+ * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths
183
+ * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and
184
+ * otherwise compares the bytes without short-circuiting. Used to compare token hashes.
185
+ */
186
+ declare function hashesMatch(a: string, b: string): boolean;
187
+ /**
188
+ * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a
189
+ * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.
190
+ */
191
+ declare class TokenGuard {
192
+ private readonly store;
193
+ private readonly clock;
194
+ /**
195
+ * @param store The token repository to look records up in.
196
+ * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.
197
+ */
198
+ constructor(store: TokenStore, clock?: () => number);
199
+ /**
200
+ * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the
201
+ * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`
202
+ * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.
203
+ */
204
+ authenticate(bearer: string): PersonalAccessToken | null;
205
+ /**
206
+ * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token
207
+ * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need
208
+ * the user id.
209
+ */
210
+ authenticateToken(bearer: string): string | number | null;
211
+ /** Whether `bearer` resolves to a valid, unexpired token. */
212
+ check(bearer: string): boolean;
213
+ }
214
+
215
+ /** The owning model of a set of tokens - its primary key and optional morph type. */
216
+ interface Tokenable {
217
+ /** The owner's primary key, stamped as `tokenableId` on issued tokens. */
218
+ id: string | number;
219
+ /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */
220
+ type?: string;
221
+ }
222
+ /** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */
223
+ interface HasApiTokensCreateOptions {
224
+ /** A human-readable name for the token. */
225
+ name: string;
226
+ /** The abilities to grant; defaults to `['*']`. */
227
+ abilities?: string[];
228
+ /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */
229
+ expiresAt?: number;
230
+ }
231
+ /** The owner-bound token API returned by {@link hasApiTokens}. */
232
+ interface HasApiTokens {
233
+ /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */
234
+ createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken;
235
+ /** Every stored token belonging to the bound owner. */
236
+ tokens(): PersonalAccessToken[];
237
+ /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */
238
+ tokenCan(ability: string): boolean;
239
+ }
240
+ /**
241
+ * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and
242
+ * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.
243
+ */
244
+ declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens;
245
+
246
+ /**
247
+ * @plinthjs/api-tokens - API token authentication.
248
+ *
249
+ * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.
250
+ * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is
251
+ * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and
252
+ * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in
253
+ * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.
254
+ *
255
+ * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the
256
+ * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.
257
+ */
258
+ /** The Plinth version this build of `sanctum` ships with. */
259
+ declare const VERSION = "0.1.0";
260
+
261
+ export { ArrayTokenStore, type CreateTokenOptions, type CreateTokenSeams, type HasApiTokens, type HasApiTokensCreateOptions, type NewAccessToken, PersonalAccessToken, type PersonalAccessTokenAttributes, TOKEN_SEPARATOR, TokenGuard, type TokenStore, type Tokenable, VERSION, WILDCARD_ABILITY, createToken, findToken, hasApiTokens, hashSecret, hashesMatch, issueToken, parseToken };
@@ -0,0 +1,261 @@
1
+ /**
2
+ * `PersonalAccessToken`.
3
+ *
4
+ * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash
5
+ * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what
6
+ * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard
7
+ * `'*'` grants every ability and any other ability requires an exact string match.
8
+ */
9
+ /** The wildcard ability that grants every permission, as in Sanctum. */
10
+ declare const WILDCARD_ABILITY = "*";
11
+ /**
12
+ * The persisted shape of a personal access token - the columns of Sanctum's
13
+ * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is
14
+ * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the
15
+ * record round-trips cleanly under `exactOptionalPropertyTypes`.
16
+ */
17
+ interface PersonalAccessTokenAttributes {
18
+ /** The token id - the part before the `|` in the plaintext, used to look the record up. */
19
+ id: string;
20
+ /** A human-readable name for the token (e.g. the device or integration it was issued for). */
21
+ name: string;
22
+ /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */
23
+ tokenHash: string;
24
+ /** The abilities granted to the token; `['*']` grants everything. */
25
+ abilities: string[];
26
+ /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */
27
+ tokenableId?: string | number;
28
+ /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */
29
+ tokenableType?: string;
30
+ /** Epoch milliseconds when the token was last used to authenticate, if ever. */
31
+ lastUsedAt?: number;
32
+ /** Epoch milliseconds when the token expires; absent means it never expires. */
33
+ expiresAt?: number;
34
+ /** Epoch milliseconds when the token was created. */
35
+ createdAt: number;
36
+ }
37
+ /**
38
+ * A personal access token record. Construct directly from attributes, or via
39
+ * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives
40
+ * here; persistence lives behind a `TokenStore`.
41
+ */
42
+ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
43
+ /** @see PersonalAccessTokenAttributes.id */
44
+ readonly id: string;
45
+ /** @see PersonalAccessTokenAttributes.name */
46
+ readonly name: string;
47
+ /** @see PersonalAccessTokenAttributes.tokenHash */
48
+ readonly tokenHash: string;
49
+ /** @see PersonalAccessTokenAttributes.abilities */
50
+ readonly abilities: string[];
51
+ /** @see PersonalAccessTokenAttributes.tokenableId */
52
+ readonly tokenableId?: string | number;
53
+ /** @see PersonalAccessTokenAttributes.tokenableType */
54
+ readonly tokenableType?: string;
55
+ /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
56
+ lastUsedAt?: number;
57
+ /** @see PersonalAccessTokenAttributes.expiresAt */
58
+ readonly expiresAt?: number;
59
+ /** @see PersonalAccessTokenAttributes.createdAt */
60
+ readonly createdAt: number;
61
+ constructor(attributes: PersonalAccessTokenAttributes);
62
+ /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */
63
+ static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken;
64
+ /**
65
+ * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any
66
+ * other ability must match an entry exactly.
67
+ */
68
+ can(ability: string): boolean;
69
+ /** The negation of {@link can}. */
70
+ cant(ability: string): boolean;
71
+ /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */
72
+ isExpired(now: number): boolean;
73
+ /** A plain snapshot of the record, omitting any unset optional fields. */
74
+ toAttributes(): PersonalAccessTokenAttributes;
75
+ }
76
+
77
+ /**
78
+ * `TokenStore` - the persistence seam for personal access tokens.
79
+ *
80
+ * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the
81
+ * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is
82
+ * an in-memory implementation suitable for tests and ephemeral use.
83
+ */
84
+
85
+ /**
86
+ * The seam between the guard/factory and however tokens are persisted - the Sanctum
87
+ * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).
88
+ */
89
+ interface TokenStore {
90
+ /** Find a token by its id, or `undefined` if none is stored. */
91
+ find(id: string): PersonalAccessToken | undefined;
92
+ /** Persist (insert or replace) a token, keyed by its id. */
93
+ save(token: PersonalAccessToken): void;
94
+ /** Delete the token with the given id, if present. The revoke equivalent. */
95
+ delete(id: string): void;
96
+ /** Every stored token. */
97
+ all(): PersonalAccessToken[];
98
+ }
99
+ /**
100
+ * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so
101
+ * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell
102
+ * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).
103
+ */
104
+ declare function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined;
105
+ /**
106
+ * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for
107
+ * tests, fixtures, and short-lived use. Real persistence is implemented by the application.
108
+ */
109
+ declare class ArrayTokenStore implements TokenStore {
110
+ private readonly tokens;
111
+ /** Seed the store with an optional initial set of tokens. */
112
+ constructor(initial?: Iterable<PersonalAccessToken>);
113
+ find(id: string): PersonalAccessToken | undefined;
114
+ save(token: PersonalAccessToken): void;
115
+ delete(id: string): void;
116
+ all(): PersonalAccessToken[];
117
+ /** Remove every stored token. Convenience for resetting between tests. */
118
+ flush(): void;
119
+ /** The number of stored tokens. */
120
+ get size(): number;
121
+ }
122
+
123
+ /** The separator between the id and the secret in a plaintext token. */
124
+ declare const TOKEN_SEPARATOR = "|";
125
+ /**
126
+ * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the
127
+ * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and
128
+ * is shared by issuance and verification so the two stay in lockstep.
129
+ */
130
+ declare function hashSecret(secret: string): string;
131
+ /**
132
+ * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the
133
+ * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a
134
+ * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.
135
+ */
136
+ declare function parseToken(plainTextToken: string): {
137
+ id: string;
138
+ secret: string;
139
+ } | null;
140
+ /** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */
141
+ interface CreateTokenOptions {
142
+ /** A human-readable name for the token. */
143
+ name: string;
144
+ /** The abilities to grant; defaults to `['*']` (full access). */
145
+ abilities?: string[];
146
+ /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */
147
+ expiresAt?: number;
148
+ /** The owning model's primary key (`tokenable_id`). */
149
+ tokenableId?: string | number;
150
+ /** The owning model's type/morph name (`tokenable_type`). */
151
+ tokenableType?: string;
152
+ }
153
+ /** Overridable seams for {@link createToken}, primarily for deterministic tests. */
154
+ interface CreateTokenSeams {
155
+ /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */
156
+ now?: () => number;
157
+ /** Id generator; defaults to a UUID v4. */
158
+ generateId?: () => string;
159
+ /** Secret generator; defaults to 40 random bytes as hex. */
160
+ generateSecret?: () => string;
161
+ }
162
+ /**
163
+ * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is
164
+ * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the
165
+ * hash.
166
+ */
167
+ interface NewAccessToken {
168
+ /** The persisted record (hash only - no plaintext). */
169
+ accessToken: PersonalAccessToken;
170
+ /** The full plaintext token to hand to the client this one time. */
171
+ plainTextToken: string;
172
+ }
173
+ /**
174
+ * Issue a new personal access token, persist its record (hash only) to `store`, and return the
175
+ * record together with the one-time plaintext.
176
+ */
177
+ declare function createToken(store: TokenStore, options: CreateTokenOptions, seams?: CreateTokenSeams): NewAccessToken;
178
+ /** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */
179
+ declare const issueToken: (store: TokenStore, options: CreateTokenOptions, seams?: CreateTokenSeams) => NewAccessToken;
180
+
181
+ /**
182
+ * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths
183
+ * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and
184
+ * otherwise compares the bytes without short-circuiting. Used to compare token hashes.
185
+ */
186
+ declare function hashesMatch(a: string, b: string): boolean;
187
+ /**
188
+ * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a
189
+ * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.
190
+ */
191
+ declare class TokenGuard {
192
+ private readonly store;
193
+ private readonly clock;
194
+ /**
195
+ * @param store The token repository to look records up in.
196
+ * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.
197
+ */
198
+ constructor(store: TokenStore, clock?: () => number);
199
+ /**
200
+ * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the
201
+ * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`
202
+ * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.
203
+ */
204
+ authenticate(bearer: string): PersonalAccessToken | null;
205
+ /**
206
+ * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token
207
+ * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need
208
+ * the user id.
209
+ */
210
+ authenticateToken(bearer: string): string | number | null;
211
+ /** Whether `bearer` resolves to a valid, unexpired token. */
212
+ check(bearer: string): boolean;
213
+ }
214
+
215
+ /** The owning model of a set of tokens - its primary key and optional morph type. */
216
+ interface Tokenable {
217
+ /** The owner's primary key, stamped as `tokenableId` on issued tokens. */
218
+ id: string | number;
219
+ /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */
220
+ type?: string;
221
+ }
222
+ /** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */
223
+ interface HasApiTokensCreateOptions {
224
+ /** A human-readable name for the token. */
225
+ name: string;
226
+ /** The abilities to grant; defaults to `['*']`. */
227
+ abilities?: string[];
228
+ /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */
229
+ expiresAt?: number;
230
+ }
231
+ /** The owner-bound token API returned by {@link hasApiTokens}. */
232
+ interface HasApiTokens {
233
+ /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */
234
+ createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken;
235
+ /** Every stored token belonging to the bound owner. */
236
+ tokens(): PersonalAccessToken[];
237
+ /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */
238
+ tokenCan(ability: string): boolean;
239
+ }
240
+ /**
241
+ * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and
242
+ * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.
243
+ */
244
+ declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens;
245
+
246
+ /**
247
+ * @plinthjs/api-tokens - API token authentication.
248
+ *
249
+ * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.
250
+ * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is
251
+ * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and
252
+ * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in
253
+ * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.
254
+ *
255
+ * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the
256
+ * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.
257
+ */
258
+ /** The Plinth version this build of `sanctum` ships with. */
259
+ declare const VERSION = "0.1.0";
260
+
261
+ export { ArrayTokenStore, type CreateTokenOptions, type CreateTokenSeams, type HasApiTokens, type HasApiTokensCreateOptions, type NewAccessToken, PersonalAccessToken, type PersonalAccessTokenAttributes, TOKEN_SEPARATOR, TokenGuard, type TokenStore, type Tokenable, VERSION, WILDCARD_ABILITY, createToken, findToken, hasApiTokens, hashSecret, hashesMatch, issueToken, parseToken };
package/dist/index.js ADDED
@@ -0,0 +1,233 @@
1
+ import { createHash, timingSafeEqual, randomBytes } from 'crypto';
2
+ import { uuid } from '@plinthjs/support';
3
+
4
+ // src/factory.ts
5
+
6
+ // src/token.ts
7
+ var WILDCARD_ABILITY = "*";
8
+ var PersonalAccessToken = class _PersonalAccessToken {
9
+ /** @see PersonalAccessTokenAttributes.id */
10
+ id;
11
+ /** @see PersonalAccessTokenAttributes.name */
12
+ name;
13
+ /** @see PersonalAccessTokenAttributes.tokenHash */
14
+ tokenHash;
15
+ /** @see PersonalAccessTokenAttributes.abilities */
16
+ abilities;
17
+ /** @see PersonalAccessTokenAttributes.tokenableId */
18
+ tokenableId;
19
+ /** @see PersonalAccessTokenAttributes.tokenableType */
20
+ tokenableType;
21
+ /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
22
+ lastUsedAt;
23
+ /** @see PersonalAccessTokenAttributes.expiresAt */
24
+ expiresAt;
25
+ /** @see PersonalAccessTokenAttributes.createdAt */
26
+ createdAt;
27
+ constructor(attributes) {
28
+ this.id = attributes.id;
29
+ this.name = attributes.name;
30
+ this.tokenHash = attributes.tokenHash;
31
+ this.abilities = [...attributes.abilities];
32
+ if (attributes.tokenableId !== void 0) this.tokenableId = attributes.tokenableId;
33
+ if (attributes.tokenableType !== void 0) this.tokenableType = attributes.tokenableType;
34
+ if (attributes.lastUsedAt !== void 0) this.lastUsedAt = attributes.lastUsedAt;
35
+ if (attributes.expiresAt !== void 0) this.expiresAt = attributes.expiresAt;
36
+ this.createdAt = attributes.createdAt;
37
+ }
38
+ /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */
39
+ static from(attributes) {
40
+ return new _PersonalAccessToken(attributes);
41
+ }
42
+ /**
43
+ * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any
44
+ * other ability must match an entry exactly.
45
+ */
46
+ can(ability) {
47
+ return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability);
48
+ }
49
+ /** The negation of {@link can}. */
50
+ cant(ability) {
51
+ return !this.can(ability);
52
+ }
53
+ /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */
54
+ isExpired(now) {
55
+ return this.expiresAt !== void 0 && this.expiresAt <= now;
56
+ }
57
+ /** A plain snapshot of the record, omitting any unset optional fields. */
58
+ toAttributes() {
59
+ const attributes = {
60
+ id: this.id,
61
+ name: this.name,
62
+ tokenHash: this.tokenHash,
63
+ abilities: [...this.abilities],
64
+ createdAt: this.createdAt
65
+ };
66
+ if (this.tokenableId !== void 0) attributes.tokenableId = this.tokenableId;
67
+ if (this.tokenableType !== void 0) attributes.tokenableType = this.tokenableType;
68
+ if (this.lastUsedAt !== void 0) attributes.lastUsedAt = this.lastUsedAt;
69
+ if (this.expiresAt !== void 0) attributes.expiresAt = this.expiresAt;
70
+ return attributes;
71
+ }
72
+ };
73
+
74
+ // src/factory.ts
75
+ var DEFAULT_ABILITIES = ["*"];
76
+ var SECRET_BYTES = 40;
77
+ var TOKEN_SEPARATOR = "|";
78
+ function hashSecret(secret) {
79
+ return createHash("sha256").update(secret).digest("hex");
80
+ }
81
+ function parseToken(plainTextToken) {
82
+ const index = plainTextToken.indexOf(TOKEN_SEPARATOR);
83
+ if (index <= 0) return null;
84
+ const id = plainTextToken.slice(0, index);
85
+ const secret = plainTextToken.slice(index + 1);
86
+ if (secret.length === 0) return null;
87
+ return { id, secret };
88
+ }
89
+ function generateSecret() {
90
+ return randomBytes(SECRET_BYTES).toString("hex");
91
+ }
92
+ function createToken(store, options, seams) {
93
+ const now = (seams?.now ?? Date.now)();
94
+ const id = (seams?.generateId ?? uuid)();
95
+ const secret = (seams?.generateSecret ?? generateSecret)();
96
+ const abilities = options.abilities ?? [...DEFAULT_ABILITIES];
97
+ const attributes = {
98
+ id,
99
+ name: options.name,
100
+ tokenHash: hashSecret(secret),
101
+ abilities,
102
+ createdAt: now
103
+ };
104
+ if (options.tokenableId !== void 0) attributes.tokenableId = options.tokenableId;
105
+ if (options.tokenableType !== void 0) attributes.tokenableType = options.tokenableType;
106
+ if (options.expiresAt !== void 0) attributes.expiresAt = options.expiresAt;
107
+ const accessToken = new PersonalAccessToken(attributes);
108
+ store.save(accessToken);
109
+ return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` };
110
+ }
111
+ var issueToken = createToken;
112
+
113
+ // src/store.ts
114
+ function findToken(store, id) {
115
+ return store.find(id);
116
+ }
117
+ var ArrayTokenStore = class {
118
+ tokens = /* @__PURE__ */ new Map();
119
+ /** Seed the store with an optional initial set of tokens. */
120
+ constructor(initial) {
121
+ if (initial !== void 0) {
122
+ for (const token of initial) this.tokens.set(token.id, token);
123
+ }
124
+ }
125
+ find(id) {
126
+ return this.tokens.get(id);
127
+ }
128
+ save(token) {
129
+ this.tokens.set(token.id, token);
130
+ }
131
+ delete(id) {
132
+ this.tokens.delete(id);
133
+ }
134
+ all() {
135
+ return [...this.tokens.values()];
136
+ }
137
+ /** Remove every stored token. Convenience for resetting between tests. */
138
+ flush() {
139
+ this.tokens.clear();
140
+ }
141
+ /** The number of stored tokens. */
142
+ get size() {
143
+ return this.tokens.size;
144
+ }
145
+ };
146
+
147
+ // src/guard.ts
148
+ function hashesMatch(a, b) {
149
+ const left = Buffer.from(a, "utf8");
150
+ const right = Buffer.from(b, "utf8");
151
+ if (left.length !== right.length) return false;
152
+ return timingSafeEqual(left, right);
153
+ }
154
+ var TokenGuard = class {
155
+ store;
156
+ clock;
157
+ /**
158
+ * @param store The token repository to look records up in.
159
+ * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.
160
+ */
161
+ constructor(store, clock) {
162
+ this.store = store;
163
+ this.clock = clock ?? Date.now;
164
+ }
165
+ /**
166
+ * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the
167
+ * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`
168
+ * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.
169
+ */
170
+ authenticate(bearer) {
171
+ const parts = parseToken(bearer);
172
+ if (parts === null) return null;
173
+ const { id, secret } = parts;
174
+ const token = findToken(this.store, id);
175
+ if (token === void 0) return null;
176
+ if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null;
177
+ const now = this.clock();
178
+ if (token.isExpired(now)) return null;
179
+ token.lastUsedAt = now;
180
+ this.store.save(token);
181
+ return token;
182
+ }
183
+ /**
184
+ * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token
185
+ * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need
186
+ * the user id.
187
+ */
188
+ authenticateToken(bearer) {
189
+ const token = this.authenticate(bearer);
190
+ if (token === null) return null;
191
+ return token.tokenableId ?? null;
192
+ }
193
+ /** Whether `bearer` resolves to a valid, unexpired token. */
194
+ check(bearer) {
195
+ return this.authenticate(bearer) !== null;
196
+ }
197
+ };
198
+
199
+ // src/has-api-tokens.ts
200
+ function ownedBy(token, owner) {
201
+ if (token.tokenableId !== owner.id) return false;
202
+ if (owner.type === void 0) return true;
203
+ return token.tokenableType === owner.type;
204
+ }
205
+ function hasApiTokens(store, owner) {
206
+ return {
207
+ createToken(options, seams) {
208
+ const base = {
209
+ name: options.name,
210
+ tokenableId: owner.id
211
+ };
212
+ if (options.abilities !== void 0) base.abilities = options.abilities;
213
+ if (options.expiresAt !== void 0) base.expiresAt = options.expiresAt;
214
+ if (owner.type !== void 0) base.tokenableType = owner.type;
215
+ return createToken(store, base, seams);
216
+ },
217
+ tokens() {
218
+ return store.all().filter((token) => ownedBy(token, owner));
219
+ },
220
+ tokenCan(ability) {
221
+ return store.all().some(
222
+ (token) => ownedBy(token, owner) && (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability))
223
+ );
224
+ }
225
+ };
226
+ }
227
+
228
+ // src/index.ts
229
+ var VERSION = "0.1.0";
230
+
231
+ export { ArrayTokenStore, PersonalAccessToken, TOKEN_SEPARATOR, TokenGuard, VERSION, WILDCARD_ABILITY, createToken, findToken, hasApiTokens, hashSecret, hashesMatch, issueToken, parseToken };
232
+ //# sourceMappingURL=index.js.map
233
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/token.ts","../src/factory.ts","../src/store.ts","../src/guard.ts","../src/has-api-tokens.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAUO,IAAM,gBAAA,GAAmB;AAkCzB,IAAM,mBAAA,GAAN,MAAM,oBAAA,CAA6D;AAAA;AAAA,EAE/D,EAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA,EAEA,aAAA;AAAA;AAAA,EAET,UAAA;AAAA;AAAA,EAES,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,YAAY,UAAA,EAA2C;AACrD,IAAA,IAAA,CAAK,KAAK,UAAA,CAAW,EAAA;AACrB,IAAA,IAAA,CAAK,OAAO,UAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,YAAY,UAAA,CAAW,SAAA;AAC5B,IAAA,IAAA,CAAK,SAAA,GAAY,CAAC,GAAG,UAAA,CAAW,SAAS,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O,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token - the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id - the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme - the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret - the part AFTER the `|` - with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified - full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only - no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` - the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted - the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` - authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens - its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens - API token authentication.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@plinthjs/api-tokens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "Plinth API token authentication.",
5
+ "keywords": [
6
+ "plinth",
7
+ "framework",
8
+ "typescript",
9
+ "api-tokens"
10
+ ],
11
+ "homepage": "https://github.com/anilkumarthakur60/plinthjs/tree/main/packages/api-tokens#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/anilkumarthakur60/plinthjs/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/anilkumarthakur60/plinthjs.git",
18
+ "directory": "packages/api-tokens"
19
+ },
20
+ "license": "MIT",
21
+ "author": "Er. Anil Kumar Thakur",
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js",
31
+ "require": "./dist/index.cjs"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "main": "./dist/index.cjs",
36
+ "module": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "@plinthjs/support": "^0.1.2",
46
+ "@plinthjs/contracts": "^0.1.2"
47
+ },
48
+ "devDependencies": {
49
+ "tsup": "^8.3.5",
50
+ "typescript": "^5.7.2",
51
+ "vitest": "^3.0.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "dev": "tsup --watch",
56
+ "test": "vitest run",
57
+ "typecheck": "tsc --noEmit",
58
+ "clean": "rm -rf dist .turbo *.tsbuildinfo"
59
+ }
6
60
  }