@neon-pixels/api-keys 0.0.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +69 -0
- package/dist/index.d.ts +71 -0
- package/dist/index.js +128 -0
- package/package.json +32 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Neon Pixels Studio
|
|
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
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @neon-pixels/api-keys
|
|
2
|
+
|
|
3
|
+
The mechanics of personal API keys: generate, hash, verify, expire, and scope. It has no database or framework dependency and uses only Node's built-in `crypto`. Your app owns the table, the queries, and the routes.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @neon-pixels/api-keys
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import {
|
|
15
|
+
computeExpiresAt,
|
|
16
|
+
generateApiKey,
|
|
17
|
+
normalizeScopes,
|
|
18
|
+
verifyApiKey,
|
|
19
|
+
} from "@neon-pixels/api-keys";
|
|
20
|
+
|
|
21
|
+
const MARKER = "mp_live_";
|
|
22
|
+
const SCOPES = ["records:read", "records:write"];
|
|
23
|
+
|
|
24
|
+
// Create: store prefix and keyHash (and scopes, expiresAt); show key once.
|
|
25
|
+
const { key, prefix, keyHash } = generateApiKey({ marker: MARKER });
|
|
26
|
+
const scopes = normalizeScopes(["records:read"], SCOPES);
|
|
27
|
+
const expiresAt = computeExpiresAt(90);
|
|
28
|
+
|
|
29
|
+
// Authenticate a bearer token.
|
|
30
|
+
const result = await verifyApiKey({
|
|
31
|
+
token,
|
|
32
|
+
marker: MARKER,
|
|
33
|
+
findByHash: (hash) => db.findApiKeyByHash(hash),
|
|
34
|
+
});
|
|
35
|
+
if (!result.valid) {
|
|
36
|
+
// result.reason is "unknown", "revoked", or "expired"
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Keys
|
|
41
|
+
|
|
42
|
+
- `generateApiKey({ marker })` returns `{ key, prefix, keyHash }`. The key is the marker followed by 32 random bytes, base64url encoded. `prefix` is the first 12 characters of the key, marker included, and is safe to store and display. The marker must be non-empty and shorter than 12 characters so the prefix includes random characters.
|
|
43
|
+
- `hashApiKey(key)` returns the SHA-256 hex digest. Store only the hash: the raw key exists once, in the return value of `generateApiKey`.
|
|
44
|
+
- `hasMarker(token, marker)` tells an API key apart from any other bearer token.
|
|
45
|
+
|
|
46
|
+
### Verifying
|
|
47
|
+
|
|
48
|
+
`verifyApiKey({ token, marker, findByHash, now? })` returns a promise of `{ valid: true, record }` or `{ valid: false, reason }`. Reasons are checked in this order: `unknown` (no marker, or no record), `revoked`, `expired`. `findByHash` receives the hash, never the raw token, and may be sync or async. The record may carry `revokedAt` and `expiresAt`; convert stored values to `Date` in `findByHash` (a non-`Date` `expiresAt` is treated as expired). An invalid key never throws (a missing or invalid `marker` does, so a misconfiguration is loud rather than rejecting every key), and the token is never logged or returned. Errors thrown by `findByHash` (for example a database outage) propagate.
|
|
49
|
+
|
|
50
|
+
### Expiry and last-used
|
|
51
|
+
|
|
52
|
+
- `computeExpiresAt(days, now?)` returns a `Date` for a whole number of days from 1 to 3650, or `null` when `days` is omitted (no expiry). Anything else throws a `RangeError`.
|
|
53
|
+
- `isExpired(expiresAt, now?)` is `false` for `null`, and `true` at and after the expiry instant.
|
|
54
|
+
- `isLastUsedStale(lastUsedAt, now?, intervalMs?)` is `true` when the key was never used, was last used at least `intervalMs` ago (default 5 minutes), or the timestamp is unreadable or in the future (clock skew). A negative or `NaN` `intervalMs` throws a `RangeError`. Use it to write `lastUsedAt` at most once per interval.
|
|
55
|
+
|
|
56
|
+
### Scopes
|
|
57
|
+
|
|
58
|
+
Scopes are part of every key. Your app passes its own scope list; a key always has an explicit, non-empty scope array; there is no value that means full access.
|
|
59
|
+
|
|
60
|
+
- `normalizeScopes(input, knownScopes)` returns the scopes de-duplicated in first-seen order, or throws `InvalidScopesError` for a missing, empty, non-array, or unknown-scope input.
|
|
61
|
+
- `hasScope(granted, required)` checks one required scope.
|
|
62
|
+
- `isScopeSubset(requested, granted)` is `true` when a key may mint or update another key with `requested` scopes. Call it with the caller's scopes as `granted`.
|
|
63
|
+
- `readOnlyScopes(knownScopes)` returns the scopes ending in `:read`, for issuing a key that cannot write.
|
|
64
|
+
|
|
65
|
+
Name scopes `<resource>:read` and `<resource>:write` (for example `records:read`). `readOnlyScopes` relies on that naming.
|
|
66
|
+
|
|
67
|
+
## Notes
|
|
68
|
+
|
|
69
|
+
Existing keys are not touched by this package. If your app already issues keys in another format (for example hex instead of base64url), it keeps verifying them by hashing the presented token, which `verifyApiKey` does for any token that starts with the marker.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export declare const MIN_EXPIRY_DAYS = 1;
|
|
2
|
+
export declare const MAX_EXPIRY_DAYS = 3650;
|
|
3
|
+
export declare const DEFAULT_LAST_USED_INTERVAL_MS: number;
|
|
4
|
+
/**
|
|
5
|
+
* Returns the expiry date for a key valid for `days` days, or `null` for a key
|
|
6
|
+
* that never expires (`days` is `undefined` or `null`). Throws a `RangeError`
|
|
7
|
+
* for anything else outside the whole numbers 1 to 3650.
|
|
8
|
+
*/
|
|
9
|
+
export declare function computeExpiresAt(days: number | null | undefined, now?: Date): Date | null;
|
|
10
|
+
/** A key with no expiry (`null` or `undefined`) is never expired. */
|
|
11
|
+
export declare function isExpired(expiresAt: Date | null | undefined, now?: Date): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* True when the last-used timestamp is missing, unreadable, in the future, or older than `intervalMs`, so
|
|
14
|
+
* the app only writes it at most once per interval.
|
|
15
|
+
*/
|
|
16
|
+
export declare function isLastUsedStale(lastUsedAt: Date | null | undefined, now?: Date, intervalMs?: number): boolean;
|
|
17
|
+
export declare const KEY_PREFIX_LENGTH = 12;
|
|
18
|
+
type GeneratedApiKey = {
|
|
19
|
+
/** The raw key. Show it to the user once; never store it. */
|
|
20
|
+
key: string;
|
|
21
|
+
/** First 12 characters of the key, marker included. Safe to store and display. */
|
|
22
|
+
prefix: string;
|
|
23
|
+
/** SHA-256 hex digest of the key. This is what you store and look up. */
|
|
24
|
+
keyHash: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function hashApiKey(key: string): string;
|
|
27
|
+
export declare function hasMarker(token: string, marker: string): boolean;
|
|
28
|
+
export declare function generateApiKey({ marker }: {
|
|
29
|
+
marker: string;
|
|
30
|
+
}): GeneratedApiKey;
|
|
31
|
+
export declare class InvalidScopesError extends Error {
|
|
32
|
+
constructor(message: string);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Validates a requested scope list against the app's known scopes and returns
|
|
36
|
+
* it de-duplicated, in first-seen order. There is no "all scopes" value: an
|
|
37
|
+
* omitted, empty, non-array, or unknown-scope input throws `InvalidScopesError`.
|
|
38
|
+
*/
|
|
39
|
+
export declare function normalizeScopes(input: unknown, knownScopes: readonly string[]): string[];
|
|
40
|
+
export declare function hasScope(granted: readonly string[], required: string): boolean;
|
|
41
|
+
/** True when every requested scope is in `granted`: a key cannot mint a broader key. */
|
|
42
|
+
export declare function isScopeSubset(requested: readonly string[], granted: readonly string[]): boolean;
|
|
43
|
+
/** The known scopes named `<resource>:read`, for issuing a key that cannot write. */
|
|
44
|
+
export declare function readOnlyScopes(knownScopes: readonly string[]): string[];
|
|
45
|
+
type ApiKeyRecord = {
|
|
46
|
+
revokedAt?: Date | null;
|
|
47
|
+
expiresAt?: Date | null;
|
|
48
|
+
};
|
|
49
|
+
type InvalidReason = "unknown" | "revoked" | "expired";
|
|
50
|
+
type VerifyResult<TRecord> = {
|
|
51
|
+
valid: true;
|
|
52
|
+
record: TRecord;
|
|
53
|
+
} | {
|
|
54
|
+
valid: false;
|
|
55
|
+
reason: InvalidReason;
|
|
56
|
+
};
|
|
57
|
+
type VerifyApiKeyOptions<TRecord extends ApiKeyRecord> = {
|
|
58
|
+
token: string;
|
|
59
|
+
marker: string;
|
|
60
|
+
/** Looks up the stored record by SHA-256 hash. Return `null` when none exists. */
|
|
61
|
+
findByHash: (keyHash: string) => Promise<TRecord | null> | TRecord | null;
|
|
62
|
+
now?: Date;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Hashes the token, calls the app's lookup, and classifies the result. Invalid
|
|
66
|
+
* keys never throw (a misconfigured marker does, so a misconfiguration is
|
|
67
|
+
* loud); errors thrown by `findByHash` itself propagate. The raw
|
|
68
|
+
* token is never logged or returned.
|
|
69
|
+
*/
|
|
70
|
+
export declare function verifyApiKey<TRecord extends ApiKeyRecord>({ token, marker, findByHash, now }: VerifyApiKeyOptions<TRecord>): Promise<VerifyResult<TRecord>>;
|
|
71
|
+
export type { ApiKeyRecord, GeneratedApiKey, InvalidReason, VerifyApiKeyOptions, VerifyResult };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
// src/expiry.ts
|
|
3
|
+
const MIN_EXPIRY_DAYS = 1;
|
|
4
|
+
const MAX_EXPIRY_DAYS = 3650;
|
|
5
|
+
const MILLISECONDS_PER_DAY = 864e5;
|
|
6
|
+
const DEFAULT_LAST_USED_INTERVAL_MS = 3e5;
|
|
7
|
+
function assertValidNow(now) {
|
|
8
|
+
if (!(now instanceof Date) || Number.isNaN(now.getTime())) throw new RangeError("now must be a valid Date");
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Returns the expiry date for a key valid for `days` days, or `null` for a key
|
|
12
|
+
* that never expires (`days` is `undefined` or `null`). Throws a `RangeError`
|
|
13
|
+
* for anything else outside the whole numbers 1 to 3650.
|
|
14
|
+
*/
|
|
15
|
+
function computeExpiresAt(days, now = /* @__PURE__ */ new Date()) {
|
|
16
|
+
assertValidNow(now);
|
|
17
|
+
if (days === void 0 || days === null) return null;
|
|
18
|
+
if (!(Number.isInteger(days) && days >= 1 && days <= 3650)) throw new RangeError(`days must be a whole number from 1 to ${MAX_EXPIRY_DAYS}, or omitted for no expiry`);
|
|
19
|
+
return new Date(now.getTime() + days * MILLISECONDS_PER_DAY);
|
|
20
|
+
}
|
|
21
|
+
/** A key with no expiry (`null` or `undefined`) is never expired. */
|
|
22
|
+
function isExpired(expiresAt, now = /* @__PURE__ */ new Date()) {
|
|
23
|
+
assertValidNow(now);
|
|
24
|
+
if (expiresAt === null || expiresAt === void 0) return false;
|
|
25
|
+
if (!(expiresAt instanceof Date)) return true;
|
|
26
|
+
const expiresAtMs = expiresAt.getTime();
|
|
27
|
+
if (Number.isNaN(expiresAtMs)) return true;
|
|
28
|
+
return expiresAtMs <= now.getTime();
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* True when the last-used timestamp is missing, unreadable, in the future, or older than `intervalMs`, so
|
|
32
|
+
* the app only writes it at most once per interval.
|
|
33
|
+
*/
|
|
34
|
+
function isLastUsedStale(lastUsedAt, now = /* @__PURE__ */ new Date(), intervalMs = DEFAULT_LAST_USED_INTERVAL_MS) {
|
|
35
|
+
assertValidNow(now);
|
|
36
|
+
if (!(intervalMs >= 0)) throw new RangeError("intervalMs must be a number of 0 or more");
|
|
37
|
+
if (!(lastUsedAt instanceof Date)) return true;
|
|
38
|
+
const elapsedMs = now.getTime() - lastUsedAt.getTime();
|
|
39
|
+
if (Number.isNaN(elapsedMs) || elapsedMs < 0) return true;
|
|
40
|
+
return elapsedMs >= intervalMs;
|
|
41
|
+
}
|
|
42
|
+
const KEY_PREFIX_LENGTH = 12;
|
|
43
|
+
const HASH_ALGORITHM = "sha256";
|
|
44
|
+
function hashApiKey(key) {
|
|
45
|
+
return createHash(HASH_ALGORITHM).update(key).digest("hex");
|
|
46
|
+
}
|
|
47
|
+
function hasMarker(token, marker) {
|
|
48
|
+
return typeof token === "string" && typeof marker === "string" && marker.length > 0 && token.startsWith(marker);
|
|
49
|
+
}
|
|
50
|
+
function assertValidMarker(marker) {
|
|
51
|
+
if (typeof marker !== "string" || marker.length === 0) throw new TypeError("marker must be a non-empty string");
|
|
52
|
+
if (marker.length >= 12) throw new RangeError(`marker must be shorter than 12 characters so the stored prefix includes random characters`);
|
|
53
|
+
}
|
|
54
|
+
function generateApiKey({ marker }) {
|
|
55
|
+
assertValidMarker(marker);
|
|
56
|
+
const key = `${marker}${randomBytes(32).toString("base64url")}`;
|
|
57
|
+
return {
|
|
58
|
+
key,
|
|
59
|
+
prefix: key.slice(0, 12),
|
|
60
|
+
keyHash: hashApiKey(key)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// src/scopes.ts
|
|
64
|
+
const READ_SCOPE_SUFFIX = ":read";
|
|
65
|
+
var InvalidScopesError = class extends Error {
|
|
66
|
+
constructor(message) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = "InvalidScopesError";
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Validates a requested scope list against the app's known scopes and returns
|
|
73
|
+
* it de-duplicated, in first-seen order. There is no "all scopes" value: an
|
|
74
|
+
* omitted, empty, non-array, or unknown-scope input throws `InvalidScopesError`.
|
|
75
|
+
*/
|
|
76
|
+
function normalizeScopes(input, knownScopes) {
|
|
77
|
+
if (!Array.isArray(input) || input.length === 0) throw new InvalidScopesError("scopes must be a non-empty array");
|
|
78
|
+
const requested = Array.from(input);
|
|
79
|
+
if (requested.some((scope) => typeof scope !== "string")) throw new InvalidScopesError("scopes must be strings");
|
|
80
|
+
const unknownScopes = requested.filter((scope) => !knownScopes.includes(scope));
|
|
81
|
+
if (unknownScopes.length > 0) throw new InvalidScopesError(`unknown scopes: ${unknownScopes.join(", ")}`);
|
|
82
|
+
return Array.from(new Set(requested));
|
|
83
|
+
}
|
|
84
|
+
function hasScope(granted, required) {
|
|
85
|
+
if (!Array.isArray(granted)) return false;
|
|
86
|
+
return granted.includes(required);
|
|
87
|
+
}
|
|
88
|
+
/** True when every requested scope is in `granted`: a key cannot mint a broader key. */
|
|
89
|
+
function isScopeSubset(requested, granted) {
|
|
90
|
+
if (!Array.isArray(requested) || !Array.isArray(granted)) return false;
|
|
91
|
+
return requested.every((scope) => granted.includes(scope));
|
|
92
|
+
}
|
|
93
|
+
/** The known scopes named `<resource>:read`, for issuing a key that cannot write. */
|
|
94
|
+
function readOnlyScopes(knownScopes) {
|
|
95
|
+
return knownScopes.filter((scope) => scope.endsWith(READ_SCOPE_SUFFIX));
|
|
96
|
+
}
|
|
97
|
+
// src/verify.ts
|
|
98
|
+
/**
|
|
99
|
+
* Hashes the token, calls the app's lookup, and classifies the result. Invalid
|
|
100
|
+
* keys never throw (a misconfigured marker does, so a misconfiguration is
|
|
101
|
+
* loud); errors thrown by `findByHash` itself propagate. The raw
|
|
102
|
+
* token is never logged or returned.
|
|
103
|
+
*/
|
|
104
|
+
async function verifyApiKey({ token, marker, findByHash, now = /* @__PURE__ */ new Date() }) {
|
|
105
|
+
assertValidMarker(marker);
|
|
106
|
+
if (!hasMarker(token, marker)) return {
|
|
107
|
+
valid: false,
|
|
108
|
+
reason: "unknown"
|
|
109
|
+
};
|
|
110
|
+
const record = await findByHash(hashApiKey(token));
|
|
111
|
+
if (!record) return {
|
|
112
|
+
valid: false,
|
|
113
|
+
reason: "unknown"
|
|
114
|
+
};
|
|
115
|
+
if (record.revokedAt !== null && record.revokedAt !== void 0) return {
|
|
116
|
+
valid: false,
|
|
117
|
+
reason: "revoked"
|
|
118
|
+
};
|
|
119
|
+
if (isExpired(record.expiresAt, now)) return {
|
|
120
|
+
valid: false,
|
|
121
|
+
reason: "expired"
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
valid: true,
|
|
125
|
+
record
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export { DEFAULT_LAST_USED_INTERVAL_MS, InvalidScopesError, KEY_PREFIX_LENGTH, MAX_EXPIRY_DAYS, MIN_EXPIRY_DAYS, computeExpiresAt, generateApiKey, hasMarker, hasScope, hashApiKey, isExpired, isLastUsedStale, isScopeSubset, normalizeScopes, readOnlyScopes, verifyApiKey };
|
package/package.json
CHANGED
|
@@ -1 +1,32 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@neon-pixels/api-keys",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "API token mechanics: generate, hash, verify, expire, and scope personal API keys.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/neonpixels-studio/packages.git",
|
|
10
|
+
"directory": "packages/api-keys"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": "^22.17.0 || ^24.0.0 || >=26.0.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsdown",
|
|
30
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
31
|
+
}
|
|
32
|
+
}
|