-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.ts
193 lines (175 loc) · 5.15 KB
/
auth.ts
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2022-2024 Kitson P. Kelly. All rights reserved. MIT License
/**
* Handles managing auth against GCP.
*
* @module
*/
import { importPKCS8, SignJWT } from "jose";
import { assert } from "@std/assert/assert";
import { DatastoreError } from "./error.ts";
export interface ServiceAccountJSON {
client_email: string;
private_key: string;
private_key_id: string;
}
const ALG = "RS256";
interface OAuth2TokenJson {
access_token: string;
scope?: string;
token_type: string;
expires_in: number;
}
/** A class that wraps the response from the Google APIs OAuth2 token service. */
export class OAuth2Token {
#created = Date.now();
#json: OAuth2TokenJson;
/** The raw access token string. */
get accessToken(): string {
return this.#json.access_token;
}
/** Returns if the `true` if the token has expired, otherwise `false`. */
get expired(): boolean {
return this.expiresIn <= 0;
}
/** The number of seconds until the token expires. If less than or equal to 0
* then the token has expired. */
get expiresIn(): number {
return (this.#created + (this.#json.expires_in * 1000)) - Date.now();
}
/** Any scopes returned in the authorization response. */
get scope(): string | undefined {
return this.#json.scope;
}
/** The type of token that was returned. */
get tokenType(): string {
return this.#json.token_type;
}
constructor(json: OAuth2TokenJson) {
this.#json = json;
}
/** Returns the token as a value for an `Authorization:` header. */
toString(): string {
return `${this.#json.token_type} ${this.#json.access_token}`;
}
}
/** Generates an OAuth2 token against Google APIs for the provided service
* account and scopes. Provides an instance of {@linkcode OAuth2Token} that
* wraps the response from Google API OAuth2 service.
*
* @example
*
* ```ts
* import { createOAuth2Token } from "https://deno.land/x/deno_gcp_admin/auth.ts";
* import keys from "./service-account.json" asserts { type: "json" };
*
* const token = await createOAuth2Token(
* keys,
* "https://www.googleapis.com/auth/cloud-platform"
* );
*
* const response = fetch("https://example.googleapis.com/", {
* headers: {
* authorization: token.toString(),
* }
* });
* ```
*
* @param json A JSON object representing the data from a service account JSON
* file obtained from Google Cloud.
* @param scopes [Scopes](https://developers.google.com/identity/protocols/oauth2/scopes)
* that the authorization is being requested for.
*/
export async function createOAuth2Token(
json: ServiceAccountJSON,
...scopes: string[]
): Promise<OAuth2Token> {
const AUD = "https://oauth2.googleapis.com/token";
const key = await importPKCS8(json.private_key, ALG);
const jwt = await new SignJWT({
scope: scopes.join(" "),
})
.setProtectedHeader({ alg: ALG })
.setIssuer(json.client_email)
.setSubject(json.client_email)
.setAudience(AUD)
.setIssuedAt()
.setExpirationTime("1h")
.sign(key);
const res = await fetch(AUD, {
method: "POST",
body: new URLSearchParams([[
"grant_type",
"urn:ietf:params:oauth:grant-type:jwt-bearer",
], ["assertion", jwt]]),
headers: { "content-type": "application/x-www-form-urlencoded" },
});
assert(
res.status === 200,
`Unexpected authorization response ${res.status} - ${res.statusText}.`,
);
return new OAuth2Token(await res.json());
}
/** Generates a custom token that can be used with Firebase's
* `signInWithCustomToken()` API. */
export async function createCustomToken(
json: ServiceAccountJSON,
claims?: Record<string, unknown>,
): Promise<string> {
const AUD =
"https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";
const key = await importPKCS8(json.private_key, ALG);
return new SignJWT({
uid: json.private_key_id,
claims,
})
.setProtectedHeader({ alg: ALG })
.setIssuer(json.client_email)
.setSubject(json.client_email)
.setAudience(AUD)
.setIssuedAt()
.setExpirationTime("1h")
.sign(key);
}
interface AuthInit {
client_email: string;
private_key: string;
private_key_id: string;
project_id: string;
datastore_host?: string;
}
export class Auth {
#tokenPromise: Promise<OAuth2Token> | undefined;
init: AuthInit;
token?: OAuth2Token;
scopes: string;
host: string;
constructor(init: AuthInit, scopes: string) {
this.init = init;
this.scopes = scopes;
this.host = init.datastore_host ?? "https://datastore.googleapis.com";
}
get baseEndpoint(): string {
return `${this.host}/v1/projects/${this.init.project_id}`;
}
async setToken(): Promise<OAuth2Token | undefined> {
if (this.init.datastore_host) {
return;
}
if (this.#tokenPromise) {
return this.#tokenPromise;
}
this.#tokenPromise = createOAuth2Token(this.init, this.scopes);
try {
this.token = await this.#tokenPromise;
this.#tokenPromise = undefined;
return this.token;
} catch (cause) {
throw new DatastoreError(
`Error setting token: ${
cause instanceof Error ? cause.message : "Unknown"
}`,
{ cause },
);
}
}
}