-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestSdkUtilities.js
More file actions
158 lines (130 loc) · 5.48 KB
/
testSdkUtilities.js
File metadata and controls
158 lines (130 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import {
BaseAuthStore,
cookieParse,
cookieSerialize,
serializeQueryParams,
normalizeUnknownQueryParams,
getTokenPayload,
isTokenExpired,
} from "bosbase";
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function createToken(payload) {
const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
return `${header}.${body}.sig`;
}
function testQueryHelpers() {
console.log("[INFO] Testing query helpers serializeQueryParams/normalizeUnknownQueryParams...");
const options = {
method: "PATCH",
headers: { "X-Test": "normalize" },
existing: "should move",
nested: { foo: "bar" },
query: { keep: true },
params: { legacy: true },
};
normalizeUnknownQueryParams(options);
assert(!("existing" in options) && !("nested" in options), "Unknown keys should move into query");
assert(options.query.keep === true, "Existing query entries should remain");
assert(options.params.legacy === true, "Existing params entries should remain in params");
assert(options.query.existing === "should move", "Moved key should appear under query");
assert(options.query.nested?.foo === "bar", "Nested values should be preserved when moved");
const date = new Date("2024-06-30T12:00:00Z");
const query = serializeQueryParams({
page: 2,
tags: ["a", "b"],
when: date,
meta: { ok: true },
nil: null,
undef: undefined,
});
assert(query.includes("page=2"), "Numeric values should be serialized");
assert(query.includes("tags=a") && query.includes("tags=b"), "Array values should repeat per entry");
assert(
query.includes(encodeURIComponent(date.toISOString().replace("T", " "))),
"Dates should be formatted and url-encoded",
);
assert(query.includes("meta=" + encodeURIComponent(JSON.stringify({ ok: true }))), "Objects should be JSON encoded");
assert(!query.includes("nil=") && !query.includes("undef="), "Nullish values should be skipped");
console.log("[SUCCESS] Query helper utilities serialize as expected");
}
function testCookieHelpers() {
console.log("[INFO] Testing cookieParse/cookieSerialize helpers...");
const serialized = cookieSerialize("session", "abc123", {
path: "/",
httpOnly: true,
sameSite: "lax",
maxAge: 120,
});
const parsed = cookieParse(serialized);
assert(parsed.session === "abc123", "cookieParse should extract serialized cookie value");
const multi = cookieParse('foo=bar; encoded=%7B%22a%22%3A1%7D; quoted="hello world"');
assert(multi.foo === "bar", "cookieParse should decode simple pairs");
const parsedEncoded = JSON.parse(multi.encoded);
assert(parsedEncoded?.a === 1, "cookieParse should decode percent-encoded JSON values");
assert(multi.quoted === "hello world", "cookieParse should handle quoted values");
console.log("[SUCCESS] Cookie helpers parse and serialize correctly");
}
function testJwtHelpers() {
console.log("[INFO] Testing getTokenPayload/isTokenExpired helpers...");
const freshExp = Math.floor(Date.now() / 1000) + 120;
const freshToken = createToken({
exp: freshExp,
type: "auth",
collectionId: "pbc_3142635823",
collectionName: "_superusers",
});
const payload = getTokenPayload(freshToken);
assert(payload.collectionId === "pbc_3142635823", "getTokenPayload should decode token payload");
assert(!isTokenExpired(freshToken), "Fresh token should not be treated as expired");
assert(isTokenExpired(freshToken, 200), "Token should respect expiration threshold subtraction");
const invalidPayload = getTokenPayload("not-a-token");
assert(Object.keys(invalidPayload).length === 0, "Invalid token should produce empty payload");
assert(isTokenExpired("not-a-token"), "Invalid tokens should be treated as expired");
console.log("[SUCCESS] JWT helpers decode payloads and detect expiration");
}
function testAuthStoreFlags() {
console.log("[INFO] Testing BaseAuthStore isValid/isSuperuser/isAuthRecord flags...");
const store = new BaseAuthStore();
const superToken = createToken({
exp: Math.floor(Date.now() / 1000) + 60,
type: "auth",
collectionId: "pbc_3142635823",
});
store.save(superToken, { id: "sup1", collectionName: "_superusers" });
assert(store.isValid, "Superuser token should be considered valid before expiry");
assert(store.isSuperuser, "Superuser detection should respect collectionId/collectionName");
const userToken = createToken({
exp: Math.floor(Date.now() / 1000) + 60,
type: "auth",
collectionId: "pbc_users",
});
store.save(userToken, { id: "u1", collectionName: "users" });
assert(!store.isSuperuser, "Regular auth record should not be flagged as superuser");
assert(store.isAuthRecord, "isAuthRecord should return true for non-superuser auth tokens");
const expiredToken = createToken({
exp: Math.floor(Date.now() / 1000) - 10,
type: "auth",
});
store.save(expiredToken, { id: "u1", collectionName: "users" });
assert(!store.isValid, "Expired token should flip isValid to false");
console.log("[SUCCESS] Auth store flags respond to token state as expected");
}
async function main() {
try {
testQueryHelpers();
testCookieHelpers();
testJwtHelpers();
testAuthStoreFlags();
console.log("\n========== SDK utility helper tests completed ==========");
} catch (error) {
console.error("[ERROR] SDK utility helper test failed:");
console.error(error?.stack || error);
process.exit(1);
}
}
main();